Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/clang/lib/Sema/SemaExprCXX.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
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
/// \file
10
/// Implements semantic analysis for C++ expressions.
11
///
12
//===----------------------------------------------------------------------===//
13
14
#include "TreeTransform.h"
15
#include "TypeLocBuilder.h"
16
#include "clang/AST/ASTContext.h"
17
#include "clang/AST/ASTLambda.h"
18
#include "clang/AST/CXXInheritance.h"
19
#include "clang/AST/CharUnits.h"
20
#include "clang/AST/DeclObjC.h"
21
#include "clang/AST/ExprCXX.h"
22
#include "clang/AST/ExprConcepts.h"
23
#include "clang/AST/ExprObjC.h"
24
#include "clang/AST/RecursiveASTVisitor.h"
25
#include "clang/AST/Type.h"
26
#include "clang/AST/TypeLoc.h"
27
#include "clang/Basic/AlignedAllocation.h"
28
#include "clang/Basic/DiagnosticSema.h"
29
#include "clang/Basic/PartialDiagnostic.h"
30
#include "clang/Basic/TargetInfo.h"
31
#include "clang/Basic/TokenKinds.h"
32
#include "clang/Basic/TypeTraits.h"
33
#include "clang/Lex/Preprocessor.h"
34
#include "clang/Sema/DeclSpec.h"
35
#include "clang/Sema/EnterExpressionEvaluationContext.h"
36
#include "clang/Sema/Initialization.h"
37
#include "clang/Sema/Lookup.h"
38
#include "clang/Sema/ParsedTemplate.h"
39
#include "clang/Sema/Scope.h"
40
#include "clang/Sema/ScopeInfo.h"
41
#include "clang/Sema/SemaInternal.h"
42
#include "clang/Sema/SemaLambda.h"
43
#include "clang/Sema/Template.h"
44
#include "clang/Sema/TemplateDeduction.h"
45
#include "llvm/ADT/APInt.h"
46
#include "llvm/ADT/STLExtras.h"
47
#include "llvm/ADT/StringExtras.h"
48
#include "llvm/Support/ErrorHandling.h"
49
#include "llvm/Support/TypeSize.h"
50
#include <optional>
51
using namespace clang;
52
using namespace sema;
53
54
/// Handle the result of the special case name lookup for inheriting
55
/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
56
/// constructor names in member using declarations, even if 'X' is not the
57
/// name of the corresponding type.
58
ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
59
                                              SourceLocation NameLoc,
60
0
                                              IdentifierInfo &Name) {
61
0
  NestedNameSpecifier *NNS = SS.getScopeRep();
62
63
  // Convert the nested-name-specifier into a type.
64
0
  QualType Type;
65
0
  switch (NNS->getKind()) {
66
0
  case NestedNameSpecifier::TypeSpec:
67
0
  case NestedNameSpecifier::TypeSpecWithTemplate:
68
0
    Type = QualType(NNS->getAsType(), 0);
69
0
    break;
70
71
0
  case NestedNameSpecifier::Identifier:
72
    // Strip off the last layer of the nested-name-specifier and build a
73
    // typename type for it.
74
0
    assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
75
0
    Type = Context.getDependentNameType(
76
0
        ElaboratedTypeKeyword::None, NNS->getPrefix(), NNS->getAsIdentifier());
77
0
    break;
78
79
0
  case NestedNameSpecifier::Global:
80
0
  case NestedNameSpecifier::Super:
81
0
  case NestedNameSpecifier::Namespace:
82
0
  case NestedNameSpecifier::NamespaceAlias:
83
0
    llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
84
0
  }
85
86
  // This reference to the type is located entirely at the location of the
87
  // final identifier in the qualified-id.
88
0
  return CreateParsedType(Type,
89
0
                          Context.getTrivialTypeSourceInfo(Type, NameLoc));
90
0
}
91
92
ParsedType Sema::getConstructorName(IdentifierInfo &II,
93
                                    SourceLocation NameLoc,
94
                                    Scope *S, CXXScopeSpec &SS,
95
0
                                    bool EnteringContext) {
96
0
  CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
97
0
  assert(CurClass && &II == CurClass->getIdentifier() &&
98
0
         "not a constructor name");
99
100
  // When naming a constructor as a member of a dependent context (eg, in a
101
  // friend declaration or an inherited constructor declaration), form an
102
  // unresolved "typename" type.
103
0
  if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) {
104
0
    QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None,
105
0
                                              SS.getScopeRep(), &II);
106
0
    return ParsedType::make(T);
107
0
  }
108
109
0
  if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
110
0
    return ParsedType();
111
112
  // Find the injected-class-name declaration. Note that we make no attempt to
113
  // diagnose cases where the injected-class-name is shadowed: the only
114
  // declaration that can validly shadow the injected-class-name is a
115
  // non-static data member, and if the class contains both a non-static data
116
  // member and a constructor then it is ill-formed (we check that in
117
  // CheckCompletedCXXClass).
118
0
  CXXRecordDecl *InjectedClassName = nullptr;
119
0
  for (NamedDecl *ND : CurClass->lookup(&II)) {
120
0
    auto *RD = dyn_cast<CXXRecordDecl>(ND);
121
0
    if (RD && RD->isInjectedClassName()) {
122
0
      InjectedClassName = RD;
123
0
      break;
124
0
    }
125
0
  }
126
0
  if (!InjectedClassName) {
127
0
    if (!CurClass->isInvalidDecl()) {
128
      // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
129
      // properly. Work around it here for now.
130
0
      Diag(SS.getLastQualifierNameLoc(),
131
0
           diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
132
0
    }
133
0
    return ParsedType();
134
0
  }
135
136
0
  QualType T = Context.getTypeDeclType(InjectedClassName);
137
0
  DiagnoseUseOfDecl(InjectedClassName, NameLoc);
138
0
  MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
139
140
0
  return ParsedType::make(T);
141
0
}
142
143
ParsedType Sema::getDestructorName(IdentifierInfo &II, SourceLocation NameLoc,
144
                                   Scope *S, CXXScopeSpec &SS,
145
                                   ParsedType ObjectTypePtr,
146
88
                                   bool EnteringContext) {
147
  // Determine where to perform name lookup.
148
149
  // FIXME: This area of the standard is very messy, and the current
150
  // wording is rather unclear about which scopes we search for the
151
  // destructor name; see core issues 399 and 555. Issue 399 in
152
  // particular shows where the current description of destructor name
153
  // lookup is completely out of line with existing practice, e.g.,
154
  // this appears to be ill-formed:
155
  //
156
  //   namespace N {
157
  //     template <typename T> struct S {
158
  //       ~S();
159
  //     };
160
  //   }
161
  //
162
  //   void f(N::S<int>* s) {
163
  //     s->N::S<int>::~S();
164
  //   }
165
  //
166
  // See also PR6358 and PR6359.
167
  //
168
  // For now, we accept all the cases in which the name given could plausibly
169
  // be interpreted as a correct destructor name, issuing off-by-default
170
  // extension diagnostics on the cases that don't strictly conform to the
171
  // C++20 rules. This basically means we always consider looking in the
172
  // nested-name-specifier prefix, the complete nested-name-specifier, and
173
  // the scope, and accept if we find the expected type in any of the three
174
  // places.
175
176
88
  if (SS.isInvalid())
177
0
    return nullptr;
178
179
  // Whether we've failed with a diagnostic already.
180
88
  bool Failed = false;
181
182
88
  llvm::SmallVector<NamedDecl*, 8> FoundDecls;
183
88
  llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 8> FoundDeclSet;
184
185
  // If we have an object type, it's because we are in a
186
  // pseudo-destructor-expression or a member access expression, and
187
  // we know what type we're looking for.
188
88
  QualType SearchType =
189
88
      ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType();
190
191
88
  auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType {
192
88
    auto IsAcceptableResult = [&](NamedDecl *D) -> bool {
193
29
      auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl());
194
29
      if (!Type)
195
29
        return false;
196
197
0
      if (SearchType.isNull() || SearchType->isDependentType())
198
0
        return true;
199
200
0
      QualType T = Context.getTypeDeclType(Type);
201
0
      return Context.hasSameUnqualifiedType(T, SearchType);
202
0
    };
203
204
88
    unsigned NumAcceptableResults = 0;
205
88
    for (NamedDecl *D : Found) {
206
29
      if (IsAcceptableResult(D))
207
0
        ++NumAcceptableResults;
208
209
      // Don't list a class twice in the lookup failure diagnostic if it's
210
      // found by both its injected-class-name and by the name in the enclosing
211
      // scope.
212
29
      if (auto *RD = dyn_cast<CXXRecordDecl>(D))
213
0
        if (RD->isInjectedClassName())
214
0
          D = cast<NamedDecl>(RD->getParent());
215
216
29
      if (FoundDeclSet.insert(D).second)
217
29
        FoundDecls.push_back(D);
218
29
    }
219
220
    // As an extension, attempt to "fix" an ambiguity by erasing all non-type
221
    // results, and all non-matching results if we have a search type. It's not
222
    // clear what the right behavior is if destructor lookup hits an ambiguity,
223
    // but other compilers do generally accept at least some kinds of
224
    // ambiguity.
225
88
    if (Found.isAmbiguous() && NumAcceptableResults == 1) {
226
0
      Diag(NameLoc, diag::ext_dtor_name_ambiguous);
227
0
      LookupResult::Filter F = Found.makeFilter();
228
0
      while (F.hasNext()) {
229
0
        NamedDecl *D = F.next();
230
0
        if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
231
0
          Diag(D->getLocation(), diag::note_destructor_type_here)
232
0
              << Context.getTypeDeclType(TD);
233
0
        else
234
0
          Diag(D->getLocation(), diag::note_destructor_nontype_here);
235
236
0
        if (!IsAcceptableResult(D))
237
0
          F.erase();
238
0
      }
239
0
      F.done();
240
0
    }
241
242
88
    if (Found.isAmbiguous())
243
0
      Failed = true;
244
245
88
    if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
246
0
      if (IsAcceptableResult(Type)) {
247
0
        QualType T = Context.getTypeDeclType(Type);
248
0
        MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
249
0
        return CreateParsedType(
250
0
            Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr, T),
251
0
            Context.getTrivialTypeSourceInfo(T, NameLoc));
252
0
      }
253
0
    }
254
255
88
    return nullptr;
256
88
  };
257
258
88
  bool IsDependent = false;
259
260
88
  auto LookupInObjectType = [&]() -> ParsedType {
261
88
    if (Failed || SearchType.isNull())
262
88
      return nullptr;
263
264
0
    IsDependent |= SearchType->isDependentType();
265
266
0
    LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
267
0
    DeclContext *LookupCtx = computeDeclContext(SearchType);
268
0
    if (!LookupCtx)
269
0
      return nullptr;
270
0
    LookupQualifiedName(Found, LookupCtx);
271
0
    return CheckLookupResult(Found);
272
0
  };
273
274
88
  auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType {
275
0
    if (Failed)
276
0
      return nullptr;
277
278
0
    IsDependent |= isDependentScopeSpecifier(LookupSS);
279
0
    DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext);
280
0
    if (!LookupCtx)
281
0
      return nullptr;
282
283
0
    LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
284
0
    if (RequireCompleteDeclContext(LookupSS, LookupCtx)) {
285
0
      Failed = true;
286
0
      return nullptr;
287
0
    }
288
0
    LookupQualifiedName(Found, LookupCtx);
289
0
    return CheckLookupResult(Found);
290
0
  };
291
292
88
  auto LookupInScope = [&]() -> ParsedType {
293
88
    if (Failed || !S)
294
0
      return nullptr;
295
296
88
    LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
297
88
    LookupName(Found, S);
298
88
    return CheckLookupResult(Found);
299
88
  };
300
301
  // C++2a [basic.lookup.qual]p6:
302
  //   In a qualified-id of the form
303
  //
304
  //     nested-name-specifier[opt] type-name :: ~ type-name
305
  //
306
  //   the second type-name is looked up in the same scope as the first.
307
  //
308
  // We interpret this as meaning that if you do a dual-scope lookup for the
309
  // first name, you also do a dual-scope lookup for the second name, per
310
  // C++ [basic.lookup.classref]p4:
311
  //
312
  //   If the id-expression in a class member access is a qualified-id of the
313
  //   form
314
  //
315
  //     class-name-or-namespace-name :: ...
316
  //
317
  //   the class-name-or-namespace-name following the . or -> is first looked
318
  //   up in the class of the object expression and the name, if found, is used.
319
  //   Otherwise, it is looked up in the context of the entire
320
  //   postfix-expression.
321
  //
322
  // This looks in the same scopes as for an unqualified destructor name:
323
  //
324
  // C++ [basic.lookup.classref]p3:
325
  //   If the unqualified-id is ~ type-name, the type-name is looked up
326
  //   in the context of the entire postfix-expression. If the type T
327
  //   of the object expression is of a class type C, the type-name is
328
  //   also looked up in the scope of class C. At least one of the
329
  //   lookups shall find a name that refers to cv T.
330
  //
331
  // FIXME: The intent is unclear here. Should type-name::~type-name look in
332
  // the scope anyway if it finds a non-matching name declared in the class?
333
  // If both lookups succeed and find a dependent result, which result should
334
  // we retain? (Same question for p->~type-name().)
335
336
88
  if (NestedNameSpecifier *Prefix =
337
88
      SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) {
338
    // This is
339
    //
340
    //   nested-name-specifier type-name :: ~ type-name
341
    //
342
    // Look for the second type-name in the nested-name-specifier.
343
0
    CXXScopeSpec PrefixSS;
344
0
    PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
345
0
    if (ParsedType T = LookupInNestedNameSpec(PrefixSS))
346
0
      return T;
347
88
  } else {
348
    // This is one of
349
    //
350
    //   type-name :: ~ type-name
351
    //   ~ type-name
352
    //
353
    // Look in the scope and (if any) the object type.
354
88
    if (ParsedType T = LookupInScope())
355
0
      return T;
356
88
    if (ParsedType T = LookupInObjectType())
357
0
      return T;
358
88
  }
359
360
88
  if (Failed)
361
0
    return nullptr;
362
363
88
  if (IsDependent) {
364
    // We didn't find our type, but that's OK: it's dependent anyway.
365
366
    // FIXME: What if we have no nested-name-specifier?
367
0
    QualType T =
368
0
        CheckTypenameType(ElaboratedTypeKeyword::None, SourceLocation(),
369
0
                          SS.getWithLocInContext(Context), II, NameLoc);
370
0
    return ParsedType::make(T);
371
0
  }
372
373
  // The remaining cases are all non-standard extensions imitating the behavior
374
  // of various other compilers.
375
88
  unsigned NumNonExtensionDecls = FoundDecls.size();
376
377
88
  if (SS.isSet()) {
378
    // For compatibility with older broken C++ rules and existing code,
379
    //
380
    //   nested-name-specifier :: ~ type-name
381
    //
382
    // also looks for type-name within the nested-name-specifier.
383
0
    if (ParsedType T = LookupInNestedNameSpec(SS)) {
384
0
      Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope)
385
0
          << SS.getRange()
386
0
          << FixItHint::CreateInsertion(SS.getEndLoc(),
387
0
                                        ("::" + II.getName()).str());
388
0
      return T;
389
0
    }
390
391
    // For compatibility with other compilers and older versions of Clang,
392
    //
393
    //   nested-name-specifier type-name :: ~ type-name
394
    //
395
    // also looks for type-name in the scope. Unfortunately, we can't
396
    // reasonably apply this fallback for dependent nested-name-specifiers.
397
0
    if (SS.isValid() && SS.getScopeRep()->getPrefix()) {
398
0
      if (ParsedType T = LookupInScope()) {
399
0
        Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope)
400
0
            << FixItHint::CreateRemoval(SS.getRange());
401
0
        Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here)
402
0
            << GetTypeFromParser(T);
403
0
        return T;
404
0
      }
405
0
    }
406
0
  }
407
408
  // We didn't find anything matching; tell the user what we did find (if
409
  // anything).
410
411
  // Don't tell the user about declarations we shouldn't have found.
412
88
  FoundDecls.resize(NumNonExtensionDecls);
413
414
  // List types before non-types.
415
88
  std::stable_sort(FoundDecls.begin(), FoundDecls.end(),
416
88
                   [](NamedDecl *A, NamedDecl *B) {
417
0
                     return isa<TypeDecl>(A->getUnderlyingDecl()) >
418
0
                            isa<TypeDecl>(B->getUnderlyingDecl());
419
0
                   });
420
421
  // Suggest a fixit to properly name the destroyed type.
422
88
  auto MakeFixItHint = [&]{
423
88
    const CXXRecordDecl *Destroyed = nullptr;
424
    // FIXME: If we have a scope specifier, suggest its last component?
425
88
    if (!SearchType.isNull())
426
0
      Destroyed = SearchType->getAsCXXRecordDecl();
427
88
    else if (S)
428
88
      Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity());
429
88
    if (Destroyed)
430
0
      return FixItHint::CreateReplacement(SourceRange(NameLoc),
431
0
                                          Destroyed->getNameAsString());
432
88
    return FixItHint();
433
88
  };
434
435
88
  if (FoundDecls.empty()) {
436
    // FIXME: Attempt typo-correction?
437
59
    Diag(NameLoc, diag::err_undeclared_destructor_name)
438
59
      << &II << MakeFixItHint();
439
59
  } else if (!SearchType.isNull() && FoundDecls.size() == 1) {
440
0
    if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) {
441
0
      assert(!SearchType.isNull() &&
442
0
             "should only reject a type result if we have a search type");
443
0
      QualType T = Context.getTypeDeclType(TD);
444
0
      Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
445
0
          << T << SearchType << MakeFixItHint();
446
0
    } else {
447
0
      Diag(NameLoc, diag::err_destructor_expr_nontype)
448
0
          << &II << MakeFixItHint();
449
0
    }
450
29
  } else {
451
29
    Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype
452
29
                                      : diag::err_destructor_expr_mismatch)
453
29
        << &II << SearchType << MakeFixItHint();
454
29
  }
455
456
29
  for (NamedDecl *FoundD : FoundDecls) {
457
29
    if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl()))
458
0
      Diag(FoundD->getLocation(), diag::note_destructor_type_here)
459
0
          << Context.getTypeDeclType(TD);
460
29
    else
461
29
      Diag(FoundD->getLocation(), diag::note_destructor_nontype_here)
462
29
          << FoundD;
463
29
  }
464
465
88
  return nullptr;
466
88
}
467
468
ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
469
0
                                              ParsedType ObjectType) {
470
0
  if (DS.getTypeSpecType() == DeclSpec::TST_error)
471
0
    return nullptr;
472
473
0
  if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
474
0
    Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
475
0
    return nullptr;
476
0
  }
477
478
0
  assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
479
0
         "unexpected type in getDestructorType");
480
0
  QualType T = BuildDecltypeType(DS.getRepAsExpr());
481
482
  // If we know the type of the object, check that the correct destructor
483
  // type was named now; we can give better diagnostics this way.
484
0
  QualType SearchType = GetTypeFromParser(ObjectType);
485
0
  if (!SearchType.isNull() && !SearchType->isDependentType() &&
486
0
      !Context.hasSameUnqualifiedType(T, SearchType)) {
487
0
    Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
488
0
      << T << SearchType;
489
0
    return nullptr;
490
0
  }
491
492
0
  return ParsedType::make(T);
493
0
}
494
495
bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
496
0
                                  const UnqualifiedId &Name, bool IsUDSuffix) {
497
0
  assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
498
0
  if (!IsUDSuffix) {
499
    // [over.literal] p8
500
    //
501
    // double operator""_Bq(long double);  // OK: not a reserved identifier
502
    // double operator"" _Bq(long double); // ill-formed, no diagnostic required
503
0
    IdentifierInfo *II = Name.Identifier;
504
0
    ReservedIdentifierStatus Status = II->isReserved(PP.getLangOpts());
505
0
    SourceLocation Loc = Name.getEndLoc();
506
0
    if (!PP.getSourceManager().isInSystemHeader(Loc)) {
507
0
      if (auto Hint = FixItHint::CreateReplacement(
508
0
              Name.getSourceRange(),
509
0
              (StringRef("operator\"\"") + II->getName()).str());
510
0
          isReservedInAllContexts(Status)) {
511
0
        Diag(Loc, diag::warn_reserved_extern_symbol)
512
0
            << II << static_cast<int>(Status) << Hint;
513
0
      } else {
514
0
        Diag(Loc, diag::warn_deprecated_literal_operator_id) << II << Hint;
515
0
      }
516
0
    }
517
0
  }
518
519
0
  if (!SS.isValid())
520
0
    return false;
521
522
0
  switch (SS.getScopeRep()->getKind()) {
523
0
  case NestedNameSpecifier::Identifier:
524
0
  case NestedNameSpecifier::TypeSpec:
525
0
  case NestedNameSpecifier::TypeSpecWithTemplate:
526
    // Per C++11 [over.literal]p2, literal operators can only be declared at
527
    // namespace scope. Therefore, this unqualified-id cannot name anything.
528
    // Reject it early, because we have no AST representation for this in the
529
    // case where the scope is dependent.
530
0
    Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
531
0
        << SS.getScopeRep();
532
0
    return true;
533
534
0
  case NestedNameSpecifier::Global:
535
0
  case NestedNameSpecifier::Super:
536
0
  case NestedNameSpecifier::Namespace:
537
0
  case NestedNameSpecifier::NamespaceAlias:
538
0
    return false;
539
0
  }
540
541
0
  llvm_unreachable("unknown nested name specifier kind");
542
0
}
543
544
/// Build a C++ typeid expression with a type operand.
545
ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
546
                                SourceLocation TypeidLoc,
547
                                TypeSourceInfo *Operand,
548
0
                                SourceLocation RParenLoc) {
549
  // C++ [expr.typeid]p4:
550
  //   The top-level cv-qualifiers of the lvalue expression or the type-id
551
  //   that is the operand of typeid are always ignored.
552
  //   If the type of the type-id is a class type or a reference to a class
553
  //   type, the class shall be completely-defined.
554
0
  Qualifiers Quals;
555
0
  QualType T
556
0
    = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
557
0
                                      Quals);
558
0
  if (T->getAs<RecordType>() &&
559
0
      RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
560
0
    return ExprError();
561
562
0
  if (T->isVariablyModifiedType())
563
0
    return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
564
565
0
  if (CheckQualifiedFunctionForTypeId(T, TypeidLoc))
566
0
    return ExprError();
567
568
0
  return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
569
0
                                     SourceRange(TypeidLoc, RParenLoc));
570
0
}
571
572
/// Build a C++ typeid expression with an expression operand.
573
ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
574
                                SourceLocation TypeidLoc,
575
                                Expr *E,
576
0
                                SourceLocation RParenLoc) {
577
0
  bool WasEvaluated = false;
578
0
  if (E && !E->isTypeDependent()) {
579
0
    if (E->hasPlaceholderType()) {
580
0
      ExprResult result = CheckPlaceholderExpr(E);
581
0
      if (result.isInvalid()) return ExprError();
582
0
      E = result.get();
583
0
    }
584
585
0
    QualType T = E->getType();
586
0
    if (const RecordType *RecordT = T->getAs<RecordType>()) {
587
0
      CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
588
      // C++ [expr.typeid]p3:
589
      //   [...] If the type of the expression is a class type, the class
590
      //   shall be completely-defined.
591
0
      if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
592
0
        return ExprError();
593
594
      // C++ [expr.typeid]p3:
595
      //   When typeid is applied to an expression other than an glvalue of a
596
      //   polymorphic class type [...] [the] expression is an unevaluated
597
      //   operand. [...]
598
0
      if (RecordD->isPolymorphic() && E->isGLValue()) {
599
0
        if (isUnevaluatedContext()) {
600
          // The operand was processed in unevaluated context, switch the
601
          // context and recheck the subexpression.
602
0
          ExprResult Result = TransformToPotentiallyEvaluated(E);
603
0
          if (Result.isInvalid())
604
0
            return ExprError();
605
0
          E = Result.get();
606
0
        }
607
608
        // We require a vtable to query the type at run time.
609
0
        MarkVTableUsed(TypeidLoc, RecordD);
610
0
        WasEvaluated = true;
611
0
      }
612
0
    }
613
614
0
    ExprResult Result = CheckUnevaluatedOperand(E);
615
0
    if (Result.isInvalid())
616
0
      return ExprError();
617
0
    E = Result.get();
618
619
    // C++ [expr.typeid]p4:
620
    //   [...] If the type of the type-id is a reference to a possibly
621
    //   cv-qualified type, the result of the typeid expression refers to a
622
    //   std::type_info object representing the cv-unqualified referenced
623
    //   type.
624
0
    Qualifiers Quals;
625
0
    QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
626
0
    if (!Context.hasSameType(T, UnqualT)) {
627
0
      T = UnqualT;
628
0
      E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
629
0
    }
630
0
  }
631
632
0
  if (E->getType()->isVariablyModifiedType())
633
0
    return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
634
0
                     << E->getType());
635
0
  else if (!inTemplateInstantiation() &&
636
0
           E->HasSideEffects(Context, WasEvaluated)) {
637
    // The expression operand for typeid is in an unevaluated expression
638
    // context, so side effects could result in unintended consequences.
639
0
    Diag(E->getExprLoc(), WasEvaluated
640
0
                              ? diag::warn_side_effects_typeid
641
0
                              : diag::warn_side_effects_unevaluated_context);
642
0
  }
643
644
0
  return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
645
0
                                     SourceRange(TypeidLoc, RParenLoc));
646
0
}
647
648
/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
649
ExprResult
650
Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
651
0
                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
652
  // typeid is not supported in OpenCL.
653
0
  if (getLangOpts().OpenCLCPlusPlus) {
654
0
    return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
655
0
                     << "typeid");
656
0
  }
657
658
  // Find the std::type_info type.
659
0
  if (!getStdNamespace())
660
0
    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
661
662
0
  if (!CXXTypeInfoDecl) {
663
0
    IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
664
0
    LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
665
0
    LookupQualifiedName(R, getStdNamespace());
666
0
    CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
667
    // Microsoft's typeinfo doesn't have type_info in std but in the global
668
    // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
669
0
    if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
670
0
      LookupQualifiedName(R, Context.getTranslationUnitDecl());
671
0
      CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
672
0
    }
673
0
    if (!CXXTypeInfoDecl)
674
0
      return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
675
0
  }
676
677
0
  if (!getLangOpts().RTTI) {
678
0
    return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
679
0
  }
680
681
0
  QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
682
683
0
  if (isType) {
684
    // The operand is a type; handle it as such.
685
0
    TypeSourceInfo *TInfo = nullptr;
686
0
    QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
687
0
                                   &TInfo);
688
0
    if (T.isNull())
689
0
      return ExprError();
690
691
0
    if (!TInfo)
692
0
      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
693
694
0
    return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
695
0
  }
696
697
  // The operand is an expression.
698
0
  ExprResult Result =
699
0
      BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc);
700
701
0
  if (!getLangOpts().RTTIData && !Result.isInvalid())
702
0
    if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get()))
703
0
      if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context))
704
0
        Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled)
705
0
            << (getDiagnostics().getDiagnosticOptions().getFormat() ==
706
0
                DiagnosticOptions::MSVC);
707
0
  return Result;
708
0
}
709
710
/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
711
/// a single GUID.
712
static void
713
getUuidAttrOfType(Sema &SemaRef, QualType QT,
714
0
                  llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
715
  // Optionally remove one level of pointer, reference or array indirection.
716
0
  const Type *Ty = QT.getTypePtr();
717
0
  if (QT->isPointerType() || QT->isReferenceType())
718
0
    Ty = QT->getPointeeType().getTypePtr();
719
0
  else if (QT->isArrayType())
720
0
    Ty = Ty->getBaseElementTypeUnsafe();
721
722
0
  const auto *TD = Ty->getAsTagDecl();
723
0
  if (!TD)
724
0
    return;
725
726
0
  if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
727
0
    UuidAttrs.insert(Uuid);
728
0
    return;
729
0
  }
730
731
  // __uuidof can grab UUIDs from template arguments.
732
0
  if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
733
0
    const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
734
0
    for (const TemplateArgument &TA : TAL.asArray()) {
735
0
      const UuidAttr *UuidForTA = nullptr;
736
0
      if (TA.getKind() == TemplateArgument::Type)
737
0
        getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
738
0
      else if (TA.getKind() == TemplateArgument::Declaration)
739
0
        getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
740
741
0
      if (UuidForTA)
742
0
        UuidAttrs.insert(UuidForTA);
743
0
    }
744
0
  }
745
0
}
746
747
/// Build a Microsoft __uuidof expression with a type operand.
748
ExprResult Sema::BuildCXXUuidof(QualType Type,
749
                                SourceLocation TypeidLoc,
750
                                TypeSourceInfo *Operand,
751
0
                                SourceLocation RParenLoc) {
752
0
  MSGuidDecl *Guid = nullptr;
753
0
  if (!Operand->getType()->isDependentType()) {
754
0
    llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
755
0
    getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
756
0
    if (UuidAttrs.empty())
757
0
      return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
758
0
    if (UuidAttrs.size() > 1)
759
0
      return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
760
0
    Guid = UuidAttrs.back()->getGuidDecl();
761
0
  }
762
763
0
  return new (Context)
764
0
      CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc));
765
0
}
766
767
/// Build a Microsoft __uuidof expression with an expression operand.
768
ExprResult Sema::BuildCXXUuidof(QualType Type, SourceLocation TypeidLoc,
769
0
                                Expr *E, SourceLocation RParenLoc) {
770
0
  MSGuidDecl *Guid = nullptr;
771
0
  if (!E->getType()->isDependentType()) {
772
0
    if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
773
      // A null pointer results in {00000000-0000-0000-0000-000000000000}.
774
0
      Guid = Context.getMSGuidDecl(MSGuidDecl::Parts{});
775
0
    } else {
776
0
      llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
777
0
      getUuidAttrOfType(*this, E->getType(), UuidAttrs);
778
0
      if (UuidAttrs.empty())
779
0
        return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
780
0
      if (UuidAttrs.size() > 1)
781
0
        return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
782
0
      Guid = UuidAttrs.back()->getGuidDecl();
783
0
    }
784
0
  }
785
786
0
  return new (Context)
787
0
      CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc));
788
0
}
789
790
/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
791
ExprResult
792
Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
793
0
                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
794
0
  QualType GuidType = Context.getMSGuidType();
795
0
  GuidType.addConst();
796
797
0
  if (isType) {
798
    // The operand is a type; handle it as such.
799
0
    TypeSourceInfo *TInfo = nullptr;
800
0
    QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
801
0
                                   &TInfo);
802
0
    if (T.isNull())
803
0
      return ExprError();
804
805
0
    if (!TInfo)
806
0
      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
807
808
0
    return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
809
0
  }
810
811
  // The operand is an expression.
812
0
  return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
813
0
}
814
815
/// ActOnCXXBoolLiteral - Parse {true,false} literals.
816
ExprResult
817
0
Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
818
0
  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
819
0
         "Unknown C++ Boolean value!");
820
0
  return new (Context)
821
0
      CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
822
0
}
823
824
/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
825
ExprResult
826
0
Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
827
0
  return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
828
0
}
829
830
/// ActOnCXXThrow - Parse throw expressions.
831
ExprResult
832
0
Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
833
0
  bool IsThrownVarInScope = false;
834
0
  if (Ex) {
835
    // C++0x [class.copymove]p31:
836
    //   When certain criteria are met, an implementation is allowed to omit the
837
    //   copy/move construction of a class object [...]
838
    //
839
    //     - in a throw-expression, when the operand is the name of a
840
    //       non-volatile automatic object (other than a function or catch-
841
    //       clause parameter) whose scope does not extend beyond the end of the
842
    //       innermost enclosing try-block (if there is one), the copy/move
843
    //       operation from the operand to the exception object (15.1) can be
844
    //       omitted by constructing the automatic object directly into the
845
    //       exception object
846
0
    if (const auto *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
847
0
      if (const auto *Var = dyn_cast<VarDecl>(DRE->getDecl());
848
0
          Var && Var->hasLocalStorage() &&
849
0
          !Var->getType().isVolatileQualified()) {
850
0
        for (; S; S = S->getParent()) {
851
0
          if (S->isDeclScope(Var)) {
852
0
            IsThrownVarInScope = true;
853
0
            break;
854
0
          }
855
856
          // FIXME: Many of the scope checks here seem incorrect.
857
0
          if (S->getFlags() &
858
0
              (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
859
0
               Scope::ObjCMethodScope | Scope::TryScope))
860
0
            break;
861
0
        }
862
0
      }
863
0
  }
864
865
0
  return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
866
0
}
867
868
ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
869
0
                               bool IsThrownVarInScope) {
870
0
  const llvm::Triple &T = Context.getTargetInfo().getTriple();
871
0
  const bool IsOpenMPGPUTarget =
872
0
      getLangOpts().OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN());
873
  // Don't report an error if 'throw' is used in system headers or in an OpenMP
874
  // target region compiled for a GPU architecture.
875
0
  if (!IsOpenMPGPUTarget && !getLangOpts().CXXExceptions &&
876
0
      !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) {
877
    // Delay error emission for the OpenMP device code.
878
0
    targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";
879
0
  }
880
881
  // In OpenMP target regions, we replace 'throw' with a trap on GPU targets.
882
0
  if (IsOpenMPGPUTarget)
883
0
    targetDiag(OpLoc, diag::warn_throw_not_valid_on_target) << T.str();
884
885
  // Exceptions aren't allowed in CUDA device code.
886
0
  if (getLangOpts().CUDA)
887
0
    CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
888
0
        << "throw" << CurrentCUDATarget();
889
890
0
  if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
891
0
    Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
892
893
0
  if (Ex && !Ex->isTypeDependent()) {
894
    // Initialize the exception result.  This implicitly weeds out
895
    // abstract types or types with inaccessible copy constructors.
896
897
    // C++0x [class.copymove]p31:
898
    //   When certain criteria are met, an implementation is allowed to omit the
899
    //   copy/move construction of a class object [...]
900
    //
901
    //     - in a throw-expression, when the operand is the name of a
902
    //       non-volatile automatic object (other than a function or
903
    //       catch-clause
904
    //       parameter) whose scope does not extend beyond the end of the
905
    //       innermost enclosing try-block (if there is one), the copy/move
906
    //       operation from the operand to the exception object (15.1) can be
907
    //       omitted by constructing the automatic object directly into the
908
    //       exception object
909
0
    NamedReturnInfo NRInfo =
910
0
        IsThrownVarInScope ? getNamedReturnInfo(Ex) : NamedReturnInfo();
911
912
0
    QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
913
0
    if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
914
0
      return ExprError();
915
916
0
    InitializedEntity Entity =
917
0
        InitializedEntity::InitializeException(OpLoc, ExceptionObjectTy);
918
0
    ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRInfo, Ex);
919
0
    if (Res.isInvalid())
920
0
      return ExprError();
921
0
    Ex = Res.get();
922
0
  }
923
924
  // PPC MMA non-pointer types are not allowed as throw expr types.
925
0
  if (Ex && Context.getTargetInfo().getTriple().isPPC64())
926
0
    CheckPPCMMAType(Ex->getType(), Ex->getBeginLoc());
927
928
0
  return new (Context)
929
0
      CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
930
0
}
931
932
static void
933
collectPublicBases(CXXRecordDecl *RD,
934
                   llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
935
                   llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
936
                   llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
937
0
                   bool ParentIsPublic) {
938
0
  for (const CXXBaseSpecifier &BS : RD->bases()) {
939
0
    CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
940
0
    bool NewSubobject;
941
    // Virtual bases constitute the same subobject.  Non-virtual bases are
942
    // always distinct subobjects.
943
0
    if (BS.isVirtual())
944
0
      NewSubobject = VBases.insert(BaseDecl).second;
945
0
    else
946
0
      NewSubobject = true;
947
948
0
    if (NewSubobject)
949
0
      ++SubobjectsSeen[BaseDecl];
950
951
    // Only add subobjects which have public access throughout the entire chain.
952
0
    bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
953
0
    if (PublicPath)
954
0
      PublicSubobjectsSeen.insert(BaseDecl);
955
956
    // Recurse on to each base subobject.
957
0
    collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
958
0
                       PublicPath);
959
0
  }
960
0
}
961
962
static void getUnambiguousPublicSubobjects(
963
0
    CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
964
0
  llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
965
0
  llvm::SmallSet<CXXRecordDecl *, 2> VBases;
966
0
  llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
967
0
  SubobjectsSeen[RD] = 1;
968
0
  PublicSubobjectsSeen.insert(RD);
969
0
  collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
970
0
                     /*ParentIsPublic=*/true);
971
972
0
  for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
973
    // Skip ambiguous objects.
974
0
    if (SubobjectsSeen[PublicSubobject] > 1)
975
0
      continue;
976
977
0
    Objects.push_back(PublicSubobject);
978
0
  }
979
0
}
980
981
/// CheckCXXThrowOperand - Validate the operand of a throw.
982
bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
983
0
                                QualType ExceptionObjectTy, Expr *E) {
984
  //   If the type of the exception would be an incomplete type or a pointer
985
  //   to an incomplete type other than (cv) void the program is ill-formed.
986
0
  QualType Ty = ExceptionObjectTy;
987
0
  bool isPointer = false;
988
0
  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
989
0
    Ty = Ptr->getPointeeType();
990
0
    isPointer = true;
991
0
  }
992
993
  // Cannot throw WebAssembly reference type.
994
0
  if (Ty.isWebAssemblyReferenceType()) {
995
0
    Diag(ThrowLoc, diag::err_wasm_reftype_tc) << 0 << E->getSourceRange();
996
0
    return true;
997
0
  }
998
999
  // Cannot throw WebAssembly table.
1000
0
  if (isPointer && Ty.isWebAssemblyReferenceType()) {
1001
0
    Diag(ThrowLoc, diag::err_wasm_table_art) << 2 << E->getSourceRange();
1002
0
    return true;
1003
0
  }
1004
1005
0
  if (!isPointer || !Ty->isVoidType()) {
1006
0
    if (RequireCompleteType(ThrowLoc, Ty,
1007
0
                            isPointer ? diag::err_throw_incomplete_ptr
1008
0
                                      : diag::err_throw_incomplete,
1009
0
                            E->getSourceRange()))
1010
0
      return true;
1011
1012
0
    if (!isPointer && Ty->isSizelessType()) {
1013
0
      Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange();
1014
0
      return true;
1015
0
    }
1016
1017
0
    if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
1018
0
                               diag::err_throw_abstract_type, E))
1019
0
      return true;
1020
0
  }
1021
1022
  // If the exception has class type, we need additional handling.
1023
0
  CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1024
0
  if (!RD)
1025
0
    return false;
1026
1027
  // If we are throwing a polymorphic class type or pointer thereof,
1028
  // exception handling will make use of the vtable.
1029
0
  MarkVTableUsed(ThrowLoc, RD);
1030
1031
  // If a pointer is thrown, the referenced object will not be destroyed.
1032
0
  if (isPointer)
1033
0
    return false;
1034
1035
  // If the class has a destructor, we must be able to call it.
1036
0
  if (!RD->hasIrrelevantDestructor()) {
1037
0
    if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
1038
0
      MarkFunctionReferenced(E->getExprLoc(), Destructor);
1039
0
      CheckDestructorAccess(E->getExprLoc(), Destructor,
1040
0
                            PDiag(diag::err_access_dtor_exception) << Ty);
1041
0
      if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
1042
0
        return true;
1043
0
    }
1044
0
  }
1045
1046
  // The MSVC ABI creates a list of all types which can catch the exception
1047
  // object.  This list also references the appropriate copy constructor to call
1048
  // if the object is caught by value and has a non-trivial copy constructor.
1049
0
  if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1050
    // We are only interested in the public, unambiguous bases contained within
1051
    // the exception object.  Bases which are ambiguous or otherwise
1052
    // inaccessible are not catchable types.
1053
0
    llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
1054
0
    getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
1055
1056
0
    for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
1057
      // Attempt to lookup the copy constructor.  Various pieces of machinery
1058
      // will spring into action, like template instantiation, which means this
1059
      // cannot be a simple walk of the class's decls.  Instead, we must perform
1060
      // lookup and overload resolution.
1061
0
      CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
1062
0
      if (!CD || CD->isDeleted())
1063
0
        continue;
1064
1065
      // Mark the constructor referenced as it is used by this throw expression.
1066
0
      MarkFunctionReferenced(E->getExprLoc(), CD);
1067
1068
      // Skip this copy constructor if it is trivial, we don't need to record it
1069
      // in the catchable type data.
1070
0
      if (CD->isTrivial())
1071
0
        continue;
1072
1073
      // The copy constructor is non-trivial, create a mapping from this class
1074
      // type to this constructor.
1075
      // N.B.  The selection of copy constructor is not sensitive to this
1076
      // particular throw-site.  Lookup will be performed at the catch-site to
1077
      // ensure that the copy constructor is, in fact, accessible (via
1078
      // friendship or any other means).
1079
0
      Context.addCopyConstructorForExceptionObject(Subobject, CD);
1080
1081
      // We don't keep the instantiated default argument expressions around so
1082
      // we must rebuild them here.
1083
0
      for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
1084
0
        if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
1085
0
          return true;
1086
0
      }
1087
0
    }
1088
0
  }
1089
1090
  // Under the Itanium C++ ABI, memory for the exception object is allocated by
1091
  // the runtime with no ability for the compiler to request additional
1092
  // alignment. Warn if the exception type requires alignment beyond the minimum
1093
  // guaranteed by the target C++ runtime.
1094
0
  if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) {
1095
0
    CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
1096
0
    CharUnits ExnObjAlign = Context.getExnObjectAlignment();
1097
0
    if (ExnObjAlign < TypeAlign) {
1098
0
      Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
1099
0
      Diag(ThrowLoc, diag::note_throw_underaligned_obj)
1100
0
          << Ty << (unsigned)TypeAlign.getQuantity()
1101
0
          << (unsigned)ExnObjAlign.getQuantity();
1102
0
    }
1103
0
  }
1104
0
  if (!isPointer && getLangOpts().AssumeNothrowExceptionDtor) {
1105
0
    if (CXXDestructorDecl *Dtor = RD->getDestructor()) {
1106
0
      auto Ty = Dtor->getType();
1107
0
      if (auto *FT = Ty.getTypePtr()->getAs<FunctionProtoType>()) {
1108
0
        if (!isUnresolvedExceptionSpec(FT->getExceptionSpecType()) &&
1109
0
            !FT->isNothrow())
1110
0
          Diag(ThrowLoc, diag::err_throw_object_throwing_dtor) << RD;
1111
0
      }
1112
0
    }
1113
0
  }
1114
1115
0
  return false;
1116
0
}
1117
1118
static QualType adjustCVQualifiersForCXXThisWithinLambda(
1119
    ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
1120
0
    DeclContext *CurSemaContext, ASTContext &ASTCtx) {
1121
1122
0
  QualType ClassType = ThisTy->getPointeeType();
1123
0
  LambdaScopeInfo *CurLSI = nullptr;
1124
0
  DeclContext *CurDC = CurSemaContext;
1125
1126
  // Iterate through the stack of lambdas starting from the innermost lambda to
1127
  // the outermost lambda, checking if '*this' is ever captured by copy - since
1128
  // that could change the cv-qualifiers of the '*this' object.
1129
  // The object referred to by '*this' starts out with the cv-qualifiers of its
1130
  // member function.  We then start with the innermost lambda and iterate
1131
  // outward checking to see if any lambda performs a by-copy capture of '*this'
1132
  // - and if so, any nested lambda must respect the 'constness' of that
1133
  // capturing lamdbda's call operator.
1134
  //
1135
1136
  // Since the FunctionScopeInfo stack is representative of the lexical
1137
  // nesting of the lambda expressions during initial parsing (and is the best
1138
  // place for querying information about captures about lambdas that are
1139
  // partially processed) and perhaps during instantiation of function templates
1140
  // that contain lambda expressions that need to be transformed BUT not
1141
  // necessarily during instantiation of a nested generic lambda's function call
1142
  // operator (which might even be instantiated at the end of the TU) - at which
1143
  // time the DeclContext tree is mature enough to query capture information
1144
  // reliably - we use a two pronged approach to walk through all the lexically
1145
  // enclosing lambda expressions:
1146
  //
1147
  //  1) Climb down the FunctionScopeInfo stack as long as each item represents
1148
  //  a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
1149
  //  enclosed by the call-operator of the LSI below it on the stack (while
1150
  //  tracking the enclosing DC for step 2 if needed).  Note the topmost LSI on
1151
  //  the stack represents the innermost lambda.
1152
  //
1153
  //  2) If we run out of enclosing LSI's, check if the enclosing DeclContext
1154
  //  represents a lambda's call operator.  If it does, we must be instantiating
1155
  //  a generic lambda's call operator (represented by the Current LSI, and
1156
  //  should be the only scenario where an inconsistency between the LSI and the
1157
  //  DeclContext should occur), so climb out the DeclContexts if they
1158
  //  represent lambdas, while querying the corresponding closure types
1159
  //  regarding capture information.
1160
1161
  // 1) Climb down the function scope info stack.
1162
0
  for (int I = FunctionScopes.size();
1163
0
       I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
1164
0
       (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
1165
0
                       cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
1166
0
       CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
1167
0
    CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
1168
1169
0
    if (!CurLSI->isCXXThisCaptured())
1170
0
        continue;
1171
1172
0
    auto C = CurLSI->getCXXThisCapture();
1173
1174
0
    if (C.isCopyCapture()) {
1175
0
      if (CurLSI->lambdaCaptureShouldBeConst())
1176
0
        ClassType.addConst();
1177
0
      return ASTCtx.getPointerType(ClassType);
1178
0
    }
1179
0
  }
1180
1181
  // 2) We've run out of ScopeInfos but check 1. if CurDC is a lambda (which
1182
  //    can happen during instantiation of its nested generic lambda call
1183
  //    operator); 2. if we're in a lambda scope (lambda body).
1184
0
  if (CurLSI && isLambdaCallOperator(CurDC)) {
1185
0
    assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
1186
0
           "While computing 'this' capture-type for a generic lambda, when we "
1187
0
           "run out of enclosing LSI's, yet the enclosing DC is a "
1188
0
           "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1189
0
           "lambda call oeprator");
1190
0
    assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
1191
1192
0
    auto IsThisCaptured =
1193
0
        [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1194
0
      IsConst = false;
1195
0
      IsByCopy = false;
1196
0
      for (auto &&C : Closure->captures()) {
1197
0
        if (C.capturesThis()) {
1198
0
          if (C.getCaptureKind() == LCK_StarThis)
1199
0
            IsByCopy = true;
1200
0
          if (Closure->getLambdaCallOperator()->isConst())
1201
0
            IsConst = true;
1202
0
          return true;
1203
0
        }
1204
0
      }
1205
0
      return false;
1206
0
    };
1207
1208
0
    bool IsByCopyCapture = false;
1209
0
    bool IsConstCapture = false;
1210
0
    CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1211
0
    while (Closure &&
1212
0
           IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1213
0
      if (IsByCopyCapture) {
1214
0
        if (IsConstCapture)
1215
0
          ClassType.addConst();
1216
0
        return ASTCtx.getPointerType(ClassType);
1217
0
      }
1218
0
      Closure = isLambdaCallOperator(Closure->getParent())
1219
0
                    ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1220
0
                    : nullptr;
1221
0
    }
1222
0
  }
1223
0
  return ASTCtx.getPointerType(ClassType);
1224
0
}
1225
1226
0
QualType Sema::getCurrentThisType() {
1227
0
  DeclContext *DC = getFunctionLevelDeclContext();
1228
0
  QualType ThisTy = CXXThisTypeOverride;
1229
1230
0
  if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1231
0
    if (method && method->isImplicitObjectMemberFunction())
1232
0
      ThisTy = method->getThisType().getNonReferenceType();
1233
0
  }
1234
1235
0
  if (ThisTy.isNull() && isLambdaCallWithImplicitObjectParameter(CurContext) &&
1236
0
      inTemplateInstantiation() && isa<CXXRecordDecl>(DC)) {
1237
1238
    // This is a lambda call operator that is being instantiated as a default
1239
    // initializer. DC must point to the enclosing class type, so we can recover
1240
    // the 'this' type from it.
1241
0
    QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1242
    // There are no cv-qualifiers for 'this' within default initializers,
1243
    // per [expr.prim.general]p4.
1244
0
    ThisTy = Context.getPointerType(ClassTy);
1245
0
  }
1246
1247
  // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1248
  // might need to be adjusted if the lambda or any of its enclosing lambda's
1249
  // captures '*this' by copy.
1250
0
  if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1251
0
    return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1252
0
                                                    CurContext, Context);
1253
0
  return ThisTy;
1254
0
}
1255
1256
Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
1257
                                         Decl *ContextDecl,
1258
                                         Qualifiers CXXThisTypeQuals,
1259
                                         bool Enabled)
1260
  : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1261
0
{
1262
0
  if (!Enabled || !ContextDecl)
1263
0
    return;
1264
1265
0
  CXXRecordDecl *Record = nullptr;
1266
0
  if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1267
0
    Record = Template->getTemplatedDecl();
1268
0
  else
1269
0
    Record = cast<CXXRecordDecl>(ContextDecl);
1270
1271
0
  QualType T = S.Context.getRecordType(Record);
1272
0
  T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1273
1274
0
  S.CXXThisTypeOverride =
1275
0
      S.Context.getLangOpts().HLSL ? T : S.Context.getPointerType(T);
1276
1277
0
  this->Enabled = true;
1278
0
}
1279
1280
1281
0
Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1282
0
  if (Enabled) {
1283
0
    S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1284
0
  }
1285
0
}
1286
1287
0
static void buildLambdaThisCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI) {
1288
0
  SourceLocation DiagLoc = LSI->IntroducerRange.getEnd();
1289
0
  assert(!LSI->isCXXThisCaptured());
1290
  //  [=, this] {};   // until C++20: Error: this when = is the default
1291
0
  if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval &&
1292
0
      !Sema.getLangOpts().CPlusPlus20)
1293
0
    return;
1294
0
  Sema.Diag(DiagLoc, diag::note_lambda_this_capture_fixit)
1295
0
      << FixItHint::CreateInsertion(
1296
0
             DiagLoc, LSI->NumExplicitCaptures > 0 ? ", this" : "this");
1297
0
}
1298
1299
bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1300
    bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1301
0
    const bool ByCopy) {
1302
  // We don't need to capture this in an unevaluated context.
1303
0
  if (isUnevaluatedContext() && !Explicit)
1304
0
    return true;
1305
1306
0
  assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
1307
1308
0
  const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1309
0
                                         ? *FunctionScopeIndexToStopAt
1310
0
                                         : FunctionScopes.size() - 1;
1311
1312
  // Check that we can capture the *enclosing object* (referred to by '*this')
1313
  // by the capturing-entity/closure (lambda/block/etc) at
1314
  // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1315
1316
  // Note: The *enclosing object* can only be captured by-value by a
1317
  // closure that is a lambda, using the explicit notation:
1318
  //    [*this] { ... }.
1319
  // Every other capture of the *enclosing object* results in its by-reference
1320
  // capture.
1321
1322
  // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1323
  // stack), we can capture the *enclosing object* only if:
1324
  // - 'L' has an explicit byref or byval capture of the *enclosing object*
1325
  // -  or, 'L' has an implicit capture.
1326
  // AND
1327
  //   -- there is no enclosing closure
1328
  //   -- or, there is some enclosing closure 'E' that has already captured the
1329
  //      *enclosing object*, and every intervening closure (if any) between 'E'
1330
  //      and 'L' can implicitly capture the *enclosing object*.
1331
  //   -- or, every enclosing closure can implicitly capture the
1332
  //      *enclosing object*
1333
1334
1335
0
  unsigned NumCapturingClosures = 0;
1336
0
  for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
1337
0
    if (CapturingScopeInfo *CSI =
1338
0
            dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1339
0
      if (CSI->CXXThisCaptureIndex != 0) {
1340
        // 'this' is already being captured; there isn't anything more to do.
1341
0
        CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1342
0
        break;
1343
0
      }
1344
0
      LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1345
0
      if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1346
        // This context can't implicitly capture 'this'; fail out.
1347
0
        if (BuildAndDiagnose) {
1348
0
          LSI->CallOperator->setInvalidDecl();
1349
0
          Diag(Loc, diag::err_this_capture)
1350
0
              << (Explicit && idx == MaxFunctionScopesIndex);
1351
0
          if (!Explicit)
1352
0
            buildLambdaThisCaptureFixit(*this, LSI);
1353
0
        }
1354
0
        return true;
1355
0
      }
1356
0
      if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1357
0
          CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1358
0
          CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1359
0
          CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1360
0
          (Explicit && idx == MaxFunctionScopesIndex)) {
1361
        // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1362
        // iteration through can be an explicit capture, all enclosing closures,
1363
        // if any, must perform implicit captures.
1364
1365
        // This closure can capture 'this'; continue looking upwards.
1366
0
        NumCapturingClosures++;
1367
0
        continue;
1368
0
      }
1369
      // This context can't implicitly capture 'this'; fail out.
1370
0
      if (BuildAndDiagnose) {
1371
0
        LSI->CallOperator->setInvalidDecl();
1372
0
        Diag(Loc, diag::err_this_capture)
1373
0
            << (Explicit && idx == MaxFunctionScopesIndex);
1374
0
      }
1375
0
      if (!Explicit)
1376
0
        buildLambdaThisCaptureFixit(*this, LSI);
1377
0
      return true;
1378
0
    }
1379
0
    break;
1380
0
  }
1381
0
  if (!BuildAndDiagnose) return false;
1382
1383
  // If we got here, then the closure at MaxFunctionScopesIndex on the
1384
  // FunctionScopes stack, can capture the *enclosing object*, so capture it
1385
  // (including implicit by-reference captures in any enclosing closures).
1386
1387
  // In the loop below, respect the ByCopy flag only for the closure requesting
1388
  // the capture (i.e. first iteration through the loop below).  Ignore it for
1389
  // all enclosing closure's up to NumCapturingClosures (since they must be
1390
  // implicitly capturing the *enclosing  object* by reference (see loop
1391
  // above)).
1392
0
  assert((!ByCopy ||
1393
0
          isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1394
0
         "Only a lambda can capture the enclosing object (referred to by "
1395
0
         "*this) by copy");
1396
0
  QualType ThisTy = getCurrentThisType();
1397
0
  for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1398
0
       --idx, --NumCapturingClosures) {
1399
0
    CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1400
1401
    // The type of the corresponding data member (not a 'this' pointer if 'by
1402
    // copy').
1403
0
    QualType CaptureType = ByCopy ? ThisTy->getPointeeType() : ThisTy;
1404
1405
0
    bool isNested = NumCapturingClosures > 1;
1406
0
    CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);
1407
0
  }
1408
0
  return false;
1409
0
}
1410
1411
0
ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
1412
  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1413
  /// is a non-lvalue expression whose value is the address of the object for
1414
  /// which the function is called.
1415
0
  QualType ThisTy = getCurrentThisType();
1416
1417
0
  if (ThisTy.isNull()) {
1418
0
    DeclContext *DC = getFunctionLevelDeclContext();
1419
1420
0
    if (const auto *Method = dyn_cast<CXXMethodDecl>(DC);
1421
0
        Method && Method->isExplicitObjectMemberFunction()) {
1422
0
      return Diag(Loc, diag::err_invalid_this_use) << 1;
1423
0
    }
1424
1425
0
    if (isLambdaCallWithExplicitObjectParameter(CurContext))
1426
0
      return Diag(Loc, diag::err_invalid_this_use) << 1;
1427
1428
0
    return Diag(Loc, diag::err_invalid_this_use) << 0;
1429
0
  }
1430
1431
0
  return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
1432
0
}
1433
1434
Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type,
1435
0
                             bool IsImplicit) {
1436
0
  auto *This = CXXThisExpr::Create(Context, Loc, Type, IsImplicit);
1437
0
  MarkThisReferenced(This);
1438
0
  return This;
1439
0
}
1440
1441
0
void Sema::MarkThisReferenced(CXXThisExpr *This) {
1442
0
  CheckCXXThisCapture(This->getExprLoc());
1443
0
}
1444
1445
0
bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1446
  // If we're outside the body of a member function, then we'll have a specified
1447
  // type for 'this'.
1448
0
  if (CXXThisTypeOverride.isNull())
1449
0
    return false;
1450
1451
  // Determine whether we're looking into a class that's currently being
1452
  // defined.
1453
0
  CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1454
0
  return Class && Class->isBeingDefined();
1455
0
}
1456
1457
/// Parse construction of a specified type.
1458
/// Can be interpreted either as function-style casting ("int(x)")
1459
/// or class type construction ("ClassType(x,y,z)")
1460
/// or creation of a value-initialized type ("int()").
1461
ExprResult
1462
Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
1463
                                SourceLocation LParenOrBraceLoc,
1464
                                MultiExprArg exprs,
1465
                                SourceLocation RParenOrBraceLoc,
1466
0
                                bool ListInitialization) {
1467
0
  if (!TypeRep)
1468
0
    return ExprError();
1469
1470
0
  TypeSourceInfo *TInfo;
1471
0
  QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1472
0
  if (!TInfo)
1473
0
    TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
1474
1475
0
  auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1476
0
                                          RParenOrBraceLoc, ListInitialization);
1477
  // Avoid creating a non-type-dependent expression that contains typos.
1478
  // Non-type-dependent expressions are liable to be discarded without
1479
  // checking for embedded typos.
1480
0
  if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1481
0
      !Result.get()->isTypeDependent())
1482
0
    Result = CorrectDelayedTyposInExpr(Result.get());
1483
0
  else if (Result.isInvalid())
1484
0
    Result = CreateRecoveryExpr(TInfo->getTypeLoc().getBeginLoc(),
1485
0
                                RParenOrBraceLoc, exprs, Ty);
1486
0
  return Result;
1487
0
}
1488
1489
ExprResult
1490
Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1491
                                SourceLocation LParenOrBraceLoc,
1492
                                MultiExprArg Exprs,
1493
                                SourceLocation RParenOrBraceLoc,
1494
0
                                bool ListInitialization) {
1495
0
  QualType Ty = TInfo->getType();
1496
0
  SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1497
1498
0
  assert((!ListInitialization || Exprs.size() == 1) &&
1499
0
         "List initialization must have exactly one expression.");
1500
0
  SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1501
1502
0
  InitializedEntity Entity =
1503
0
      InitializedEntity::InitializeTemporary(Context, TInfo);
1504
0
  InitializationKind Kind =
1505
0
      Exprs.size()
1506
0
          ? ListInitialization
1507
0
                ? InitializationKind::CreateDirectList(
1508
0
                      TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1509
0
                : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1510
0
                                                   RParenOrBraceLoc)
1511
0
          : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1512
0
                                            RParenOrBraceLoc);
1513
1514
  // C++17 [expr.type.conv]p1:
1515
  //   If the type is a placeholder for a deduced class type, [...perform class
1516
  //   template argument deduction...]
1517
  // C++23:
1518
  //   Otherwise, if the type contains a placeholder type, it is replaced by the
1519
  //   type determined by placeholder type deduction.
1520
0
  DeducedType *Deduced = Ty->getContainedDeducedType();
1521
0
  if (Deduced && !Deduced->isDeduced() &&
1522
0
      isa<DeducedTemplateSpecializationType>(Deduced)) {
1523
0
    Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1524
0
                                                     Kind, Exprs);
1525
0
    if (Ty.isNull())
1526
0
      return ExprError();
1527
0
    Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1528
0
  } else if (Deduced && !Deduced->isDeduced()) {
1529
0
    MultiExprArg Inits = Exprs;
1530
0
    if (ListInitialization) {
1531
0
      auto *ILE = cast<InitListExpr>(Exprs[0]);
1532
0
      Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
1533
0
    }
1534
1535
0
    if (Inits.empty())
1536
0
      return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_init_no_expression)
1537
0
                       << Ty << FullRange);
1538
0
    if (Inits.size() > 1) {
1539
0
      Expr *FirstBad = Inits[1];
1540
0
      return ExprError(Diag(FirstBad->getBeginLoc(),
1541
0
                            diag::err_auto_expr_init_multiple_expressions)
1542
0
                       << Ty << FullRange);
1543
0
    }
1544
0
    if (getLangOpts().CPlusPlus23) {
1545
0
      if (Ty->getAs<AutoType>())
1546
0
        Diag(TyBeginLoc, diag::warn_cxx20_compat_auto_expr) << FullRange;
1547
0
    }
1548
0
    Expr *Deduce = Inits[0];
1549
0
    if (isa<InitListExpr>(Deduce))
1550
0
      return ExprError(
1551
0
          Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
1552
0
          << ListInitialization << Ty << FullRange);
1553
0
    QualType DeducedType;
1554
0
    TemplateDeductionInfo Info(Deduce->getExprLoc());
1555
0
    TemplateDeductionResult Result =
1556
0
        DeduceAutoType(TInfo->getTypeLoc(), Deduce, DeducedType, Info);
1557
0
    if (Result != TDK_Success && Result != TDK_AlreadyDiagnosed)
1558
0
      return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_deduction_failure)
1559
0
                       << Ty << Deduce->getType() << FullRange
1560
0
                       << Deduce->getSourceRange());
1561
0
    if (DeducedType.isNull()) {
1562
0
      assert(Result == TDK_AlreadyDiagnosed);
1563
0
      return ExprError();
1564
0
    }
1565
1566
0
    Ty = DeducedType;
1567
0
    Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1568
0
  }
1569
1570
0
  if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs))
1571
0
    return CXXUnresolvedConstructExpr::Create(
1572
0
        Context, Ty.getNonReferenceType(), TInfo, LParenOrBraceLoc, Exprs,
1573
0
        RParenOrBraceLoc, ListInitialization);
1574
1575
  // C++ [expr.type.conv]p1:
1576
  // If the expression list is a parenthesized single expression, the type
1577
  // conversion expression is equivalent (in definedness, and if defined in
1578
  // meaning) to the corresponding cast expression.
1579
0
  if (Exprs.size() == 1 && !ListInitialization &&
1580
0
      !isa<InitListExpr>(Exprs[0])) {
1581
0
    Expr *Arg = Exprs[0];
1582
0
    return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1583
0
                                      RParenOrBraceLoc);
1584
0
  }
1585
1586
  //   For an expression of the form T(), T shall not be an array type.
1587
0
  QualType ElemTy = Ty;
1588
0
  if (Ty->isArrayType()) {
1589
0
    if (!ListInitialization)
1590
0
      return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1591
0
                         << FullRange);
1592
0
    ElemTy = Context.getBaseElementType(Ty);
1593
0
  }
1594
1595
  // Only construct objects with object types.
1596
  // The standard doesn't explicitly forbid function types here, but that's an
1597
  // obvious oversight, as there's no way to dynamically construct a function
1598
  // in general.
1599
0
  if (Ty->isFunctionType())
1600
0
    return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1601
0
                       << Ty << FullRange);
1602
1603
  // C++17 [expr.type.conv]p2:
1604
  //   If the type is cv void and the initializer is (), the expression is a
1605
  //   prvalue of the specified type that performs no initialization.
1606
0
  if (!Ty->isVoidType() &&
1607
0
      RequireCompleteType(TyBeginLoc, ElemTy,
1608
0
                          diag::err_invalid_incomplete_type_use, FullRange))
1609
0
    return ExprError();
1610
1611
  //   Otherwise, the expression is a prvalue of the specified type whose
1612
  //   result object is direct-initialized (11.6) with the initializer.
1613
0
  InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1614
0
  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1615
1616
0
  if (Result.isInvalid())
1617
0
    return Result;
1618
1619
0
  Expr *Inner = Result.get();
1620
0
  if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1621
0
    Inner = BTE->getSubExpr();
1622
0
  if (auto *CE = dyn_cast<ConstantExpr>(Inner);
1623
0
      CE && CE->isImmediateInvocation())
1624
0
    Inner = CE->getSubExpr();
1625
0
  if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1626
0
      !isa<CXXScalarValueInitExpr>(Inner)) {
1627
    // If we created a CXXTemporaryObjectExpr, that node also represents the
1628
    // functional cast. Otherwise, create an explicit cast to represent
1629
    // the syntactic form of a functional-style cast that was used here.
1630
    //
1631
    // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1632
    // would give a more consistent AST representation than using a
1633
    // CXXTemporaryObjectExpr. It's also weird that the functional cast
1634
    // is sometimes handled by initialization and sometimes not.
1635
0
    QualType ResultType = Result.get()->getType();
1636
0
    SourceRange Locs = ListInitialization
1637
0
                           ? SourceRange()
1638
0
                           : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1639
0
    Result = CXXFunctionalCastExpr::Create(
1640
0
        Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1641
0
        Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(),
1642
0
        Locs.getBegin(), Locs.getEnd());
1643
0
  }
1644
1645
0
  return Result;
1646
0
}
1647
1648
0
bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) {
1649
  // [CUDA] Ignore this function, if we can't call it.
1650
0
  const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
1651
0
  if (getLangOpts().CUDA) {
1652
0
    auto CallPreference = IdentifyCUDAPreference(Caller, Method);
1653
    // If it's not callable at all, it's not the right function.
1654
0
    if (CallPreference < CFP_WrongSide)
1655
0
      return false;
1656
0
    if (CallPreference == CFP_WrongSide) {
1657
      // Maybe. We have to check if there are better alternatives.
1658
0
      DeclContext::lookup_result R =
1659
0
          Method->getDeclContext()->lookup(Method->getDeclName());
1660
0
      for (const auto *D : R) {
1661
0
        if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1662
0
          if (IdentifyCUDAPreference(Caller, FD) > CFP_WrongSide)
1663
0
            return false;
1664
0
        }
1665
0
      }
1666
      // We've found no better variants.
1667
0
    }
1668
0
  }
1669
1670
0
  SmallVector<const FunctionDecl*, 4> PreventedBy;
1671
0
  bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1672
1673
0
  if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1674
0
    return Result;
1675
1676
  // In case of CUDA, return true if none of the 1-argument deallocator
1677
  // functions are actually callable.
1678
0
  return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1679
0
    assert(FD->getNumParams() == 1 &&
1680
0
           "Only single-operand functions should be in PreventedBy");
1681
0
    return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice;
1682
0
  });
1683
0
}
1684
1685
/// Determine whether the given function is a non-placement
1686
/// deallocation function.
1687
0
static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1688
0
  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1689
0
    return S.isUsualDeallocationFunction(Method);
1690
1691
0
  if (FD->getOverloadedOperator() != OO_Delete &&
1692
0
      FD->getOverloadedOperator() != OO_Array_Delete)
1693
0
    return false;
1694
1695
0
  unsigned UsualParams = 1;
1696
1697
0
  if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1698
0
      S.Context.hasSameUnqualifiedType(
1699
0
          FD->getParamDecl(UsualParams)->getType(),
1700
0
          S.Context.getSizeType()))
1701
0
    ++UsualParams;
1702
1703
0
  if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1704
0
      S.Context.hasSameUnqualifiedType(
1705
0
          FD->getParamDecl(UsualParams)->getType(),
1706
0
          S.Context.getTypeDeclType(S.getStdAlignValT())))
1707
0
    ++UsualParams;
1708
1709
0
  return UsualParams == FD->getNumParams();
1710
0
}
1711
1712
namespace {
1713
  struct UsualDeallocFnInfo {
1714
0
    UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1715
    UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1716
        : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1717
          Destroying(false), HasSizeT(false), HasAlignValT(false),
1718
0
          CUDAPref(Sema::CFP_Native) {
1719
      // A function template declaration is never a usual deallocation function.
1720
0
      if (!FD)
1721
0
        return;
1722
0
      unsigned NumBaseParams = 1;
1723
0
      if (FD->isDestroyingOperatorDelete()) {
1724
0
        Destroying = true;
1725
0
        ++NumBaseParams;
1726
0
      }
1727
1728
0
      if (NumBaseParams < FD->getNumParams() &&
1729
0
          S.Context.hasSameUnqualifiedType(
1730
0
              FD->getParamDecl(NumBaseParams)->getType(),
1731
0
              S.Context.getSizeType())) {
1732
0
        ++NumBaseParams;
1733
0
        HasSizeT = true;
1734
0
      }
1735
1736
0
      if (NumBaseParams < FD->getNumParams() &&
1737
0
          FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1738
0
        ++NumBaseParams;
1739
0
        HasAlignValT = true;
1740
0
      }
1741
1742
      // In CUDA, determine how much we'd like / dislike to call this.
1743
0
      if (S.getLangOpts().CUDA)
1744
0
        CUDAPref = S.IdentifyCUDAPreference(
1745
0
            S.getCurFunctionDecl(/*AllowLambda=*/true), FD);
1746
0
    }
1747
1748
0
    explicit operator bool() const { return FD; }
1749
1750
    bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1751
0
                      bool WantAlign) const {
1752
      // C++ P0722:
1753
      //   A destroying operator delete is preferred over a non-destroying
1754
      //   operator delete.
1755
0
      if (Destroying != Other.Destroying)
1756
0
        return Destroying;
1757
1758
      // C++17 [expr.delete]p10:
1759
      //   If the type has new-extended alignment, a function with a parameter
1760
      //   of type std::align_val_t is preferred; otherwise a function without
1761
      //   such a parameter is preferred
1762
0
      if (HasAlignValT != Other.HasAlignValT)
1763
0
        return HasAlignValT == WantAlign;
1764
1765
0
      if (HasSizeT != Other.HasSizeT)
1766
0
        return HasSizeT == WantSize;
1767
1768
      // Use CUDA call preference as a tiebreaker.
1769
0
      return CUDAPref > Other.CUDAPref;
1770
0
    }
1771
1772
    DeclAccessPair Found;
1773
    FunctionDecl *FD;
1774
    bool Destroying, HasSizeT, HasAlignValT;
1775
    Sema::CUDAFunctionPreference CUDAPref;
1776
  };
1777
}
1778
1779
/// Determine whether a type has new-extended alignment. This may be called when
1780
/// the type is incomplete (for a delete-expression with an incomplete pointee
1781
/// type), in which case it will conservatively return false if the alignment is
1782
/// not known.
1783
0
static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1784
0
  return S.getLangOpts().AlignedAllocation &&
1785
0
         S.getASTContext().getTypeAlignIfKnown(AllocType) >
1786
0
             S.getASTContext().getTargetInfo().getNewAlign();
1787
0
}
1788
1789
/// Select the correct "usual" deallocation function to use from a selection of
1790
/// deallocation functions (either global or class-scope).
1791
static UsualDeallocFnInfo resolveDeallocationOverload(
1792
    Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1793
0
    llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1794
0
  UsualDeallocFnInfo Best;
1795
1796
0
  for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1797
0
    UsualDeallocFnInfo Info(S, I.getPair());
1798
0
    if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1799
0
        Info.CUDAPref == Sema::CFP_Never)
1800
0
      continue;
1801
1802
0
    if (!Best) {
1803
0
      Best = Info;
1804
0
      if (BestFns)
1805
0
        BestFns->push_back(Info);
1806
0
      continue;
1807
0
    }
1808
1809
0
    if (Best.isBetterThan(Info, WantSize, WantAlign))
1810
0
      continue;
1811
1812
    //   If more than one preferred function is found, all non-preferred
1813
    //   functions are eliminated from further consideration.
1814
0
    if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1815
0
      BestFns->clear();
1816
1817
0
    Best = Info;
1818
0
    if (BestFns)
1819
0
      BestFns->push_back(Info);
1820
0
  }
1821
1822
0
  return Best;
1823
0
}
1824
1825
/// Determine whether a given type is a class for which 'delete[]' would call
1826
/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1827
/// we need to store the array size (even if the type is
1828
/// trivially-destructible).
1829
static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1830
0
                                         QualType allocType) {
1831
0
  const RecordType *record =
1832
0
    allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1833
0
  if (!record) return false;
1834
1835
  // Try to find an operator delete[] in class scope.
1836
1837
0
  DeclarationName deleteName =
1838
0
    S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1839
0
  LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1840
0
  S.LookupQualifiedName(ops, record->getDecl());
1841
1842
  // We're just doing this for information.
1843
0
  ops.suppressDiagnostics();
1844
1845
  // Very likely: there's no operator delete[].
1846
0
  if (ops.empty()) return false;
1847
1848
  // If it's ambiguous, it should be illegal to call operator delete[]
1849
  // on this thing, so it doesn't matter if we allocate extra space or not.
1850
0
  if (ops.isAmbiguous()) return false;
1851
1852
  // C++17 [expr.delete]p10:
1853
  //   If the deallocation functions have class scope, the one without a
1854
  //   parameter of type std::size_t is selected.
1855
0
  auto Best = resolveDeallocationOverload(
1856
0
      S, ops, /*WantSize*/false,
1857
0
      /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1858
0
  return Best && Best.HasSizeT;
1859
0
}
1860
1861
/// Parsed a C++ 'new' expression (C++ 5.3.4).
1862
///
1863
/// E.g.:
1864
/// @code new (memory) int[size][4] @endcode
1865
/// or
1866
/// @code ::new Foo(23, "hello") @endcode
1867
///
1868
/// \param StartLoc The first location of the expression.
1869
/// \param UseGlobal True if 'new' was prefixed with '::'.
1870
/// \param PlacementLParen Opening paren of the placement arguments.
1871
/// \param PlacementArgs Placement new arguments.
1872
/// \param PlacementRParen Closing paren of the placement arguments.
1873
/// \param TypeIdParens If the type is in parens, the source range.
1874
/// \param D The type to be allocated, as well as array dimensions.
1875
/// \param Initializer The initializing expression or initializer-list, or null
1876
///   if there is none.
1877
ExprResult
1878
Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1879
                  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1880
                  SourceLocation PlacementRParen, SourceRange TypeIdParens,
1881
0
                  Declarator &D, Expr *Initializer) {
1882
0
  std::optional<Expr *> ArraySize;
1883
  // If the specified type is an array, unwrap it and save the expression.
1884
0
  if (D.getNumTypeObjects() > 0 &&
1885
0
      D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1886
0
    DeclaratorChunk &Chunk = D.getTypeObject(0);
1887
0
    if (D.getDeclSpec().hasAutoTypeSpec())
1888
0
      return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1889
0
        << D.getSourceRange());
1890
0
    if (Chunk.Arr.hasStatic)
1891
0
      return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1892
0
        << D.getSourceRange());
1893
0
    if (!Chunk.Arr.NumElts && !Initializer)
1894
0
      return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1895
0
        << D.getSourceRange());
1896
1897
0
    ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1898
0
    D.DropFirstTypeObject();
1899
0
  }
1900
1901
  // Every dimension shall be of constant size.
1902
0
  if (ArraySize) {
1903
0
    for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1904
0
      if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1905
0
        break;
1906
1907
0
      DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1908
0
      if (Expr *NumElts = (Expr *)Array.NumElts) {
1909
0
        if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1910
          // FIXME: GCC permits constant folding here. We should either do so consistently
1911
          // or not do so at all, rather than changing behavior in C++14 onwards.
1912
0
          if (getLangOpts().CPlusPlus14) {
1913
            // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1914
            //   shall be a converted constant expression (5.19) of type std::size_t
1915
            //   and shall evaluate to a strictly positive value.
1916
0
            llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));
1917
0
            Array.NumElts
1918
0
             = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1919
0
                                                CCEK_ArrayBound)
1920
0
                 .get();
1921
0
          } else {
1922
0
            Array.NumElts =
1923
0
                VerifyIntegerConstantExpression(
1924
0
                    NumElts, nullptr, diag::err_new_array_nonconst, AllowFold)
1925
0
                    .get();
1926
0
          }
1927
0
          if (!Array.NumElts)
1928
0
            return ExprError();
1929
0
        }
1930
0
      }
1931
0
    }
1932
0
  }
1933
1934
0
  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1935
0
  QualType AllocType = TInfo->getType();
1936
0
  if (D.isInvalidType())
1937
0
    return ExprError();
1938
1939
0
  SourceRange DirectInitRange;
1940
0
  if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1941
0
    DirectInitRange = List->getSourceRange();
1942
1943
0
  return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1944
0
                     PlacementLParen, PlacementArgs, PlacementRParen,
1945
0
                     TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
1946
0
                     Initializer);
1947
0
}
1948
1949
static bool isLegalArrayNewInitializer(CXXNewInitializationStyle Style,
1950
0
                                       Expr *Init) {
1951
0
  if (!Init)
1952
0
    return true;
1953
0
  if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1954
0
    return PLE->getNumExprs() == 0;
1955
0
  if (isa<ImplicitValueInitExpr>(Init))
1956
0
    return true;
1957
0
  else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1958
0
    return !CCE->isListInitialization() &&
1959
0
           CCE->getConstructor()->isDefaultConstructor();
1960
0
  else if (Style == CXXNewInitializationStyle::List) {
1961
0
    assert(isa<InitListExpr>(Init) &&
1962
0
           "Shouldn't create list CXXConstructExprs for arrays.");
1963
0
    return true;
1964
0
  }
1965
0
  return false;
1966
0
}
1967
1968
bool
1969
0
Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const {
1970
0
  if (!getLangOpts().AlignedAllocationUnavailable)
1971
0
    return false;
1972
0
  if (FD.isDefined())
1973
0
    return false;
1974
0
  std::optional<unsigned> AlignmentParam;
1975
0
  if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) &&
1976
0
      AlignmentParam)
1977
0
    return true;
1978
0
  return false;
1979
0
}
1980
1981
// Emit a diagnostic if an aligned allocation/deallocation function that is not
1982
// implemented in the standard library is selected.
1983
void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1984
0
                                                SourceLocation Loc) {
1985
0
  if (isUnavailableAlignedAllocationFunction(FD)) {
1986
0
    const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
1987
0
    StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1988
0
        getASTContext().getTargetInfo().getPlatformName());
1989
0
    VersionTuple OSVersion = alignedAllocMinVersion(T.getOS());
1990
1991
0
    OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator();
1992
0
    bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
1993
0
    Diag(Loc, diag::err_aligned_allocation_unavailable)
1994
0
        << IsDelete << FD.getType().getAsString() << OSName
1995
0
        << OSVersion.getAsString() << OSVersion.empty();
1996
0
    Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
1997
0
  }
1998
0
}
1999
2000
ExprResult Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
2001
                             SourceLocation PlacementLParen,
2002
                             MultiExprArg PlacementArgs,
2003
                             SourceLocation PlacementRParen,
2004
                             SourceRange TypeIdParens, QualType AllocType,
2005
                             TypeSourceInfo *AllocTypeInfo,
2006
                             std::optional<Expr *> ArraySize,
2007
0
                             SourceRange DirectInitRange, Expr *Initializer) {
2008
0
  SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
2009
0
  SourceLocation StartLoc = Range.getBegin();
2010
2011
0
  CXXNewInitializationStyle InitStyle;
2012
0
  if (DirectInitRange.isValid()) {
2013
0
    assert(Initializer && "Have parens but no initializer.");
2014
0
    InitStyle = CXXNewInitializationStyle::Call;
2015
0
  } else if (Initializer && isa<InitListExpr>(Initializer))
2016
0
    InitStyle = CXXNewInitializationStyle::List;
2017
0
  else {
2018
0
    assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
2019
0
            isa<CXXConstructExpr>(Initializer)) &&
2020
0
           "Initializer expression that cannot have been implicitly created.");
2021
0
    InitStyle = CXXNewInitializationStyle::None;
2022
0
  }
2023
2024
0
  MultiExprArg Exprs(&Initializer, Initializer ? 1 : 0);
2025
0
  if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
2026
0
    assert(InitStyle == CXXNewInitializationStyle::Call &&
2027
0
           "paren init for non-call init");
2028
0
    Exprs = MultiExprArg(List->getExprs(), List->getNumExprs());
2029
0
  }
2030
2031
  // C++11 [expr.new]p15:
2032
  //   A new-expression that creates an object of type T initializes that
2033
  //   object as follows:
2034
0
  InitializationKind Kind = [&] {
2035
0
    switch (InitStyle) {
2036
    //     - If the new-initializer is omitted, the object is default-
2037
    //       initialized (8.5); if no initialization is performed,
2038
    //       the object has indeterminate value
2039
0
    case CXXNewInitializationStyle::None:
2040
0
    case CXXNewInitializationStyle::Implicit:
2041
0
      return InitializationKind::CreateDefault(TypeRange.getBegin());
2042
    //     - Otherwise, the new-initializer is interpreted according to the
2043
    //       initialization rules of 8.5 for direct-initialization.
2044
0
    case CXXNewInitializationStyle::Call:
2045
0
      return InitializationKind::CreateDirect(TypeRange.getBegin(),
2046
0
                                              DirectInitRange.getBegin(),
2047
0
                                              DirectInitRange.getEnd());
2048
0
    case CXXNewInitializationStyle::List:
2049
0
      return InitializationKind::CreateDirectList(TypeRange.getBegin(),
2050
0
                                                  Initializer->getBeginLoc(),
2051
0
                                                  Initializer->getEndLoc());
2052
0
    }
2053
0
    llvm_unreachable("Unknown initialization kind");
2054
0
  }();
2055
2056
  // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
2057
0
  auto *Deduced = AllocType->getContainedDeducedType();
2058
0
  if (Deduced && !Deduced->isDeduced() &&
2059
0
      isa<DeducedTemplateSpecializationType>(Deduced)) {
2060
0
    if (ArraySize)
2061
0
      return ExprError(
2062
0
          Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
2063
0
               diag::err_deduced_class_template_compound_type)
2064
0
          << /*array*/ 2
2065
0
          << (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
2066
2067
0
    InitializedEntity Entity
2068
0
      = InitializedEntity::InitializeNew(StartLoc, AllocType);
2069
0
    AllocType = DeduceTemplateSpecializationFromInitializer(
2070
0
        AllocTypeInfo, Entity, Kind, Exprs);
2071
0
    if (AllocType.isNull())
2072
0
      return ExprError();
2073
0
  } else if (Deduced && !Deduced->isDeduced()) {
2074
0
    MultiExprArg Inits = Exprs;
2075
0
    bool Braced = (InitStyle == CXXNewInitializationStyle::List);
2076
0
    if (Braced) {
2077
0
      auto *ILE = cast<InitListExpr>(Exprs[0]);
2078
0
      Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
2079
0
    }
2080
2081
0
    if (InitStyle == CXXNewInitializationStyle::None ||
2082
0
        InitStyle == CXXNewInitializationStyle::Implicit || Inits.empty())
2083
0
      return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
2084
0
                       << AllocType << TypeRange);
2085
0
    if (Inits.size() > 1) {
2086
0
      Expr *FirstBad = Inits[1];
2087
0
      return ExprError(Diag(FirstBad->getBeginLoc(),
2088
0
                            diag::err_auto_new_ctor_multiple_expressions)
2089
0
                       << AllocType << TypeRange);
2090
0
    }
2091
0
    if (Braced && !getLangOpts().CPlusPlus17)
2092
0
      Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
2093
0
          << AllocType << TypeRange;
2094
0
    Expr *Deduce = Inits[0];
2095
0
    if (isa<InitListExpr>(Deduce))
2096
0
      return ExprError(
2097
0
          Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
2098
0
          << Braced << AllocType << TypeRange);
2099
0
    QualType DeducedType;
2100
0
    TemplateDeductionInfo Info(Deduce->getExprLoc());
2101
0
    TemplateDeductionResult Result =
2102
0
        DeduceAutoType(AllocTypeInfo->getTypeLoc(), Deduce, DeducedType, Info);
2103
0
    if (Result != TDK_Success && Result != TDK_AlreadyDiagnosed)
2104
0
      return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
2105
0
                       << AllocType << Deduce->getType() << TypeRange
2106
0
                       << Deduce->getSourceRange());
2107
0
    if (DeducedType.isNull()) {
2108
0
      assert(Result == TDK_AlreadyDiagnosed);
2109
0
      return ExprError();
2110
0
    }
2111
0
    AllocType = DeducedType;
2112
0
  }
2113
2114
  // Per C++0x [expr.new]p5, the type being constructed may be a
2115
  // typedef of an array type.
2116
0
  if (!ArraySize) {
2117
0
    if (const ConstantArrayType *Array
2118
0
                              = Context.getAsConstantArrayType(AllocType)) {
2119
0
      ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
2120
0
                                         Context.getSizeType(),
2121
0
                                         TypeRange.getEnd());
2122
0
      AllocType = Array->getElementType();
2123
0
    }
2124
0
  }
2125
2126
0
  if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
2127
0
    return ExprError();
2128
2129
0
  if (ArraySize && !checkArrayElementAlignment(AllocType, TypeRange.getBegin()))
2130
0
    return ExprError();
2131
2132
  // In ARC, infer 'retaining' for the allocated
2133
0
  if (getLangOpts().ObjCAutoRefCount &&
2134
0
      AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2135
0
      AllocType->isObjCLifetimeType()) {
2136
0
    AllocType = Context.getLifetimeQualifiedType(AllocType,
2137
0
                                    AllocType->getObjCARCImplicitLifetime());
2138
0
  }
2139
2140
0
  QualType ResultType = Context.getPointerType(AllocType);
2141
2142
0
  if (ArraySize && *ArraySize &&
2143
0
      (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
2144
0
    ExprResult result = CheckPlaceholderExpr(*ArraySize);
2145
0
    if (result.isInvalid()) return ExprError();
2146
0
    ArraySize = result.get();
2147
0
  }
2148
  // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
2149
  //   integral or enumeration type with a non-negative value."
2150
  // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
2151
  //   enumeration type, or a class type for which a single non-explicit
2152
  //   conversion function to integral or unscoped enumeration type exists.
2153
  // C++1y [expr.new]p6: The expression [...] is implicitly converted to
2154
  //   std::size_t.
2155
0
  std::optional<uint64_t> KnownArraySize;
2156
0
  if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
2157
0
    ExprResult ConvertedSize;
2158
0
    if (getLangOpts().CPlusPlus14) {
2159
0
      assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
2160
2161
0
      ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(),
2162
0
                                                AA_Converting);
2163
2164
0
      if (!ConvertedSize.isInvalid() &&
2165
0
          (*ArraySize)->getType()->getAs<RecordType>())
2166
        // Diagnose the compatibility of this conversion.
2167
0
        Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
2168
0
          << (*ArraySize)->getType() << 0 << "'size_t'";
2169
0
    } else {
2170
0
      class SizeConvertDiagnoser : public ICEConvertDiagnoser {
2171
0
      protected:
2172
0
        Expr *ArraySize;
2173
2174
0
      public:
2175
0
        SizeConvertDiagnoser(Expr *ArraySize)
2176
0
            : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
2177
0
              ArraySize(ArraySize) {}
2178
2179
0
        SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
2180
0
                                             QualType T) override {
2181
0
          return S.Diag(Loc, diag::err_array_size_not_integral)
2182
0
                   << S.getLangOpts().CPlusPlus11 << T;
2183
0
        }
2184
2185
0
        SemaDiagnosticBuilder diagnoseIncomplete(
2186
0
            Sema &S, SourceLocation Loc, QualType T) override {
2187
0
          return S.Diag(Loc, diag::err_array_size_incomplete_type)
2188
0
                   << T << ArraySize->getSourceRange();
2189
0
        }
2190
2191
0
        SemaDiagnosticBuilder diagnoseExplicitConv(
2192
0
            Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
2193
0
          return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
2194
0
        }
2195
2196
0
        SemaDiagnosticBuilder noteExplicitConv(
2197
0
            Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2198
0
          return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2199
0
                   << ConvTy->isEnumeralType() << ConvTy;
2200
0
        }
2201
2202
0
        SemaDiagnosticBuilder diagnoseAmbiguous(
2203
0
            Sema &S, SourceLocation Loc, QualType T) override {
2204
0
          return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
2205
0
        }
2206
2207
0
        SemaDiagnosticBuilder noteAmbiguous(
2208
0
            Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2209
0
          return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2210
0
                   << ConvTy->isEnumeralType() << ConvTy;
2211
0
        }
2212
2213
0
        SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2214
0
                                                 QualType T,
2215
0
                                                 QualType ConvTy) override {
2216
0
          return S.Diag(Loc,
2217
0
                        S.getLangOpts().CPlusPlus11
2218
0
                          ? diag::warn_cxx98_compat_array_size_conversion
2219
0
                          : diag::ext_array_size_conversion)
2220
0
                   << T << ConvTy->isEnumeralType() << ConvTy;
2221
0
        }
2222
0
      } SizeDiagnoser(*ArraySize);
2223
2224
0
      ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
2225
0
                                                          SizeDiagnoser);
2226
0
    }
2227
0
    if (ConvertedSize.isInvalid())
2228
0
      return ExprError();
2229
2230
0
    ArraySize = ConvertedSize.get();
2231
0
    QualType SizeType = (*ArraySize)->getType();
2232
2233
0
    if (!SizeType->isIntegralOrUnscopedEnumerationType())
2234
0
      return ExprError();
2235
2236
    // C++98 [expr.new]p7:
2237
    //   The expression in a direct-new-declarator shall have integral type
2238
    //   with a non-negative value.
2239
    //
2240
    // Let's see if this is a constant < 0. If so, we reject it out of hand,
2241
    // per CWG1464. Otherwise, if it's not a constant, we must have an
2242
    // unparenthesized array type.
2243
2244
    // We've already performed any required implicit conversion to integer or
2245
    // unscoped enumeration type.
2246
    // FIXME: Per CWG1464, we are required to check the value prior to
2247
    // converting to size_t. This will never find a negative array size in
2248
    // C++14 onwards, because Value is always unsigned here!
2249
0
    if (std::optional<llvm::APSInt> Value =
2250
0
            (*ArraySize)->getIntegerConstantExpr(Context)) {
2251
0
      if (Value->isSigned() && Value->isNegative()) {
2252
0
        return ExprError(Diag((*ArraySize)->getBeginLoc(),
2253
0
                              diag::err_typecheck_negative_array_size)
2254
0
                         << (*ArraySize)->getSourceRange());
2255
0
      }
2256
2257
0
      if (!AllocType->isDependentType()) {
2258
0
        unsigned ActiveSizeBits =
2259
0
            ConstantArrayType::getNumAddressingBits(Context, AllocType, *Value);
2260
0
        if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2261
0
          return ExprError(
2262
0
              Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2263
0
              << toString(*Value, 10) << (*ArraySize)->getSourceRange());
2264
0
      }
2265
2266
0
      KnownArraySize = Value->getZExtValue();
2267
0
    } else if (TypeIdParens.isValid()) {
2268
      // Can't have dynamic array size when the type-id is in parentheses.
2269
0
      Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2270
0
          << (*ArraySize)->getSourceRange()
2271
0
          << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2272
0
          << FixItHint::CreateRemoval(TypeIdParens.getEnd());
2273
2274
0
      TypeIdParens = SourceRange();
2275
0
    }
2276
2277
    // Note that we do *not* convert the argument in any way.  It can
2278
    // be signed, larger than size_t, whatever.
2279
0
  }
2280
2281
0
  FunctionDecl *OperatorNew = nullptr;
2282
0
  FunctionDecl *OperatorDelete = nullptr;
2283
0
  unsigned Alignment =
2284
0
      AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2285
0
  unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2286
0
  bool PassAlignment = getLangOpts().AlignedAllocation &&
2287
0
                       Alignment > NewAlignment;
2288
2289
0
  AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both;
2290
0
  if (!AllocType->isDependentType() &&
2291
0
      !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
2292
0
      FindAllocationFunctions(
2293
0
          StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope,
2294
0
          AllocType, ArraySize.has_value(), PassAlignment, PlacementArgs,
2295
0
          OperatorNew, OperatorDelete))
2296
0
    return ExprError();
2297
2298
  // If this is an array allocation, compute whether the usual array
2299
  // deallocation function for the type has a size_t parameter.
2300
0
  bool UsualArrayDeleteWantsSize = false;
2301
0
  if (ArraySize && !AllocType->isDependentType())
2302
0
    UsualArrayDeleteWantsSize =
2303
0
        doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
2304
2305
0
  SmallVector<Expr *, 8> AllPlaceArgs;
2306
0
  if (OperatorNew) {
2307
0
    auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2308
0
    VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2309
0
                                                    : VariadicDoesNotApply;
2310
2311
    // We've already converted the placement args, just fill in any default
2312
    // arguments. Skip the first parameter because we don't have a corresponding
2313
    // argument. Skip the second parameter too if we're passing in the
2314
    // alignment; we've already filled it in.
2315
0
    unsigned NumImplicitArgs = PassAlignment ? 2 : 1;
2316
0
    if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2317
0
                               NumImplicitArgs, PlacementArgs, AllPlaceArgs,
2318
0
                               CallType))
2319
0
      return ExprError();
2320
2321
0
    if (!AllPlaceArgs.empty())
2322
0
      PlacementArgs = AllPlaceArgs;
2323
2324
    // We would like to perform some checking on the given `operator new` call,
2325
    // but the PlacementArgs does not contain the implicit arguments,
2326
    // namely allocation size and maybe allocation alignment,
2327
    // so we need to conjure them.
2328
2329
0
    QualType SizeTy = Context.getSizeType();
2330
0
    unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2331
2332
0
    llvm::APInt SingleEltSize(
2333
0
        SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity());
2334
2335
    // How many bytes do we want to allocate here?
2336
0
    std::optional<llvm::APInt> AllocationSize;
2337
0
    if (!ArraySize && !AllocType->isDependentType()) {
2338
      // For non-array operator new, we only want to allocate one element.
2339
0
      AllocationSize = SingleEltSize;
2340
0
    } else if (KnownArraySize && !AllocType->isDependentType()) {
2341
      // For array operator new, only deal with static array size case.
2342
0
      bool Overflow;
2343
0
      AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize)
2344
0
                           .umul_ov(SingleEltSize, Overflow);
2345
0
      (void)Overflow;
2346
0
      assert(
2347
0
          !Overflow &&
2348
0
          "Expected that all the overflows would have been handled already.");
2349
0
    }
2350
2351
0
    IntegerLiteral AllocationSizeLiteral(
2352
0
        Context, AllocationSize.value_or(llvm::APInt::getZero(SizeTyWidth)),
2353
0
        SizeTy, SourceLocation());
2354
    // Otherwise, if we failed to constant-fold the allocation size, we'll
2355
    // just give up and pass-in something opaque, that isn't a null pointer.
2356
0
    OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_PRValue,
2357
0
                                         OK_Ordinary, /*SourceExpr=*/nullptr);
2358
2359
    // Let's synthesize the alignment argument in case we will need it.
2360
    // Since we *really* want to allocate these on stack, this is slightly ugly
2361
    // because there might not be a `std::align_val_t` type.
2362
0
    EnumDecl *StdAlignValT = getStdAlignValT();
2363
0
    QualType AlignValT =
2364
0
        StdAlignValT ? Context.getTypeDeclType(StdAlignValT) : SizeTy;
2365
0
    IntegerLiteral AlignmentLiteral(
2366
0
        Context,
2367
0
        llvm::APInt(Context.getTypeSize(SizeTy),
2368
0
                    Alignment / Context.getCharWidth()),
2369
0
        SizeTy, SourceLocation());
2370
0
    ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT,
2371
0
                                      CK_IntegralCast, &AlignmentLiteral,
2372
0
                                      VK_PRValue, FPOptionsOverride());
2373
2374
    // Adjust placement args by prepending conjured size and alignment exprs.
2375
0
    llvm::SmallVector<Expr *, 8> CallArgs;
2376
0
    CallArgs.reserve(NumImplicitArgs + PlacementArgs.size());
2377
0
    CallArgs.emplace_back(AllocationSize
2378
0
                              ? static_cast<Expr *>(&AllocationSizeLiteral)
2379
0
                              : &OpaqueAllocationSize);
2380
0
    if (PassAlignment)
2381
0
      CallArgs.emplace_back(&DesiredAlignment);
2382
0
    CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end());
2383
2384
0
    DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs);
2385
2386
0
    checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs,
2387
0
              /*IsMemberFunction=*/false, StartLoc, Range, CallType);
2388
2389
    // Warn if the type is over-aligned and is being allocated by (unaligned)
2390
    // global operator new.
2391
0
    if (PlacementArgs.empty() && !PassAlignment &&
2392
0
        (OperatorNew->isImplicit() ||
2393
0
         (OperatorNew->getBeginLoc().isValid() &&
2394
0
          getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
2395
0
      if (Alignment > NewAlignment)
2396
0
        Diag(StartLoc, diag::warn_overaligned_type)
2397
0
            << AllocType
2398
0
            << unsigned(Alignment / Context.getCharWidth())
2399
0
            << unsigned(NewAlignment / Context.getCharWidth());
2400
0
    }
2401
0
  }
2402
2403
  // Array 'new' can't have any initializers except empty parentheses.
2404
  // Initializer lists are also allowed, in C++11. Rely on the parser for the
2405
  // dialect distinction.
2406
0
  if (ArraySize && !isLegalArrayNewInitializer(InitStyle, Initializer)) {
2407
0
    SourceRange InitRange(Exprs.front()->getBeginLoc(),
2408
0
                          Exprs.back()->getEndLoc());
2409
0
    Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2410
0
    return ExprError();
2411
0
  }
2412
2413
  // If we can perform the initialization, and we've not already done so,
2414
  // do it now.
2415
0
  if (!AllocType->isDependentType() &&
2416
0
      !Expr::hasAnyTypeDependentArguments(Exprs)) {
2417
    // The type we initialize is the complete type, including the array bound.
2418
0
    QualType InitType;
2419
0
    if (KnownArraySize)
2420
0
      InitType = Context.getConstantArrayType(
2421
0
          AllocType,
2422
0
          llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2423
0
                      *KnownArraySize),
2424
0
          *ArraySize, ArraySizeModifier::Normal, 0);
2425
0
    else if (ArraySize)
2426
0
      InitType = Context.getIncompleteArrayType(AllocType,
2427
0
                                                ArraySizeModifier::Normal, 0);
2428
0
    else
2429
0
      InitType = AllocType;
2430
2431
0
    InitializedEntity Entity
2432
0
      = InitializedEntity::InitializeNew(StartLoc, InitType);
2433
0
    InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
2434
0
    ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, Exprs);
2435
0
    if (FullInit.isInvalid())
2436
0
      return ExprError();
2437
2438
    // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2439
    // we don't want the initialized object to be destructed.
2440
    // FIXME: We should not create these in the first place.
2441
0
    if (CXXBindTemporaryExpr *Binder =
2442
0
            dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2443
0
      FullInit = Binder->getSubExpr();
2444
2445
0
    Initializer = FullInit.get();
2446
    // We don't know that we're generating an implicit initializer until now, so
2447
    // we have to update the initialization style as well.
2448
    //
2449
    // FIXME: it would be nice to determine the correct initialization style
2450
    // earlier so InitStyle doesn't need adjusting.
2451
0
    if (InitStyle == CXXNewInitializationStyle::None && Initializer) {
2452
0
      InitStyle = CXXNewInitializationStyle::Implicit;
2453
0
    }
2454
2455
    // FIXME: If we have a KnownArraySize, check that the array bound of the
2456
    // initializer is no greater than that constant value.
2457
2458
0
    if (ArraySize && !*ArraySize) {
2459
0
      auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
2460
0
      if (CAT) {
2461
        // FIXME: Track that the array size was inferred rather than explicitly
2462
        // specified.
2463
0
        ArraySize = IntegerLiteral::Create(
2464
0
            Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
2465
0
      } else {
2466
0
        Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
2467
0
            << Initializer->getSourceRange();
2468
0
      }
2469
0
    }
2470
0
  }
2471
2472
  // Mark the new and delete operators as referenced.
2473
0
  if (OperatorNew) {
2474
0
    if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2475
0
      return ExprError();
2476
0
    MarkFunctionReferenced(StartLoc, OperatorNew);
2477
0
  }
2478
0
  if (OperatorDelete) {
2479
0
    if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2480
0
      return ExprError();
2481
0
    MarkFunctionReferenced(StartLoc, OperatorDelete);
2482
0
  }
2483
2484
0
  return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2485
0
                            PassAlignment, UsualArrayDeleteWantsSize,
2486
0
                            PlacementArgs, TypeIdParens, ArraySize, InitStyle,
2487
0
                            Initializer, ResultType, AllocTypeInfo, Range,
2488
0
                            DirectInitRange);
2489
0
}
2490
2491
/// Checks that a type is suitable as the allocated type
2492
/// in a new-expression.
2493
bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
2494
0
                              SourceRange R) {
2495
  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2496
  //   abstract class type or array thereof.
2497
0
  if (AllocType->isFunctionType())
2498
0
    return Diag(Loc, diag::err_bad_new_type)
2499
0
      << AllocType << 0 << R;
2500
0
  else if (AllocType->isReferenceType())
2501
0
    return Diag(Loc, diag::err_bad_new_type)
2502
0
      << AllocType << 1 << R;
2503
0
  else if (!AllocType->isDependentType() &&
2504
0
           RequireCompleteSizedType(
2505
0
               Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R))
2506
0
    return true;
2507
0
  else if (RequireNonAbstractType(Loc, AllocType,
2508
0
                                  diag::err_allocation_of_abstract_type))
2509
0
    return true;
2510
0
  else if (AllocType->isVariablyModifiedType())
2511
0
    return Diag(Loc, diag::err_variably_modified_new_type)
2512
0
             << AllocType;
2513
0
  else if (AllocType.getAddressSpace() != LangAS::Default &&
2514
0
           !getLangOpts().OpenCLCPlusPlus)
2515
0
    return Diag(Loc, diag::err_address_space_qualified_new)
2516
0
      << AllocType.getUnqualifiedType()
2517
0
      << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
2518
0
  else if (getLangOpts().ObjCAutoRefCount) {
2519
0
    if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2520
0
      QualType BaseAllocType = Context.getBaseElementType(AT);
2521
0
      if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2522
0
          BaseAllocType->isObjCLifetimeType())
2523
0
        return Diag(Loc, diag::err_arc_new_array_without_ownership)
2524
0
          << BaseAllocType;
2525
0
    }
2526
0
  }
2527
2528
0
  return false;
2529
0
}
2530
2531
static bool resolveAllocationOverload(
2532
    Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2533
    bool &PassAlignment, FunctionDecl *&Operator,
2534
0
    OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2535
0
  OverloadCandidateSet Candidates(R.getNameLoc(),
2536
0
                                  OverloadCandidateSet::CSK_Normal);
2537
0
  for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2538
0
       Alloc != AllocEnd; ++Alloc) {
2539
    // Even member operator new/delete are implicitly treated as
2540
    // static, so don't use AddMemberCandidate.
2541
0
    NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2542
2543
0
    if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2544
0
      S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2545
0
                                     /*ExplicitTemplateArgs=*/nullptr, Args,
2546
0
                                     Candidates,
2547
0
                                     /*SuppressUserConversions=*/false);
2548
0
      continue;
2549
0
    }
2550
2551
0
    FunctionDecl *Fn = cast<FunctionDecl>(D);
2552
0
    S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2553
0
                           /*SuppressUserConversions=*/false);
2554
0
  }
2555
2556
  // Do the resolution.
2557
0
  OverloadCandidateSet::iterator Best;
2558
0
  switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2559
0
  case OR_Success: {
2560
    // Got one!
2561
0
    FunctionDecl *FnDecl = Best->Function;
2562
0
    if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2563
0
                                Best->FoundDecl) == Sema::AR_inaccessible)
2564
0
      return true;
2565
2566
0
    Operator = FnDecl;
2567
0
    return false;
2568
0
  }
2569
2570
0
  case OR_No_Viable_Function:
2571
    // C++17 [expr.new]p13:
2572
    //   If no matching function is found and the allocated object type has
2573
    //   new-extended alignment, the alignment argument is removed from the
2574
    //   argument list, and overload resolution is performed again.
2575
0
    if (PassAlignment) {
2576
0
      PassAlignment = false;
2577
0
      AlignArg = Args[1];
2578
0
      Args.erase(Args.begin() + 1);
2579
0
      return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2580
0
                                       Operator, &Candidates, AlignArg,
2581
0
                                       Diagnose);
2582
0
    }
2583
2584
    // MSVC will fall back on trying to find a matching global operator new
2585
    // if operator new[] cannot be found.  Also, MSVC will leak by not
2586
    // generating a call to operator delete or operator delete[], but we
2587
    // will not replicate that bug.
2588
    // FIXME: Find out how this interacts with the std::align_val_t fallback
2589
    // once MSVC implements it.
2590
0
    if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2591
0
        S.Context.getLangOpts().MSVCCompat) {
2592
0
      R.clear();
2593
0
      R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2594
0
      S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2595
      // FIXME: This will give bad diagnostics pointing at the wrong functions.
2596
0
      return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2597
0
                                       Operator, /*Candidates=*/nullptr,
2598
0
                                       /*AlignArg=*/nullptr, Diagnose);
2599
0
    }
2600
2601
0
    if (Diagnose) {
2602
      // If this is an allocation of the form 'new (p) X' for some object
2603
      // pointer p (or an expression that will decay to such a pointer),
2604
      // diagnose the missing inclusion of <new>.
2605
0
      if (!R.isClassLookup() && Args.size() == 2 &&
2606
0
          (Args[1]->getType()->isObjectPointerType() ||
2607
0
           Args[1]->getType()->isArrayType())) {
2608
0
        S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new)
2609
0
            << R.getLookupName() << Range;
2610
        // Listing the candidates is unlikely to be useful; skip it.
2611
0
        return true;
2612
0
      }
2613
2614
      // Finish checking all candidates before we note any. This checking can
2615
      // produce additional diagnostics so can't be interleaved with our
2616
      // emission of notes.
2617
      //
2618
      // For an aligned allocation, separately check the aligned and unaligned
2619
      // candidates with their respective argument lists.
2620
0
      SmallVector<OverloadCandidate*, 32> Cands;
2621
0
      SmallVector<OverloadCandidate*, 32> AlignedCands;
2622
0
      llvm::SmallVector<Expr*, 4> AlignedArgs;
2623
0
      if (AlignedCandidates) {
2624
0
        auto IsAligned = [](OverloadCandidate &C) {
2625
0
          return C.Function->getNumParams() > 1 &&
2626
0
                 C.Function->getParamDecl(1)->getType()->isAlignValT();
2627
0
        };
2628
0
        auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2629
2630
0
        AlignedArgs.reserve(Args.size() + 1);
2631
0
        AlignedArgs.push_back(Args[0]);
2632
0
        AlignedArgs.push_back(AlignArg);
2633
0
        AlignedArgs.append(Args.begin() + 1, Args.end());
2634
0
        AlignedCands = AlignedCandidates->CompleteCandidates(
2635
0
            S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned);
2636
2637
0
        Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2638
0
                                              R.getNameLoc(), IsUnaligned);
2639
0
      } else {
2640
0
        Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2641
0
                                              R.getNameLoc());
2642
0
      }
2643
2644
0
      S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2645
0
          << R.getLookupName() << Range;
2646
0
      if (AlignedCandidates)
2647
0
        AlignedCandidates->NoteCandidates(S, AlignedArgs, AlignedCands, "",
2648
0
                                          R.getNameLoc());
2649
0
      Candidates.NoteCandidates(S, Args, Cands, "", R.getNameLoc());
2650
0
    }
2651
0
    return true;
2652
2653
0
  case OR_Ambiguous:
2654
0
    if (Diagnose) {
2655
0
      Candidates.NoteCandidates(
2656
0
          PartialDiagnosticAt(R.getNameLoc(),
2657
0
                              S.PDiag(diag::err_ovl_ambiguous_call)
2658
0
                                  << R.getLookupName() << Range),
2659
0
          S, OCD_AmbiguousCandidates, Args);
2660
0
    }
2661
0
    return true;
2662
2663
0
  case OR_Deleted: {
2664
0
    if (Diagnose) {
2665
0
      Candidates.NoteCandidates(
2666
0
          PartialDiagnosticAt(R.getNameLoc(),
2667
0
                              S.PDiag(diag::err_ovl_deleted_call)
2668
0
                                  << R.getLookupName() << Range),
2669
0
          S, OCD_AllCandidates, Args);
2670
0
    }
2671
0
    return true;
2672
0
  }
2673
0
  }
2674
0
  llvm_unreachable("Unreachable, bad result from BestViableFunction");
2675
0
}
2676
2677
bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2678
                                   AllocationFunctionScope NewScope,
2679
                                   AllocationFunctionScope DeleteScope,
2680
                                   QualType AllocType, bool IsArray,
2681
                                   bool &PassAlignment, MultiExprArg PlaceArgs,
2682
                                   FunctionDecl *&OperatorNew,
2683
                                   FunctionDecl *&OperatorDelete,
2684
0
                                   bool Diagnose) {
2685
  // --- Choosing an allocation function ---
2686
  // C++ 5.3.4p8 - 14 & 18
2687
  // 1) If looking in AFS_Global scope for allocation functions, only look in
2688
  //    the global scope. Else, if AFS_Class, only look in the scope of the
2689
  //    allocated class. If AFS_Both, look in both.
2690
  // 2) If an array size is given, look for operator new[], else look for
2691
  //   operator new.
2692
  // 3) The first argument is always size_t. Append the arguments from the
2693
  //   placement form.
2694
2695
0
  SmallVector<Expr*, 8> AllocArgs;
2696
0
  AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2697
2698
  // We don't care about the actual value of these arguments.
2699
  // FIXME: Should the Sema create the expression and embed it in the syntax
2700
  // tree? Or should the consumer just recalculate the value?
2701
  // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2702
0
  QualType SizeTy = Context.getSizeType();
2703
0
  unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2704
0
  IntegerLiteral Size(Context, llvm::APInt::getZero(SizeTyWidth), SizeTy,
2705
0
                      SourceLocation());
2706
0
  AllocArgs.push_back(&Size);
2707
2708
0
  QualType AlignValT = Context.VoidTy;
2709
0
  if (PassAlignment) {
2710
0
    DeclareGlobalNewDelete();
2711
0
    AlignValT = Context.getTypeDeclType(getStdAlignValT());
2712
0
  }
2713
0
  CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2714
0
  if (PassAlignment)
2715
0
    AllocArgs.push_back(&Align);
2716
2717
0
  AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2718
2719
  // C++ [expr.new]p8:
2720
  //   If the allocated type is a non-array type, the allocation
2721
  //   function's name is operator new and the deallocation function's
2722
  //   name is operator delete. If the allocated type is an array
2723
  //   type, the allocation function's name is operator new[] and the
2724
  //   deallocation function's name is operator delete[].
2725
0
  DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
2726
0
      IsArray ? OO_Array_New : OO_New);
2727
2728
0
  QualType AllocElemType = Context.getBaseElementType(AllocType);
2729
2730
  // Find the allocation function.
2731
0
  {
2732
0
    LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2733
2734
    // C++1z [expr.new]p9:
2735
    //   If the new-expression begins with a unary :: operator, the allocation
2736
    //   function's name is looked up in the global scope. Otherwise, if the
2737
    //   allocated type is a class type T or array thereof, the allocation
2738
    //   function's name is looked up in the scope of T.
2739
0
    if (AllocElemType->isRecordType() && NewScope != AFS_Global)
2740
0
      LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2741
2742
    // We can see ambiguity here if the allocation function is found in
2743
    // multiple base classes.
2744
0
    if (R.isAmbiguous())
2745
0
      return true;
2746
2747
    //   If this lookup fails to find the name, or if the allocated type is not
2748
    //   a class type, the allocation function's name is looked up in the
2749
    //   global scope.
2750
0
    if (R.empty()) {
2751
0
      if (NewScope == AFS_Class)
2752
0
        return true;
2753
2754
0
      LookupQualifiedName(R, Context.getTranslationUnitDecl());
2755
0
    }
2756
2757
0
    if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2758
0
      if (PlaceArgs.empty()) {
2759
0
        Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2760
0
      } else {
2761
0
        Diag(StartLoc, diag::err_openclcxx_placement_new);
2762
0
      }
2763
0
      return true;
2764
0
    }
2765
2766
0
    assert(!R.empty() && "implicitly declared allocation functions not found");
2767
0
    assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2768
2769
    // We do our own custom access checks below.
2770
0
    R.suppressDiagnostics();
2771
2772
0
    if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2773
0
                                  OperatorNew, /*Candidates=*/nullptr,
2774
0
                                  /*AlignArg=*/nullptr, Diagnose))
2775
0
      return true;
2776
0
  }
2777
2778
  // We don't need an operator delete if we're running under -fno-exceptions.
2779
0
  if (!getLangOpts().Exceptions) {
2780
0
    OperatorDelete = nullptr;
2781
0
    return false;
2782
0
  }
2783
2784
  // Note, the name of OperatorNew might have been changed from array to
2785
  // non-array by resolveAllocationOverload.
2786
0
  DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2787
0
      OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2788
0
          ? OO_Array_Delete
2789
0
          : OO_Delete);
2790
2791
  // C++ [expr.new]p19:
2792
  //
2793
  //   If the new-expression begins with a unary :: operator, the
2794
  //   deallocation function's name is looked up in the global
2795
  //   scope. Otherwise, if the allocated type is a class type T or an
2796
  //   array thereof, the deallocation function's name is looked up in
2797
  //   the scope of T. If this lookup fails to find the name, or if
2798
  //   the allocated type is not a class type or array thereof, the
2799
  //   deallocation function's name is looked up in the global scope.
2800
0
  LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2801
0
  if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
2802
0
    auto *RD =
2803
0
        cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl());
2804
0
    LookupQualifiedName(FoundDelete, RD);
2805
0
  }
2806
0
  if (FoundDelete.isAmbiguous())
2807
0
    return true; // FIXME: clean up expressions?
2808
2809
  // Filter out any destroying operator deletes. We can't possibly call such a
2810
  // function in this context, because we're handling the case where the object
2811
  // was not successfully constructed.
2812
  // FIXME: This is not covered by the language rules yet.
2813
0
  {
2814
0
    LookupResult::Filter Filter = FoundDelete.makeFilter();
2815
0
    while (Filter.hasNext()) {
2816
0
      auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl());
2817
0
      if (FD && FD->isDestroyingOperatorDelete())
2818
0
        Filter.erase();
2819
0
    }
2820
0
    Filter.done();
2821
0
  }
2822
2823
0
  bool FoundGlobalDelete = FoundDelete.empty();
2824
0
  if (FoundDelete.empty()) {
2825
0
    FoundDelete.clear(LookupOrdinaryName);
2826
2827
0
    if (DeleteScope == AFS_Class)
2828
0
      return true;
2829
2830
0
    DeclareGlobalNewDelete();
2831
0
    LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2832
0
  }
2833
2834
0
  FoundDelete.suppressDiagnostics();
2835
2836
0
  SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
2837
2838
  // Whether we're looking for a placement operator delete is dictated
2839
  // by whether we selected a placement operator new, not by whether
2840
  // we had explicit placement arguments.  This matters for things like
2841
  //   struct A { void *operator new(size_t, int = 0); ... };
2842
  //   A *a = new A()
2843
  //
2844
  // We don't have any definition for what a "placement allocation function"
2845
  // is, but we assume it's any allocation function whose
2846
  // parameter-declaration-clause is anything other than (size_t).
2847
  //
2848
  // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2849
  // This affects whether an exception from the constructor of an overaligned
2850
  // type uses the sized or non-sized form of aligned operator delete.
2851
0
  bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2852
0
                        OperatorNew->isVariadic();
2853
2854
0
  if (isPlacementNew) {
2855
    // C++ [expr.new]p20:
2856
    //   A declaration of a placement deallocation function matches the
2857
    //   declaration of a placement allocation function if it has the
2858
    //   same number of parameters and, after parameter transformations
2859
    //   (8.3.5), all parameter types except the first are
2860
    //   identical. [...]
2861
    //
2862
    // To perform this comparison, we compute the function type that
2863
    // the deallocation function should have, and use that type both
2864
    // for template argument deduction and for comparison purposes.
2865
0
    QualType ExpectedFunctionType;
2866
0
    {
2867
0
      auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2868
2869
0
      SmallVector<QualType, 4> ArgTypes;
2870
0
      ArgTypes.push_back(Context.VoidPtrTy);
2871
0
      for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2872
0
        ArgTypes.push_back(Proto->getParamType(I));
2873
2874
0
      FunctionProtoType::ExtProtoInfo EPI;
2875
      // FIXME: This is not part of the standard's rule.
2876
0
      EPI.Variadic = Proto->isVariadic();
2877
2878
0
      ExpectedFunctionType
2879
0
        = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2880
0
    }
2881
2882
0
    for (LookupResult::iterator D = FoundDelete.begin(),
2883
0
                             DEnd = FoundDelete.end();
2884
0
         D != DEnd; ++D) {
2885
0
      FunctionDecl *Fn = nullptr;
2886
0
      if (FunctionTemplateDecl *FnTmpl =
2887
0
              dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2888
        // Perform template argument deduction to try to match the
2889
        // expected function type.
2890
0
        TemplateDeductionInfo Info(StartLoc);
2891
0
        if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2892
0
                                    Info))
2893
0
          continue;
2894
0
      } else
2895
0
        Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2896
2897
0
      if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2898
0
                                                  ExpectedFunctionType,
2899
0
                                                  /*AdjustExcpetionSpec*/true),
2900
0
                              ExpectedFunctionType))
2901
0
        Matches.push_back(std::make_pair(D.getPair(), Fn));
2902
0
    }
2903
2904
0
    if (getLangOpts().CUDA)
2905
0
      EraseUnwantedCUDAMatches(getCurFunctionDecl(/*AllowLambda=*/true),
2906
0
                               Matches);
2907
0
  } else {
2908
    // C++1y [expr.new]p22:
2909
    //   For a non-placement allocation function, the normal deallocation
2910
    //   function lookup is used
2911
    //
2912
    // Per [expr.delete]p10, this lookup prefers a member operator delete
2913
    // without a size_t argument, but prefers a non-member operator delete
2914
    // with a size_t where possible (which it always is in this case).
2915
0
    llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2916
0
    UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2917
0
        *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2918
0
        /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2919
0
        &BestDeallocFns);
2920
0
    if (Selected)
2921
0
      Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2922
0
    else {
2923
      // If we failed to select an operator, all remaining functions are viable
2924
      // but ambiguous.
2925
0
      for (auto Fn : BestDeallocFns)
2926
0
        Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2927
0
    }
2928
0
  }
2929
2930
  // C++ [expr.new]p20:
2931
  //   [...] If the lookup finds a single matching deallocation
2932
  //   function, that function will be called; otherwise, no
2933
  //   deallocation function will be called.
2934
0
  if (Matches.size() == 1) {
2935
0
    OperatorDelete = Matches[0].second;
2936
2937
    // C++1z [expr.new]p23:
2938
    //   If the lookup finds a usual deallocation function (3.7.4.2)
2939
    //   with a parameter of type std::size_t and that function, considered
2940
    //   as a placement deallocation function, would have been
2941
    //   selected as a match for the allocation function, the program
2942
    //   is ill-formed.
2943
0
    if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2944
0
        isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2945
0
      UsualDeallocFnInfo Info(*this,
2946
0
                              DeclAccessPair::make(OperatorDelete, AS_public));
2947
      // Core issue, per mail to core reflector, 2016-10-09:
2948
      //   If this is a member operator delete, and there is a corresponding
2949
      //   non-sized member operator delete, this isn't /really/ a sized
2950
      //   deallocation function, it just happens to have a size_t parameter.
2951
0
      bool IsSizedDelete = Info.HasSizeT;
2952
0
      if (IsSizedDelete && !FoundGlobalDelete) {
2953
0
        auto NonSizedDelete =
2954
0
            resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2955
0
                                        /*WantAlign*/Info.HasAlignValT);
2956
0
        if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2957
0
            NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2958
0
          IsSizedDelete = false;
2959
0
      }
2960
2961
0
      if (IsSizedDelete) {
2962
0
        SourceRange R = PlaceArgs.empty()
2963
0
                            ? SourceRange()
2964
0
                            : SourceRange(PlaceArgs.front()->getBeginLoc(),
2965
0
                                          PlaceArgs.back()->getEndLoc());
2966
0
        Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2967
0
        if (!OperatorDelete->isImplicit())
2968
0
          Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2969
0
              << DeleteName;
2970
0
      }
2971
0
    }
2972
2973
0
    CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2974
0
                          Matches[0].first);
2975
0
  } else if (!Matches.empty()) {
2976
    // We found multiple suitable operators. Per [expr.new]p20, that means we
2977
    // call no 'operator delete' function, but we should at least warn the user.
2978
    // FIXME: Suppress this warning if the construction cannot throw.
2979
0
    Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2980
0
      << DeleteName << AllocElemType;
2981
2982
0
    for (auto &Match : Matches)
2983
0
      Diag(Match.second->getLocation(),
2984
0
           diag::note_member_declared_here) << DeleteName;
2985
0
  }
2986
2987
0
  return false;
2988
0
}
2989
2990
/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2991
/// delete. These are:
2992
/// @code
2993
///   // C++03:
2994
///   void* operator new(std::size_t) throw(std::bad_alloc);
2995
///   void* operator new[](std::size_t) throw(std::bad_alloc);
2996
///   void operator delete(void *) throw();
2997
///   void operator delete[](void *) throw();
2998
///   // C++11:
2999
///   void* operator new(std::size_t);
3000
///   void* operator new[](std::size_t);
3001
///   void operator delete(void *) noexcept;
3002
///   void operator delete[](void *) noexcept;
3003
///   // C++1y:
3004
///   void* operator new(std::size_t);
3005
///   void* operator new[](std::size_t);
3006
///   void operator delete(void *) noexcept;
3007
///   void operator delete[](void *) noexcept;
3008
///   void operator delete(void *, std::size_t) noexcept;
3009
///   void operator delete[](void *, std::size_t) noexcept;
3010
/// @endcode
3011
/// Note that the placement and nothrow forms of new are *not* implicitly
3012
/// declared. Their use requires including \<new\>.
3013
0
void Sema::DeclareGlobalNewDelete() {
3014
0
  if (GlobalNewDeleteDeclared)
3015
0
    return;
3016
3017
  // The implicitly declared new and delete operators
3018
  // are not supported in OpenCL.
3019
0
  if (getLangOpts().OpenCLCPlusPlus)
3020
0
    return;
3021
3022
  // C++ [basic.stc.dynamic.general]p2:
3023
  //   The library provides default definitions for the global allocation
3024
  //   and deallocation functions. Some global allocation and deallocation
3025
  //   functions are replaceable ([new.delete]); these are attached to the
3026
  //   global module ([module.unit]).
3027
0
  if (getLangOpts().CPlusPlusModules && getCurrentModule())
3028
0
    PushGlobalModuleFragment(SourceLocation());
3029
3030
  // C++ [basic.std.dynamic]p2:
3031
  //   [...] The following allocation and deallocation functions (18.4) are
3032
  //   implicitly declared in global scope in each translation unit of a
3033
  //   program
3034
  //
3035
  //     C++03:
3036
  //     void* operator new(std::size_t) throw(std::bad_alloc);
3037
  //     void* operator new[](std::size_t) throw(std::bad_alloc);
3038
  //     void  operator delete(void*) throw();
3039
  //     void  operator delete[](void*) throw();
3040
  //     C++11:
3041
  //     void* operator new(std::size_t);
3042
  //     void* operator new[](std::size_t);
3043
  //     void  operator delete(void*) noexcept;
3044
  //     void  operator delete[](void*) noexcept;
3045
  //     C++1y:
3046
  //     void* operator new(std::size_t);
3047
  //     void* operator new[](std::size_t);
3048
  //     void  operator delete(void*) noexcept;
3049
  //     void  operator delete[](void*) noexcept;
3050
  //     void  operator delete(void*, std::size_t) noexcept;
3051
  //     void  operator delete[](void*, std::size_t) noexcept;
3052
  //
3053
  //   These implicit declarations introduce only the function names operator
3054
  //   new, operator new[], operator delete, operator delete[].
3055
  //
3056
  // Here, we need to refer to std::bad_alloc, so we will implicitly declare
3057
  // "std" or "bad_alloc" as necessary to form the exception specification.
3058
  // However, we do not make these implicit declarations visible to name
3059
  // lookup.
3060
0
  if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
3061
    // The "std::bad_alloc" class has not yet been declared, so build it
3062
    // implicitly.
3063
0
    StdBadAlloc = CXXRecordDecl::Create(
3064
0
        Context, TagTypeKind::Class, getOrCreateStdNamespace(),
3065
0
        SourceLocation(), SourceLocation(),
3066
0
        &PP.getIdentifierTable().get("bad_alloc"), nullptr);
3067
0
    getStdBadAlloc()->setImplicit(true);
3068
3069
    // The implicitly declared "std::bad_alloc" should live in global module
3070
    // fragment.
3071
0
    if (TheGlobalModuleFragment) {
3072
0
      getStdBadAlloc()->setModuleOwnershipKind(
3073
0
          Decl::ModuleOwnershipKind::ReachableWhenImported);
3074
0
      getStdBadAlloc()->setLocalOwningModule(TheGlobalModuleFragment);
3075
0
    }
3076
0
  }
3077
0
  if (!StdAlignValT && getLangOpts().AlignedAllocation) {
3078
    // The "std::align_val_t" enum class has not yet been declared, so build it
3079
    // implicitly.
3080
0
    auto *AlignValT = EnumDecl::Create(
3081
0
        Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
3082
0
        &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
3083
3084
    // The implicitly declared "std::align_val_t" should live in global module
3085
    // fragment.
3086
0
    if (TheGlobalModuleFragment) {
3087
0
      AlignValT->setModuleOwnershipKind(
3088
0
          Decl::ModuleOwnershipKind::ReachableWhenImported);
3089
0
      AlignValT->setLocalOwningModule(TheGlobalModuleFragment);
3090
0
    }
3091
3092
0
    AlignValT->setIntegerType(Context.getSizeType());
3093
0
    AlignValT->setPromotionType(Context.getSizeType());
3094
0
    AlignValT->setImplicit(true);
3095
3096
0
    StdAlignValT = AlignValT;
3097
0
  }
3098
3099
0
  GlobalNewDeleteDeclared = true;
3100
3101
0
  QualType VoidPtr = Context.getPointerType(Context.VoidTy);
3102
0
  QualType SizeT = Context.getSizeType();
3103
3104
0
  auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
3105
0
                                              QualType Return, QualType Param) {
3106
0
    llvm::SmallVector<QualType, 3> Params;
3107
0
    Params.push_back(Param);
3108
3109
    // Create up to four variants of the function (sized/aligned).
3110
0
    bool HasSizedVariant = getLangOpts().SizedDeallocation &&
3111
0
                           (Kind == OO_Delete || Kind == OO_Array_Delete);
3112
0
    bool HasAlignedVariant = getLangOpts().AlignedAllocation;
3113
3114
0
    int NumSizeVariants = (HasSizedVariant ? 2 : 1);
3115
0
    int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
3116
0
    for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
3117
0
      if (Sized)
3118
0
        Params.push_back(SizeT);
3119
3120
0
      for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
3121
0
        if (Aligned)
3122
0
          Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
3123
3124
0
        DeclareGlobalAllocationFunction(
3125
0
            Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
3126
3127
0
        if (Aligned)
3128
0
          Params.pop_back();
3129
0
      }
3130
0
    }
3131
0
  };
3132
3133
0
  DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
3134
0
  DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
3135
0
  DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
3136
0
  DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
3137
3138
0
  if (getLangOpts().CPlusPlusModules && getCurrentModule())
3139
0
    PopGlobalModuleFragment();
3140
0
}
3141
3142
/// DeclareGlobalAllocationFunction - Declares a single implicit global
3143
/// allocation function if it doesn't already exist.
3144
void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
3145
                                           QualType Return,
3146
0
                                           ArrayRef<QualType> Params) {
3147
0
  DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
3148
3149
  // Check if this function is already declared.
3150
0
  DeclContext::lookup_result R = GlobalCtx->lookup(Name);
3151
0
  for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
3152
0
       Alloc != AllocEnd; ++Alloc) {
3153
    // Only look at non-template functions, as it is the predefined,
3154
    // non-templated allocation function we are trying to declare here.
3155
0
    if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
3156
0
      if (Func->getNumParams() == Params.size()) {
3157
0
        llvm::SmallVector<QualType, 3> FuncParams;
3158
0
        for (auto *P : Func->parameters())
3159
0
          FuncParams.push_back(
3160
0
              Context.getCanonicalType(P->getType().getUnqualifiedType()));
3161
0
        if (llvm::ArrayRef(FuncParams) == Params) {
3162
          // Make the function visible to name lookup, even if we found it in
3163
          // an unimported module. It either is an implicitly-declared global
3164
          // allocation function, or is suppressing that function.
3165
0
          Func->setVisibleDespiteOwningModule();
3166
0
          return;
3167
0
        }
3168
0
      }
3169
0
    }
3170
0
  }
3171
3172
0
  FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
3173
0
      /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
3174
3175
0
  QualType BadAllocType;
3176
0
  bool HasBadAllocExceptionSpec
3177
0
    = (Name.getCXXOverloadedOperator() == OO_New ||
3178
0
       Name.getCXXOverloadedOperator() == OO_Array_New);
3179
0
  if (HasBadAllocExceptionSpec) {
3180
0
    if (!getLangOpts().CPlusPlus11) {
3181
0
      BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
3182
0
      assert(StdBadAlloc && "Must have std::bad_alloc declared");
3183
0
      EPI.ExceptionSpec.Type = EST_Dynamic;
3184
0
      EPI.ExceptionSpec.Exceptions = llvm::ArrayRef(BadAllocType);
3185
0
    }
3186
0
    if (getLangOpts().NewInfallible) {
3187
0
      EPI.ExceptionSpec.Type = EST_DynamicNone;
3188
0
    }
3189
0
  } else {
3190
0
    EPI.ExceptionSpec =
3191
0
        getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
3192
0
  }
3193
3194
0
  auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
3195
0
    QualType FnType = Context.getFunctionType(Return, Params, EPI);
3196
0
    FunctionDecl *Alloc = FunctionDecl::Create(
3197
0
        Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, FnType,
3198
0
        /*TInfo=*/nullptr, SC_None, getCurFPFeatures().isFPConstrained(), false,
3199
0
        true);
3200
0
    Alloc->setImplicit();
3201
    // Global allocation functions should always be visible.
3202
0
    Alloc->setVisibleDespiteOwningModule();
3203
3204
0
    if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible &&
3205
0
        !getLangOpts().CheckNew)
3206
0
      Alloc->addAttr(
3207
0
          ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation()));
3208
3209
    // C++ [basic.stc.dynamic.general]p2:
3210
    //   The library provides default definitions for the global allocation
3211
    //   and deallocation functions. Some global allocation and deallocation
3212
    //   functions are replaceable ([new.delete]); these are attached to the
3213
    //   global module ([module.unit]).
3214
    //
3215
    // In the language wording, these functions are attched to the global
3216
    // module all the time. But in the implementation, the global module
3217
    // is only meaningful when we're in a module unit. So here we attach
3218
    // these allocation functions to global module conditionally.
3219
0
    if (TheGlobalModuleFragment) {
3220
0
      Alloc->setModuleOwnershipKind(
3221
0
          Decl::ModuleOwnershipKind::ReachableWhenImported);
3222
0
      Alloc->setLocalOwningModule(TheGlobalModuleFragment);
3223
0
    }
3224
3225
0
    Alloc->addAttr(VisibilityAttr::CreateImplicit(
3226
0
        Context, LangOpts.GlobalAllocationFunctionVisibilityHidden
3227
0
                     ? VisibilityAttr::Hidden
3228
0
                     : VisibilityAttr::Default));
3229
3230
0
    llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
3231
0
    for (QualType T : Params) {
3232
0
      ParamDecls.push_back(ParmVarDecl::Create(
3233
0
          Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
3234
0
          /*TInfo=*/nullptr, SC_None, nullptr));
3235
0
      ParamDecls.back()->setImplicit();
3236
0
    }
3237
0
    Alloc->setParams(ParamDecls);
3238
0
    if (ExtraAttr)
3239
0
      Alloc->addAttr(ExtraAttr);
3240
0
    AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(Alloc);
3241
0
    Context.getTranslationUnitDecl()->addDecl(Alloc);
3242
0
    IdResolver.tryAddTopLevelDecl(Alloc, Name);
3243
0
  };
3244
3245
0
  if (!LangOpts.CUDA)
3246
0
    CreateAllocationFunctionDecl(nullptr);
3247
0
  else {
3248
    // Host and device get their own declaration so each can be
3249
    // defined or re-declared independently.
3250
0
    CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
3251
0
    CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
3252
0
  }
3253
0
}
3254
3255
FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
3256
                                                  bool CanProvideSize,
3257
                                                  bool Overaligned,
3258
0
                                                  DeclarationName Name) {
3259
0
  DeclareGlobalNewDelete();
3260
3261
0
  LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
3262
0
  LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
3263
3264
  // FIXME: It's possible for this to result in ambiguity, through a
3265
  // user-declared variadic operator delete or the enable_if attribute. We
3266
  // should probably not consider those cases to be usual deallocation
3267
  // functions. But for now we just make an arbitrary choice in that case.
3268
0
  auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
3269
0
                                            Overaligned);
3270
0
  assert(Result.FD && "operator delete missing from global scope?");
3271
0
  return Result.FD;
3272
0
}
3273
3274
FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
3275
0
                                                          CXXRecordDecl *RD) {
3276
0
  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
3277
3278
0
  FunctionDecl *OperatorDelete = nullptr;
3279
0
  if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
3280
0
    return nullptr;
3281
0
  if (OperatorDelete)
3282
0
    return OperatorDelete;
3283
3284
  // If there's no class-specific operator delete, look up the global
3285
  // non-array delete.
3286
0
  return FindUsualDeallocationFunction(
3287
0
      Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
3288
0
      Name);
3289
0
}
3290
3291
bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
3292
                                    DeclarationName Name,
3293
                                    FunctionDecl *&Operator, bool Diagnose,
3294
0
                                    bool WantSize, bool WantAligned) {
3295
0
  LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
3296
  // Try to find operator delete/operator delete[] in class scope.
3297
0
  LookupQualifiedName(Found, RD);
3298
3299
0
  if (Found.isAmbiguous())
3300
0
    return true;
3301
3302
0
  Found.suppressDiagnostics();
3303
3304
0
  bool Overaligned =
3305
0
      WantAligned || hasNewExtendedAlignment(*this, Context.getRecordType(RD));
3306
3307
  // C++17 [expr.delete]p10:
3308
  //   If the deallocation functions have class scope, the one without a
3309
  //   parameter of type std::size_t is selected.
3310
0
  llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
3311
0
  resolveDeallocationOverload(*this, Found, /*WantSize*/ WantSize,
3312
0
                              /*WantAlign*/ Overaligned, &Matches);
3313
3314
  // If we could find an overload, use it.
3315
0
  if (Matches.size() == 1) {
3316
0
    Operator = cast<CXXMethodDecl>(Matches[0].FD);
3317
3318
    // FIXME: DiagnoseUseOfDecl?
3319
0
    if (Operator->isDeleted()) {
3320
0
      if (Diagnose) {
3321
0
        Diag(StartLoc, diag::err_deleted_function_use);
3322
0
        NoteDeletedFunction(Operator);
3323
0
      }
3324
0
      return true;
3325
0
    }
3326
3327
0
    if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
3328
0
                              Matches[0].Found, Diagnose) == AR_inaccessible)
3329
0
      return true;
3330
3331
0
    return false;
3332
0
  }
3333
3334
  // We found multiple suitable operators; complain about the ambiguity.
3335
  // FIXME: The standard doesn't say to do this; it appears that the intent
3336
  // is that this should never happen.
3337
0
  if (!Matches.empty()) {
3338
0
    if (Diagnose) {
3339
0
      Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
3340
0
        << Name << RD;
3341
0
      for (auto &Match : Matches)
3342
0
        Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
3343
0
    }
3344
0
    return true;
3345
0
  }
3346
3347
  // We did find operator delete/operator delete[] declarations, but
3348
  // none of them were suitable.
3349
0
  if (!Found.empty()) {
3350
0
    if (Diagnose) {
3351
0
      Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
3352
0
        << Name << RD;
3353
3354
0
      for (NamedDecl *D : Found)
3355
0
        Diag(D->getUnderlyingDecl()->getLocation(),
3356
0
             diag::note_member_declared_here) << Name;
3357
0
    }
3358
0
    return true;
3359
0
  }
3360
3361
0
  Operator = nullptr;
3362
0
  return false;
3363
0
}
3364
3365
namespace {
3366
/// Checks whether delete-expression, and new-expression used for
3367
///  initializing deletee have the same array form.
3368
class MismatchingNewDeleteDetector {
3369
public:
3370
  enum MismatchResult {
3371
    /// Indicates that there is no mismatch or a mismatch cannot be proven.
3372
    NoMismatch,
3373
    /// Indicates that variable is initialized with mismatching form of \a new.
3374
    VarInitMismatches,
3375
    /// Indicates that member is initialized with mismatching form of \a new.
3376
    MemberInitMismatches,
3377
    /// Indicates that 1 or more constructors' definitions could not been
3378
    /// analyzed, and they will be checked again at the end of translation unit.
3379
    AnalyzeLater
3380
  };
3381
3382
  /// \param EndOfTU True, if this is the final analysis at the end of
3383
  /// translation unit. False, if this is the initial analysis at the point
3384
  /// delete-expression was encountered.
3385
  explicit MismatchingNewDeleteDetector(bool EndOfTU)
3386
      : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
3387
0
        HasUndefinedConstructors(false) {}
3388
3389
  /// Checks whether pointee of a delete-expression is initialized with
3390
  /// matching form of new-expression.
3391
  ///
3392
  /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
3393
  /// point where delete-expression is encountered, then a warning will be
3394
  /// issued immediately. If return value is \c AnalyzeLater at the point where
3395
  /// delete-expression is seen, then member will be analyzed at the end of
3396
  /// translation unit. \c AnalyzeLater is returned iff at least one constructor
3397
  /// couldn't be analyzed. If at least one constructor initializes the member
3398
  /// with matching type of new, the return value is \c NoMismatch.
3399
  MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
3400
  /// Analyzes a class member.
3401
  /// \param Field Class member to analyze.
3402
  /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3403
  /// for deleting the \p Field.
3404
  MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
3405
  FieldDecl *Field;
3406
  /// List of mismatching new-expressions used for initialization of the pointee
3407
  llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
3408
  /// Indicates whether delete-expression was in array form.
3409
  bool IsArrayForm;
3410
3411
private:
3412
  const bool EndOfTU;
3413
  /// Indicates that there is at least one constructor without body.
3414
  bool HasUndefinedConstructors;
3415
  /// Returns \c CXXNewExpr from given initialization expression.
3416
  /// \param E Expression used for initializing pointee in delete-expression.
3417
  /// E can be a single-element \c InitListExpr consisting of new-expression.
3418
  const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
3419
  /// Returns whether member is initialized with mismatching form of
3420
  /// \c new either by the member initializer or in-class initialization.
3421
  ///
3422
  /// If bodies of all constructors are not visible at the end of translation
3423
  /// unit or at least one constructor initializes member with the matching
3424
  /// form of \c new, mismatch cannot be proven, and this function will return
3425
  /// \c NoMismatch.
3426
  MismatchResult analyzeMemberExpr(const MemberExpr *ME);
3427
  /// Returns whether variable is initialized with mismatching form of
3428
  /// \c new.
3429
  ///
3430
  /// If variable is initialized with matching form of \c new or variable is not
3431
  /// initialized with a \c new expression, this function will return true.
3432
  /// If variable is initialized with mismatching form of \c new, returns false.
3433
  /// \param D Variable to analyze.
3434
  bool hasMatchingVarInit(const DeclRefExpr *D);
3435
  /// Checks whether the constructor initializes pointee with mismatching
3436
  /// form of \c new.
3437
  ///
3438
  /// Returns true, if member is initialized with matching form of \c new in
3439
  /// member initializer list. Returns false, if member is initialized with the
3440
  /// matching form of \c new in this constructor's initializer or given
3441
  /// constructor isn't defined at the point where delete-expression is seen, or
3442
  /// member isn't initialized by the constructor.
3443
  bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3444
  /// Checks whether member is initialized with matching form of
3445
  /// \c new in member initializer list.
3446
  bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3447
  /// Checks whether member is initialized with mismatching form of \c new by
3448
  /// in-class initializer.
3449
  MismatchResult analyzeInClassInitializer();
3450
};
3451
}
3452
3453
MismatchingNewDeleteDetector::MismatchResult
3454
0
MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3455
0
  NewExprs.clear();
3456
0
  assert(DE && "Expected delete-expression");
3457
0
  IsArrayForm = DE->isArrayForm();
3458
0
  const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3459
0
  if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3460
0
    return analyzeMemberExpr(ME);
3461
0
  } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3462
0
    if (!hasMatchingVarInit(D))
3463
0
      return VarInitMismatches;
3464
0
  }
3465
0
  return NoMismatch;
3466
0
}
3467
3468
const CXXNewExpr *
3469
0
MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3470
0
  assert(E != nullptr && "Expected a valid initializer expression");
3471
0
  E = E->IgnoreParenImpCasts();
3472
0
  if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3473
0
    if (ILE->getNumInits() == 1)
3474
0
      E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3475
0
  }
3476
3477
0
  return dyn_cast_or_null<const CXXNewExpr>(E);
3478
0
}
3479
3480
bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3481
0
    const CXXCtorInitializer *CI) {
3482
0
  const CXXNewExpr *NE = nullptr;
3483
0
  if (Field == CI->getMember() &&
3484
0
      (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3485
0
    if (NE->isArray() == IsArrayForm)
3486
0
      return true;
3487
0
    else
3488
0
      NewExprs.push_back(NE);
3489
0
  }
3490
0
  return false;
3491
0
}
3492
3493
bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3494
0
    const CXXConstructorDecl *CD) {
3495
0
  if (CD->isImplicit())
3496
0
    return false;
3497
0
  const FunctionDecl *Definition = CD;
3498
0
  if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3499
0
    HasUndefinedConstructors = true;
3500
0
    return EndOfTU;
3501
0
  }
3502
0
  for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3503
0
    if (hasMatchingNewInCtorInit(CI))
3504
0
      return true;
3505
0
  }
3506
0
  return false;
3507
0
}
3508
3509
MismatchingNewDeleteDetector::MismatchResult
3510
0
MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3511
0
  assert(Field != nullptr && "This should be called only for members");
3512
0
  const Expr *InitExpr = Field->getInClassInitializer();
3513
0
  if (!InitExpr)
3514
0
    return EndOfTU ? NoMismatch : AnalyzeLater;
3515
0
  if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3516
0
    if (NE->isArray() != IsArrayForm) {
3517
0
      NewExprs.push_back(NE);
3518
0
      return MemberInitMismatches;
3519
0
    }
3520
0
  }
3521
0
  return NoMismatch;
3522
0
}
3523
3524
MismatchingNewDeleteDetector::MismatchResult
3525
MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3526
0
                                           bool DeleteWasArrayForm) {
3527
0
  assert(Field != nullptr && "Analysis requires a valid class member.");
3528
0
  this->Field = Field;
3529
0
  IsArrayForm = DeleteWasArrayForm;
3530
0
  const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3531
0
  for (const auto *CD : RD->ctors()) {
3532
0
    if (hasMatchingNewInCtor(CD))
3533
0
      return NoMismatch;
3534
0
  }
3535
0
  if (HasUndefinedConstructors)
3536
0
    return EndOfTU ? NoMismatch : AnalyzeLater;
3537
0
  if (!NewExprs.empty())
3538
0
    return MemberInitMismatches;
3539
0
  return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3540
0
                                        : NoMismatch;
3541
0
}
3542
3543
MismatchingNewDeleteDetector::MismatchResult
3544
0
MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3545
0
  assert(ME != nullptr && "Expected a member expression");
3546
0
  if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3547
0
    return analyzeField(F, IsArrayForm);
3548
0
  return NoMismatch;
3549
0
}
3550
3551
0
bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3552
0
  const CXXNewExpr *NE = nullptr;
3553
0
  if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3554
0
    if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3555
0
        NE->isArray() != IsArrayForm) {
3556
0
      NewExprs.push_back(NE);
3557
0
    }
3558
0
  }
3559
0
  return NewExprs.empty();
3560
0
}
3561
3562
static void
3563
DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3564
0
                            const MismatchingNewDeleteDetector &Detector) {
3565
0
  SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3566
0
  FixItHint H;
3567
0
  if (!Detector.IsArrayForm)
3568
0
    H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3569
0
  else {
3570
0
    SourceLocation RSquare = Lexer::findLocationAfterToken(
3571
0
        DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3572
0
        SemaRef.getLangOpts(), true);
3573
0
    if (RSquare.isValid())
3574
0
      H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3575
0
  }
3576
0
  SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3577
0
      << Detector.IsArrayForm << H;
3578
3579
0
  for (const auto *NE : Detector.NewExprs)
3580
0
    SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3581
0
        << Detector.IsArrayForm;
3582
0
}
3583
3584
0
void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3585
0
  if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3586
0
    return;
3587
0
  MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3588
0
  switch (Detector.analyzeDeleteExpr(DE)) {
3589
0
  case MismatchingNewDeleteDetector::VarInitMismatches:
3590
0
  case MismatchingNewDeleteDetector::MemberInitMismatches: {
3591
0
    DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
3592
0
    break;
3593
0
  }
3594
0
  case MismatchingNewDeleteDetector::AnalyzeLater: {
3595
0
    DeleteExprs[Detector.Field].push_back(
3596
0
        std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
3597
0
    break;
3598
0
  }
3599
0
  case MismatchingNewDeleteDetector::NoMismatch:
3600
0
    break;
3601
0
  }
3602
0
}
3603
3604
void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3605
0
                                     bool DeleteWasArrayForm) {
3606
0
  MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3607
0
  switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3608
0
  case MismatchingNewDeleteDetector::VarInitMismatches:
3609
0
    llvm_unreachable("This analysis should have been done for class members.");
3610
0
  case MismatchingNewDeleteDetector::AnalyzeLater:
3611
0
    llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3612
0
                     "translation unit.");
3613
0
  case MismatchingNewDeleteDetector::MemberInitMismatches:
3614
0
    DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3615
0
    break;
3616
0
  case MismatchingNewDeleteDetector::NoMismatch:
3617
0
    break;
3618
0
  }
3619
0
}
3620
3621
/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3622
/// @code ::delete ptr; @endcode
3623
/// or
3624
/// @code delete [] ptr; @endcode
3625
ExprResult
3626
Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3627
0
                     bool ArrayForm, Expr *ExE) {
3628
  // C++ [expr.delete]p1:
3629
  //   The operand shall have a pointer type, or a class type having a single
3630
  //   non-explicit conversion function to a pointer type. The result has type
3631
  //   void.
3632
  //
3633
  // DR599 amends "pointer type" to "pointer to object type" in both cases.
3634
3635
0
  ExprResult Ex = ExE;
3636
0
  FunctionDecl *OperatorDelete = nullptr;
3637
0
  bool ArrayFormAsWritten = ArrayForm;
3638
0
  bool UsualArrayDeleteWantsSize = false;
3639
3640
0
  if (!Ex.get()->isTypeDependent()) {
3641
    // Perform lvalue-to-rvalue cast, if needed.
3642
0
    Ex = DefaultLvalueConversion(Ex.get());
3643
0
    if (Ex.isInvalid())
3644
0
      return ExprError();
3645
3646
0
    QualType Type = Ex.get()->getType();
3647
3648
0
    class DeleteConverter : public ContextualImplicitConverter {
3649
0
    public:
3650
0
      DeleteConverter() : ContextualImplicitConverter(false, true) {}
3651
3652
0
      bool match(QualType ConvType) override {
3653
        // FIXME: If we have an operator T* and an operator void*, we must pick
3654
        // the operator T*.
3655
0
        if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3656
0
          if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3657
0
            return true;
3658
0
        return false;
3659
0
      }
3660
3661
0
      SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3662
0
                                            QualType T) override {
3663
0
        return S.Diag(Loc, diag::err_delete_operand) << T;
3664
0
      }
3665
3666
0
      SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3667
0
                                               QualType T) override {
3668
0
        return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3669
0
      }
3670
3671
0
      SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3672
0
                                                 QualType T,
3673
0
                                                 QualType ConvTy) override {
3674
0
        return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3675
0
      }
3676
3677
0
      SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3678
0
                                             QualType ConvTy) override {
3679
0
        return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3680
0
          << ConvTy;
3681
0
      }
3682
3683
0
      SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3684
0
                                              QualType T) override {
3685
0
        return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3686
0
      }
3687
3688
0
      SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3689
0
                                          QualType ConvTy) override {
3690
0
        return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3691
0
          << ConvTy;
3692
0
      }
3693
3694
0
      SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3695
0
                                               QualType T,
3696
0
                                               QualType ConvTy) override {
3697
0
        llvm_unreachable("conversion functions are permitted");
3698
0
      }
3699
0
    } Converter;
3700
3701
0
    Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3702
0
    if (Ex.isInvalid())
3703
0
      return ExprError();
3704
0
    Type = Ex.get()->getType();
3705
0
    if (!Converter.match(Type))
3706
      // FIXME: PerformContextualImplicitConversion should return ExprError
3707
      //        itself in this case.
3708
0
      return ExprError();
3709
3710
0
    QualType Pointee = Type->castAs<PointerType>()->getPointeeType();
3711
0
    QualType PointeeElem = Context.getBaseElementType(Pointee);
3712
3713
0
    if (Pointee.getAddressSpace() != LangAS::Default &&
3714
0
        !getLangOpts().OpenCLCPlusPlus)
3715
0
      return Diag(Ex.get()->getBeginLoc(),
3716
0
                  diag::err_address_space_qualified_delete)
3717
0
             << Pointee.getUnqualifiedType()
3718
0
             << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
3719
3720
0
    CXXRecordDecl *PointeeRD = nullptr;
3721
0
    if (Pointee->isVoidType() && !isSFINAEContext()) {
3722
      // The C++ standard bans deleting a pointer to a non-object type, which
3723
      // effectively bans deletion of "void*". However, most compilers support
3724
      // this, so we treat it as a warning unless we're in a SFINAE context.
3725
0
      Diag(StartLoc, diag::ext_delete_void_ptr_operand)
3726
0
        << Type << Ex.get()->getSourceRange();
3727
0
    } else if (Pointee->isFunctionType() || Pointee->isVoidType() ||
3728
0
               Pointee->isSizelessType()) {
3729
0
      return ExprError(Diag(StartLoc, diag::err_delete_operand)
3730
0
        << Type << Ex.get()->getSourceRange());
3731
0
    } else if (!Pointee->isDependentType()) {
3732
      // FIXME: This can result in errors if the definition was imported from a
3733
      // module but is hidden.
3734
0
      if (!RequireCompleteType(StartLoc, Pointee,
3735
0
                               diag::warn_delete_incomplete, Ex.get())) {
3736
0
        if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3737
0
          PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3738
0
      }
3739
0
    }
3740
3741
0
    if (Pointee->isArrayType() && !ArrayForm) {
3742
0
      Diag(StartLoc, diag::warn_delete_array_type)
3743
0
          << Type << Ex.get()->getSourceRange()
3744
0
          << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
3745
0
      ArrayForm = true;
3746
0
    }
3747
3748
0
    DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3749
0
                                      ArrayForm ? OO_Array_Delete : OO_Delete);
3750
3751
0
    if (PointeeRD) {
3752
0
      if (!UseGlobal &&
3753
0
          FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3754
0
                                   OperatorDelete))
3755
0
        return ExprError();
3756
3757
      // If we're allocating an array of records, check whether the
3758
      // usual operator delete[] has a size_t parameter.
3759
0
      if (ArrayForm) {
3760
        // If the user specifically asked to use the global allocator,
3761
        // we'll need to do the lookup into the class.
3762
0
        if (UseGlobal)
3763
0
          UsualArrayDeleteWantsSize =
3764
0
            doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3765
3766
        // Otherwise, the usual operator delete[] should be the
3767
        // function we just found.
3768
0
        else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
3769
0
          UsualArrayDeleteWantsSize =
3770
0
            UsualDeallocFnInfo(*this,
3771
0
                               DeclAccessPair::make(OperatorDelete, AS_public))
3772
0
              .HasSizeT;
3773
0
      }
3774
3775
0
      if (!PointeeRD->hasIrrelevantDestructor())
3776
0
        if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3777
0
          MarkFunctionReferenced(StartLoc,
3778
0
                                    const_cast<CXXDestructorDecl*>(Dtor));
3779
0
          if (DiagnoseUseOfDecl(Dtor, StartLoc))
3780
0
            return ExprError();
3781
0
        }
3782
3783
0
      CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3784
0
                           /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3785
0
                           /*WarnOnNonAbstractTypes=*/!ArrayForm,
3786
0
                           SourceLocation());
3787
0
    }
3788
3789
0
    if (!OperatorDelete) {
3790
0
      if (getLangOpts().OpenCLCPlusPlus) {
3791
0
        Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3792
0
        return ExprError();
3793
0
      }
3794
3795
0
      bool IsComplete = isCompleteType(StartLoc, Pointee);
3796
0
      bool CanProvideSize =
3797
0
          IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3798
0
                         Pointee.isDestructedType());
3799
0
      bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3800
3801
      // Look for a global declaration.
3802
0
      OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3803
0
                                                     Overaligned, DeleteName);
3804
0
    }
3805
3806
0
    MarkFunctionReferenced(StartLoc, OperatorDelete);
3807
3808
    // Check access and ambiguity of destructor if we're going to call it.
3809
    // Note that this is required even for a virtual delete.
3810
0
    bool IsVirtualDelete = false;
3811
0
    if (PointeeRD) {
3812
0
      if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3813
0
        CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3814
0
                              PDiag(diag::err_access_dtor) << PointeeElem);
3815
0
        IsVirtualDelete = Dtor->isVirtual();
3816
0
      }
3817
0
    }
3818
3819
0
    DiagnoseUseOfDecl(OperatorDelete, StartLoc);
3820
3821
    // Convert the operand to the type of the first parameter of operator
3822
    // delete. This is only necessary if we selected a destroying operator
3823
    // delete that we are going to call (non-virtually); converting to void*
3824
    // is trivial and left to AST consumers to handle.
3825
0
    QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3826
0
    if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
3827
0
      Qualifiers Qs = Pointee.getQualifiers();
3828
0
      if (Qs.hasCVRQualifiers()) {
3829
        // Qualifiers are irrelevant to this conversion; we're only looking
3830
        // for access and ambiguity.
3831
0
        Qs.removeCVRQualifiers();
3832
0
        QualType Unqual = Context.getPointerType(
3833
0
            Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3834
0
        Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3835
0
      }
3836
0
      Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3837
0
      if (Ex.isInvalid())
3838
0
        return ExprError();
3839
0
    }
3840
0
  }
3841
3842
0
  CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
3843
0
      Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3844
0
      UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3845
0
  AnalyzeDeleteExprMismatch(Result);
3846
0
  return Result;
3847
0
}
3848
3849
static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
3850
                                            bool IsDelete,
3851
0
                                            FunctionDecl *&Operator) {
3852
3853
0
  DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
3854
0
      IsDelete ? OO_Delete : OO_New);
3855
3856
0
  LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
3857
0
  S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
3858
0
  assert(!R.empty() && "implicitly declared allocation functions not found");
3859
0
  assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3860
3861
  // We do our own custom access checks below.
3862
0
  R.suppressDiagnostics();
3863
3864
0
  SmallVector<Expr *, 8> Args(TheCall->arguments());
3865
0
  OverloadCandidateSet Candidates(R.getNameLoc(),
3866
0
                                  OverloadCandidateSet::CSK_Normal);
3867
0
  for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3868
0
       FnOvl != FnOvlEnd; ++FnOvl) {
3869
    // Even member operator new/delete are implicitly treated as
3870
    // static, so don't use AddMemberCandidate.
3871
0
    NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3872
3873
0
    if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3874
0
      S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3875
0
                                     /*ExplicitTemplateArgs=*/nullptr, Args,
3876
0
                                     Candidates,
3877
0
                                     /*SuppressUserConversions=*/false);
3878
0
      continue;
3879
0
    }
3880
3881
0
    FunctionDecl *Fn = cast<FunctionDecl>(D);
3882
0
    S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3883
0
                           /*SuppressUserConversions=*/false);
3884
0
  }
3885
3886
0
  SourceRange Range = TheCall->getSourceRange();
3887
3888
  // Do the resolution.
3889
0
  OverloadCandidateSet::iterator Best;
3890
0
  switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3891
0
  case OR_Success: {
3892
    // Got one!
3893
0
    FunctionDecl *FnDecl = Best->Function;
3894
0
    assert(R.getNamingClass() == nullptr &&
3895
0
           "class members should not be considered");
3896
3897
0
    if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3898
0
      S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3899
0
          << (IsDelete ? 1 : 0) << Range;
3900
0
      S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3901
0
          << R.getLookupName() << FnDecl->getSourceRange();
3902
0
      return true;
3903
0
    }
3904
3905
0
    Operator = FnDecl;
3906
0
    return false;
3907
0
  }
3908
3909
0
  case OR_No_Viable_Function:
3910
0
    Candidates.NoteCandidates(
3911
0
        PartialDiagnosticAt(R.getNameLoc(),
3912
0
                            S.PDiag(diag::err_ovl_no_viable_function_in_call)
3913
0
                                << R.getLookupName() << Range),
3914
0
        S, OCD_AllCandidates, Args);
3915
0
    return true;
3916
3917
0
  case OR_Ambiguous:
3918
0
    Candidates.NoteCandidates(
3919
0
        PartialDiagnosticAt(R.getNameLoc(),
3920
0
                            S.PDiag(diag::err_ovl_ambiguous_call)
3921
0
                                << R.getLookupName() << Range),
3922
0
        S, OCD_AmbiguousCandidates, Args);
3923
0
    return true;
3924
3925
0
  case OR_Deleted: {
3926
0
    Candidates.NoteCandidates(
3927
0
        PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call)
3928
0
                                                << R.getLookupName() << Range),
3929
0
        S, OCD_AllCandidates, Args);
3930
0
    return true;
3931
0
  }
3932
0
  }
3933
0
  llvm_unreachable("Unreachable, bad result from BestViableFunction");
3934
0
}
3935
3936
ExprResult
3937
Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3938
0
                                             bool IsDelete) {
3939
0
  CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3940
0
  if (!getLangOpts().CPlusPlus) {
3941
0
    Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3942
0
        << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3943
0
        << "C++";
3944
0
    return ExprError();
3945
0
  }
3946
  // CodeGen assumes it can find the global new and delete to call,
3947
  // so ensure that they are declared.
3948
0
  DeclareGlobalNewDelete();
3949
3950
0
  FunctionDecl *OperatorNewOrDelete = nullptr;
3951
0
  if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3952
0
                                      OperatorNewOrDelete))
3953
0
    return ExprError();
3954
0
  assert(OperatorNewOrDelete && "should be found");
3955
3956
0
  DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3957
0
  MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3958
3959
0
  TheCall->setType(OperatorNewOrDelete->getReturnType());
3960
0
  for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3961
0
    QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3962
0
    InitializedEntity Entity =
3963
0
        InitializedEntity::InitializeParameter(Context, ParamTy, false);
3964
0
    ExprResult Arg = PerformCopyInitialization(
3965
0
        Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
3966
0
    if (Arg.isInvalid())
3967
0
      return ExprError();
3968
0
    TheCall->setArg(i, Arg.get());
3969
0
  }
3970
0
  auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3971
0
  assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3972
0
         "Callee expected to be implicit cast to a builtin function pointer");
3973
0
  Callee->setType(OperatorNewOrDelete->getType());
3974
3975
0
  return TheCallResult;
3976
0
}
3977
3978
void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3979
                                bool IsDelete, bool CallCanBeVirtual,
3980
                                bool WarnOnNonAbstractTypes,
3981
0
                                SourceLocation DtorLoc) {
3982
0
  if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
3983
0
    return;
3984
3985
  // C++ [expr.delete]p3:
3986
  //   In the first alternative (delete object), if the static type of the
3987
  //   object to be deleted is different from its dynamic type, the static
3988
  //   type shall be a base class of the dynamic type of the object to be
3989
  //   deleted and the static type shall have a virtual destructor or the
3990
  //   behavior is undefined.
3991
  //
3992
0
  const CXXRecordDecl *PointeeRD = dtor->getParent();
3993
  // Note: a final class cannot be derived from, no issue there
3994
0
  if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3995
0
    return;
3996
3997
  // If the superclass is in a system header, there's nothing that can be done.
3998
  // The `delete` (where we emit the warning) can be in a system header,
3999
  // what matters for this warning is where the deleted type is defined.
4000
0
  if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
4001
0
    return;
4002
4003
0
  QualType ClassType = dtor->getFunctionObjectParameterType();
4004
0
  if (PointeeRD->isAbstract()) {
4005
    // If the class is abstract, we warn by default, because we're
4006
    // sure the code has undefined behavior.
4007
0
    Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
4008
0
                                                           << ClassType;
4009
0
  } else if (WarnOnNonAbstractTypes) {
4010
    // Otherwise, if this is not an array delete, it's a bit suspect,
4011
    // but not necessarily wrong.
4012
0
    Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
4013
0
                                                  << ClassType;
4014
0
  }
4015
0
  if (!IsDelete) {
4016
0
    std::string TypeStr;
4017
0
    ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
4018
0
    Diag(DtorLoc, diag::note_delete_non_virtual)
4019
0
        << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
4020
0
  }
4021
0
}
4022
4023
Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
4024
                                                   SourceLocation StmtLoc,
4025
0
                                                   ConditionKind CK) {
4026
0
  ExprResult E =
4027
0
      CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
4028
0
  if (E.isInvalid())
4029
0
    return ConditionError();
4030
0
  return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
4031
0
                         CK == ConditionKind::ConstexprIf);
4032
0
}
4033
4034
/// Check the use of the given variable as a C++ condition in an if,
4035
/// while, do-while, or switch statement.
4036
ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
4037
                                        SourceLocation StmtLoc,
4038
0
                                        ConditionKind CK) {
4039
0
  if (ConditionVar->isInvalidDecl())
4040
0
    return ExprError();
4041
4042
0
  QualType T = ConditionVar->getType();
4043
4044
  // C++ [stmt.select]p2:
4045
  //   The declarator shall not specify a function or an array.
4046
0
  if (T->isFunctionType())
4047
0
    return ExprError(Diag(ConditionVar->getLocation(),
4048
0
                          diag::err_invalid_use_of_function_type)
4049
0
                       << ConditionVar->getSourceRange());
4050
0
  else if (T->isArrayType())
4051
0
    return ExprError(Diag(ConditionVar->getLocation(),
4052
0
                          diag::err_invalid_use_of_array_type)
4053
0
                     << ConditionVar->getSourceRange());
4054
4055
0
  ExprResult Condition = BuildDeclRefExpr(
4056
0
      ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
4057
0
      ConditionVar->getLocation());
4058
4059
0
  switch (CK) {
4060
0
  case ConditionKind::Boolean:
4061
0
    return CheckBooleanCondition(StmtLoc, Condition.get());
4062
4063
0
  case ConditionKind::ConstexprIf:
4064
0
    return CheckBooleanCondition(StmtLoc, Condition.get(), true);
4065
4066
0
  case ConditionKind::Switch:
4067
0
    return CheckSwitchCondition(StmtLoc, Condition.get());
4068
0
  }
4069
4070
0
  llvm_unreachable("unexpected condition kind");
4071
0
}
4072
4073
/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
4074
0
ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
4075
  // C++11 6.4p4:
4076
  // The value of a condition that is an initialized declaration in a statement
4077
  // other than a switch statement is the value of the declared variable
4078
  // implicitly converted to type bool. If that conversion is ill-formed, the
4079
  // program is ill-formed.
4080
  // The value of a condition that is an expression is the value of the
4081
  // expression, implicitly converted to bool.
4082
  //
4083
  // C++23 8.5.2p2
4084
  // If the if statement is of the form if constexpr, the value of the condition
4085
  // is contextually converted to bool and the converted expression shall be
4086
  // a constant expression.
4087
  //
4088
4089
0
  ExprResult E = PerformContextuallyConvertToBool(CondExpr);
4090
0
  if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent())
4091
0
    return E;
4092
4093
  // FIXME: Return this value to the caller so they don't need to recompute it.
4094
0
  llvm::APSInt Cond;
4095
0
  E = VerifyIntegerConstantExpression(
4096
0
      E.get(), &Cond,
4097
0
      diag::err_constexpr_if_condition_expression_is_not_constant);
4098
0
  return E;
4099
0
}
4100
4101
/// Helper function to determine whether this is the (deprecated) C++
4102
/// conversion from a string literal to a pointer to non-const char or
4103
/// non-const wchar_t (for narrow and wide string literals,
4104
/// respectively).
4105
bool
4106
0
Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
4107
  // Look inside the implicit cast, if it exists.
4108
0
  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
4109
0
    From = Cast->getSubExpr();
4110
4111
  // A string literal (2.13.4) that is not a wide string literal can
4112
  // be converted to an rvalue of type "pointer to char"; a wide
4113
  // string literal can be converted to an rvalue of type "pointer
4114
  // to wchar_t" (C++ 4.2p2).
4115
0
  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
4116
0
    if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
4117
0
      if (const BuiltinType *ToPointeeType
4118
0
          = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
4119
        // This conversion is considered only when there is an
4120
        // explicit appropriate pointer target type (C++ 4.2p2).
4121
0
        if (!ToPtrType->getPointeeType().hasQualifiers()) {
4122
0
          switch (StrLit->getKind()) {
4123
0
          case StringLiteralKind::UTF8:
4124
0
          case StringLiteralKind::UTF16:
4125
0
          case StringLiteralKind::UTF32:
4126
            // We don't allow UTF literals to be implicitly converted
4127
0
            break;
4128
0
          case StringLiteralKind::Ordinary:
4129
0
            return (ToPointeeType->getKind() == BuiltinType::Char_U ||
4130
0
                    ToPointeeType->getKind() == BuiltinType::Char_S);
4131
0
          case StringLiteralKind::Wide:
4132
0
            return Context.typesAreCompatible(Context.getWideCharType(),
4133
0
                                              QualType(ToPointeeType, 0));
4134
0
          case StringLiteralKind::Unevaluated:
4135
0
            assert(false && "Unevaluated string literal in expression");
4136
0
            break;
4137
0
          }
4138
0
        }
4139
0
      }
4140
4141
0
  return false;
4142
0
}
4143
4144
static ExprResult BuildCXXCastArgument(Sema &S,
4145
                                       SourceLocation CastLoc,
4146
                                       QualType Ty,
4147
                                       CastKind Kind,
4148
                                       CXXMethodDecl *Method,
4149
                                       DeclAccessPair FoundDecl,
4150
                                       bool HadMultipleCandidates,
4151
0
                                       Expr *From) {
4152
0
  switch (Kind) {
4153
0
  default: llvm_unreachable("Unhandled cast kind!");
4154
0
  case CK_ConstructorConversion: {
4155
0
    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
4156
0
    SmallVector<Expr*, 8> ConstructorArgs;
4157
4158
0
    if (S.RequireNonAbstractType(CastLoc, Ty,
4159
0
                                 diag::err_allocation_of_abstract_type))
4160
0
      return ExprError();
4161
4162
0
    if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc,
4163
0
                                  ConstructorArgs))
4164
0
      return ExprError();
4165
4166
0
    S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
4167
0
                             InitializedEntity::InitializeTemporary(Ty));
4168
0
    if (S.DiagnoseUseOfDecl(Method, CastLoc))
4169
0
      return ExprError();
4170
4171
0
    ExprResult Result = S.BuildCXXConstructExpr(
4172
0
        CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
4173
0
        ConstructorArgs, HadMultipleCandidates,
4174
0
        /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4175
0
        CXXConstructionKind::Complete, SourceRange());
4176
0
    if (Result.isInvalid())
4177
0
      return ExprError();
4178
4179
0
    return S.MaybeBindToTemporary(Result.getAs<Expr>());
4180
0
  }
4181
4182
0
  case CK_UserDefinedConversion: {
4183
0
    assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
4184
4185
0
    S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
4186
0
    if (S.DiagnoseUseOfDecl(Method, CastLoc))
4187
0
      return ExprError();
4188
4189
    // Create an implicit call expr that calls it.
4190
0
    CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
4191
0
    ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
4192
0
                                                 HadMultipleCandidates);
4193
0
    if (Result.isInvalid())
4194
0
      return ExprError();
4195
    // Record usage of conversion in an implicit cast.
4196
0
    Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
4197
0
                                      CK_UserDefinedConversion, Result.get(),
4198
0
                                      nullptr, Result.get()->getValueKind(),
4199
0
                                      S.CurFPFeatureOverrides());
4200
4201
0
    return S.MaybeBindToTemporary(Result.get());
4202
0
  }
4203
0
  }
4204
0
}
4205
4206
/// PerformImplicitConversion - Perform an implicit conversion of the
4207
/// expression From to the type ToType using the pre-computed implicit
4208
/// conversion sequence ICS. Returns the converted
4209
/// expression. Action is the kind of conversion we're performing,
4210
/// used in the error message.
4211
ExprResult
4212
Sema::PerformImplicitConversion(Expr *From, QualType ToType,
4213
                                const ImplicitConversionSequence &ICS,
4214
                                AssignmentAction Action,
4215
0
                                CheckedConversionKind CCK) {
4216
  // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
4217
0
  if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType())
4218
0
    return From;
4219
4220
0
  switch (ICS.getKind()) {
4221
0
  case ImplicitConversionSequence::StandardConversion: {
4222
0
    ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
4223
0
                                               Action, CCK);
4224
0
    if (Res.isInvalid())
4225
0
      return ExprError();
4226
0
    From = Res.get();
4227
0
    break;
4228
0
  }
4229
4230
0
  case ImplicitConversionSequence::UserDefinedConversion: {
4231
4232
0
      FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
4233
0
      CastKind CastKind;
4234
0
      QualType BeforeToType;
4235
0
      assert(FD && "no conversion function for user-defined conversion seq");
4236
0
      if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
4237
0
        CastKind = CK_UserDefinedConversion;
4238
4239
        // If the user-defined conversion is specified by a conversion function,
4240
        // the initial standard conversion sequence converts the source type to
4241
        // the implicit object parameter of the conversion function.
4242
0
        BeforeToType = Context.getTagDeclType(Conv->getParent());
4243
0
      } else {
4244
0
        const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
4245
0
        CastKind = CK_ConstructorConversion;
4246
        // Do no conversion if dealing with ... for the first conversion.
4247
0
        if (!ICS.UserDefined.EllipsisConversion) {
4248
          // If the user-defined conversion is specified by a constructor, the
4249
          // initial standard conversion sequence converts the source type to
4250
          // the type required by the argument of the constructor
4251
0
          BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
4252
0
        }
4253
0
      }
4254
      // Watch out for ellipsis conversion.
4255
0
      if (!ICS.UserDefined.EllipsisConversion) {
4256
0
        ExprResult Res =
4257
0
          PerformImplicitConversion(From, BeforeToType,
4258
0
                                    ICS.UserDefined.Before, AA_Converting,
4259
0
                                    CCK);
4260
0
        if (Res.isInvalid())
4261
0
          return ExprError();
4262
0
        From = Res.get();
4263
0
      }
4264
4265
0
      ExprResult CastArg = BuildCXXCastArgument(
4266
0
          *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
4267
0
          cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
4268
0
          ICS.UserDefined.HadMultipleCandidates, From);
4269
4270
0
      if (CastArg.isInvalid())
4271
0
        return ExprError();
4272
4273
0
      From = CastArg.get();
4274
4275
      // C++ [over.match.oper]p7:
4276
      //   [...] the second standard conversion sequence of a user-defined
4277
      //   conversion sequence is not applied.
4278
0
      if (CCK == CCK_ForBuiltinOverloadedOp)
4279
0
        return From;
4280
4281
0
      return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
4282
0
                                       AA_Converting, CCK);
4283
0
  }
4284
4285
0
  case ImplicitConversionSequence::AmbiguousConversion:
4286
0
    ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
4287
0
                          PDiag(diag::err_typecheck_ambiguous_condition)
4288
0
                            << From->getSourceRange());
4289
0
    return ExprError();
4290
4291
0
  case ImplicitConversionSequence::EllipsisConversion:
4292
0
  case ImplicitConversionSequence::StaticObjectArgumentConversion:
4293
0
    llvm_unreachable("bad conversion");
4294
4295
0
  case ImplicitConversionSequence::BadConversion:
4296
0
    Sema::AssignConvertType ConvTy =
4297
0
        CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType());
4298
0
    bool Diagnosed = DiagnoseAssignmentResult(
4299
0
        ConvTy == Compatible ? Incompatible : ConvTy, From->getExprLoc(),
4300
0
        ToType, From->getType(), From, Action);
4301
0
    assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
4302
0
    return ExprError();
4303
0
  }
4304
4305
  // Everything went well.
4306
0
  return From;
4307
0
}
4308
4309
/// PerformImplicitConversion - Perform an implicit conversion of the
4310
/// expression From to the type ToType by following the standard
4311
/// conversion sequence SCS. Returns the converted
4312
/// expression. Flavor is the context in which we're performing this
4313
/// conversion, for use in error messages.
4314
ExprResult
4315
Sema::PerformImplicitConversion(Expr *From, QualType ToType,
4316
                                const StandardConversionSequence& SCS,
4317
                                AssignmentAction Action,
4318
0
                                CheckedConversionKind CCK) {
4319
0
  bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
4320
4321
  // Overall FIXME: we are recomputing too many types here and doing far too
4322
  // much extra work. What this means is that we need to keep track of more
4323
  // information that is computed when we try the implicit conversion initially,
4324
  // so that we don't need to recompute anything here.
4325
0
  QualType FromType = From->getType();
4326
4327
0
  if (SCS.CopyConstructor) {
4328
    // FIXME: When can ToType be a reference type?
4329
0
    assert(!ToType->isReferenceType());
4330
0
    if (SCS.Second == ICK_Derived_To_Base) {
4331
0
      SmallVector<Expr*, 8> ConstructorArgs;
4332
0
      if (CompleteConstructorCall(
4333
0
              cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From,
4334
0
              /*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs))
4335
0
        return ExprError();
4336
0
      return BuildCXXConstructExpr(
4337
0
          /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4338
0
          SCS.FoundCopyConstructor, SCS.CopyConstructor, ConstructorArgs,
4339
0
          /*HadMultipleCandidates*/ false,
4340
0
          /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4341
0
          CXXConstructionKind::Complete, SourceRange());
4342
0
    }
4343
0
    return BuildCXXConstructExpr(
4344
0
        /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4345
0
        SCS.FoundCopyConstructor, SCS.CopyConstructor, From,
4346
0
        /*HadMultipleCandidates*/ false,
4347
0
        /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4348
0
        CXXConstructionKind::Complete, SourceRange());
4349
0
  }
4350
4351
  // Resolve overloaded function references.
4352
0
  if (Context.hasSameType(FromType, Context.OverloadTy)) {
4353
0
    DeclAccessPair Found;
4354
0
    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
4355
0
                                                          true, Found);
4356
0
    if (!Fn)
4357
0
      return ExprError();
4358
4359
0
    if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
4360
0
      return ExprError();
4361
4362
0
    ExprResult Res = FixOverloadedFunctionReference(From, Found, Fn);
4363
0
    if (Res.isInvalid())
4364
0
      return ExprError();
4365
4366
    // We might get back another placeholder expression if we resolved to a
4367
    // builtin.
4368
0
    Res = CheckPlaceholderExpr(Res.get());
4369
0
    if (Res.isInvalid())
4370
0
      return ExprError();
4371
4372
0
    From = Res.get();
4373
0
    FromType = From->getType();
4374
0
  }
4375
4376
  // If we're converting to an atomic type, first convert to the corresponding
4377
  // non-atomic type.
4378
0
  QualType ToAtomicType;
4379
0
  if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
4380
0
    ToAtomicType = ToType;
4381
0
    ToType = ToAtomic->getValueType();
4382
0
  }
4383
4384
0
  QualType InitialFromType = FromType;
4385
  // Perform the first implicit conversion.
4386
0
  switch (SCS.First) {
4387
0
  case ICK_Identity:
4388
0
    if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
4389
0
      FromType = FromAtomic->getValueType().getUnqualifiedType();
4390
0
      From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
4391
0
                                      From, /*BasePath=*/nullptr, VK_PRValue,
4392
0
                                      FPOptionsOverride());
4393
0
    }
4394
0
    break;
4395
4396
0
  case ICK_Lvalue_To_Rvalue: {
4397
0
    assert(From->getObjectKind() != OK_ObjCProperty);
4398
0
    ExprResult FromRes = DefaultLvalueConversion(From);
4399
0
    if (FromRes.isInvalid())
4400
0
      return ExprError();
4401
4402
0
    From = FromRes.get();
4403
0
    FromType = From->getType();
4404
0
    break;
4405
0
  }
4406
4407
0
  case ICK_Array_To_Pointer:
4408
0
    FromType = Context.getArrayDecayedType(FromType);
4409
0
    From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, VK_PRValue,
4410
0
                             /*BasePath=*/nullptr, CCK)
4411
0
               .get();
4412
0
    break;
4413
4414
0
  case ICK_Function_To_Pointer:
4415
0
    FromType = Context.getPointerType(FromType);
4416
0
    From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
4417
0
                             VK_PRValue, /*BasePath=*/nullptr, CCK)
4418
0
               .get();
4419
0
    break;
4420
4421
0
  default:
4422
0
    llvm_unreachable("Improper first standard conversion");
4423
0
  }
4424
4425
  // Perform the second implicit conversion
4426
0
  switch (SCS.Second) {
4427
0
  case ICK_Identity:
4428
    // C++ [except.spec]p5:
4429
    //   [For] assignment to and initialization of pointers to functions,
4430
    //   pointers to member functions, and references to functions: the
4431
    //   target entity shall allow at least the exceptions allowed by the
4432
    //   source value in the assignment or initialization.
4433
0
    switch (Action) {
4434
0
    case AA_Assigning:
4435
0
    case AA_Initializing:
4436
      // Note, function argument passing and returning are initialization.
4437
0
    case AA_Passing:
4438
0
    case AA_Returning:
4439
0
    case AA_Sending:
4440
0
    case AA_Passing_CFAudited:
4441
0
      if (CheckExceptionSpecCompatibility(From, ToType))
4442
0
        return ExprError();
4443
0
      break;
4444
4445
0
    case AA_Casting:
4446
0
    case AA_Converting:
4447
      // Casts and implicit conversions are not initialization, so are not
4448
      // checked for exception specification mismatches.
4449
0
      break;
4450
0
    }
4451
    // Nothing else to do.
4452
0
    break;
4453
4454
0
  case ICK_Integral_Promotion:
4455
0
  case ICK_Integral_Conversion:
4456
0
    if (ToType->isBooleanType()) {
4457
0
      assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4458
0
             SCS.Second == ICK_Integral_Promotion &&
4459
0
             "only enums with fixed underlying type can promote to bool");
4460
0
      From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean, VK_PRValue,
4461
0
                               /*BasePath=*/nullptr, CCK)
4462
0
                 .get();
4463
0
    } else {
4464
0
      From = ImpCastExprToType(From, ToType, CK_IntegralCast, VK_PRValue,
4465
0
                               /*BasePath=*/nullptr, CCK)
4466
0
                 .get();
4467
0
    }
4468
0
    break;
4469
4470
0
  case ICK_Floating_Promotion:
4471
0
  case ICK_Floating_Conversion:
4472
0
    From = ImpCastExprToType(From, ToType, CK_FloatingCast, VK_PRValue,
4473
0
                             /*BasePath=*/nullptr, CCK)
4474
0
               .get();
4475
0
    break;
4476
4477
0
  case ICK_Complex_Promotion:
4478
0
  case ICK_Complex_Conversion: {
4479
0
    QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();
4480
0
    QualType ToEl = ToType->castAs<ComplexType>()->getElementType();
4481
0
    CastKind CK;
4482
0
    if (FromEl->isRealFloatingType()) {
4483
0
      if (ToEl->isRealFloatingType())
4484
0
        CK = CK_FloatingComplexCast;
4485
0
      else
4486
0
        CK = CK_FloatingComplexToIntegralComplex;
4487
0
    } else if (ToEl->isRealFloatingType()) {
4488
0
      CK = CK_IntegralComplexToFloatingComplex;
4489
0
    } else {
4490
0
      CK = CK_IntegralComplexCast;
4491
0
    }
4492
0
    From = ImpCastExprToType(From, ToType, CK, VK_PRValue, /*BasePath=*/nullptr,
4493
0
                             CCK)
4494
0
               .get();
4495
0
    break;
4496
0
  }
4497
4498
0
  case ICK_Floating_Integral:
4499
0
    if (ToType->isRealFloatingType())
4500
0
      From = ImpCastExprToType(From, ToType, CK_IntegralToFloating, VK_PRValue,
4501
0
                               /*BasePath=*/nullptr, CCK)
4502
0
                 .get();
4503
0
    else
4504
0
      From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral, VK_PRValue,
4505
0
                               /*BasePath=*/nullptr, CCK)
4506
0
                 .get();
4507
0
    break;
4508
4509
0
  case ICK_Fixed_Point_Conversion:
4510
0
    assert((FromType->isFixedPointType() || ToType->isFixedPointType()) &&
4511
0
           "Attempting implicit fixed point conversion without a fixed "
4512
0
           "point operand");
4513
0
    if (FromType->isFloatingType())
4514
0
      From = ImpCastExprToType(From, ToType, CK_FloatingToFixedPoint,
4515
0
                               VK_PRValue,
4516
0
                               /*BasePath=*/nullptr, CCK).get();
4517
0
    else if (ToType->isFloatingType())
4518
0
      From = ImpCastExprToType(From, ToType, CK_FixedPointToFloating,
4519
0
                               VK_PRValue,
4520
0
                               /*BasePath=*/nullptr, CCK).get();
4521
0
    else if (FromType->isIntegralType(Context))
4522
0
      From = ImpCastExprToType(From, ToType, CK_IntegralToFixedPoint,
4523
0
                               VK_PRValue,
4524
0
                               /*BasePath=*/nullptr, CCK).get();
4525
0
    else if (ToType->isIntegralType(Context))
4526
0
      From = ImpCastExprToType(From, ToType, CK_FixedPointToIntegral,
4527
0
                               VK_PRValue,
4528
0
                               /*BasePath=*/nullptr, CCK).get();
4529
0
    else if (ToType->isBooleanType())
4530
0
      From = ImpCastExprToType(From, ToType, CK_FixedPointToBoolean,
4531
0
                               VK_PRValue,
4532
0
                               /*BasePath=*/nullptr, CCK).get();
4533
0
    else
4534
0
      From = ImpCastExprToType(From, ToType, CK_FixedPointCast,
4535
0
                               VK_PRValue,
4536
0
                               /*BasePath=*/nullptr, CCK).get();
4537
0
    break;
4538
4539
0
  case ICK_Compatible_Conversion:
4540
0
    From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(),
4541
0
                             /*BasePath=*/nullptr, CCK).get();
4542
0
    break;
4543
4544
0
  case ICK_Writeback_Conversion:
4545
0
  case ICK_Pointer_Conversion: {
4546
0
    if (SCS.IncompatibleObjC && Action != AA_Casting) {
4547
      // Diagnose incompatible Objective-C conversions
4548
0
      if (Action == AA_Initializing || Action == AA_Assigning)
4549
0
        Diag(From->getBeginLoc(),
4550
0
             diag::ext_typecheck_convert_incompatible_pointer)
4551
0
            << ToType << From->getType() << Action << From->getSourceRange()
4552
0
            << 0;
4553
0
      else
4554
0
        Diag(From->getBeginLoc(),
4555
0
             diag::ext_typecheck_convert_incompatible_pointer)
4556
0
            << From->getType() << ToType << Action << From->getSourceRange()
4557
0
            << 0;
4558
4559
0
      if (From->getType()->isObjCObjectPointerType() &&
4560
0
          ToType->isObjCObjectPointerType())
4561
0
        EmitRelatedResultTypeNote(From);
4562
0
    } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4563
0
               !CheckObjCARCUnavailableWeakConversion(ToType,
4564
0
                                                      From->getType())) {
4565
0
      if (Action == AA_Initializing)
4566
0
        Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
4567
0
      else
4568
0
        Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4569
0
            << (Action == AA_Casting) << From->getType() << ToType
4570
0
            << From->getSourceRange();
4571
0
    }
4572
4573
    // Defer address space conversion to the third conversion.
4574
0
    QualType FromPteeType = From->getType()->getPointeeType();
4575
0
    QualType ToPteeType = ToType->getPointeeType();
4576
0
    QualType NewToType = ToType;
4577
0
    if (!FromPteeType.isNull() && !ToPteeType.isNull() &&
4578
0
        FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {
4579
0
      NewToType = Context.removeAddrSpaceQualType(ToPteeType);
4580
0
      NewToType = Context.getAddrSpaceQualType(NewToType,
4581
0
                                               FromPteeType.getAddressSpace());
4582
0
      if (ToType->isObjCObjectPointerType())
4583
0
        NewToType = Context.getObjCObjectPointerType(NewToType);
4584
0
      else if (ToType->isBlockPointerType())
4585
0
        NewToType = Context.getBlockPointerType(NewToType);
4586
0
      else
4587
0
        NewToType = Context.getPointerType(NewToType);
4588
0
    }
4589
4590
0
    CastKind Kind;
4591
0
    CXXCastPath BasePath;
4592
0
    if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))
4593
0
      return ExprError();
4594
4595
    // Make sure we extend blocks if necessary.
4596
    // FIXME: doing this here is really ugly.
4597
0
    if (Kind == CK_BlockPointerToObjCPointerCast) {
4598
0
      ExprResult E = From;
4599
0
      (void) PrepareCastToObjCObjectPointer(E);
4600
0
      From = E.get();
4601
0
    }
4602
0
    if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4603
0
      CheckObjCConversion(SourceRange(), NewToType, From, CCK);
4604
0
    From = ImpCastExprToType(From, NewToType, Kind, VK_PRValue, &BasePath, CCK)
4605
0
               .get();
4606
0
    break;
4607
0
  }
4608
4609
0
  case ICK_Pointer_Member: {
4610
0
    CastKind Kind;
4611
0
    CXXCastPath BasePath;
4612
0
    if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
4613
0
      return ExprError();
4614
0
    if (CheckExceptionSpecCompatibility(From, ToType))
4615
0
      return ExprError();
4616
4617
    // We may not have been able to figure out what this member pointer resolved
4618
    // to up until this exact point.  Attempt to lock-in it's inheritance model.
4619
0
    if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4620
0
      (void)isCompleteType(From->getExprLoc(), From->getType());
4621
0
      (void)isCompleteType(From->getExprLoc(), ToType);
4622
0
    }
4623
4624
0
    From =
4625
0
        ImpCastExprToType(From, ToType, Kind, VK_PRValue, &BasePath, CCK).get();
4626
0
    break;
4627
0
  }
4628
4629
0
  case ICK_Boolean_Conversion:
4630
    // Perform half-to-boolean conversion via float.
4631
0
    if (From->getType()->isHalfType()) {
4632
0
      From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
4633
0
      FromType = Context.FloatTy;
4634
0
    }
4635
4636
0
    From = ImpCastExprToType(From, Context.BoolTy,
4637
0
                             ScalarTypeToBooleanCastKind(FromType), VK_PRValue,
4638
0
                             /*BasePath=*/nullptr, CCK)
4639
0
               .get();
4640
0
    break;
4641
4642
0
  case ICK_Derived_To_Base: {
4643
0
    CXXCastPath BasePath;
4644
0
    if (CheckDerivedToBaseConversion(
4645
0
            From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4646
0
            From->getSourceRange(), &BasePath, CStyle))
4647
0
      return ExprError();
4648
4649
0
    From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4650
0
                      CK_DerivedToBase, From->getValueKind(),
4651
0
                      &BasePath, CCK).get();
4652
0
    break;
4653
0
  }
4654
4655
0
  case ICK_Vector_Conversion:
4656
0
    From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4657
0
                             /*BasePath=*/nullptr, CCK)
4658
0
               .get();
4659
0
    break;
4660
4661
0
  case ICK_SVE_Vector_Conversion:
4662
0
  case ICK_RVV_Vector_Conversion:
4663
0
    From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4664
0
                             /*BasePath=*/nullptr, CCK)
4665
0
               .get();
4666
0
    break;
4667
4668
0
  case ICK_Vector_Splat: {
4669
    // Vector splat from any arithmetic type to a vector.
4670
0
    Expr *Elem = prepareVectorSplat(ToType, From).get();
4671
0
    From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,
4672
0
                             /*BasePath=*/nullptr, CCK)
4673
0
               .get();
4674
0
    break;
4675
0
  }
4676
4677
0
  case ICK_Complex_Real:
4678
    // Case 1.  x -> _Complex y
4679
0
    if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4680
0
      QualType ElType = ToComplex->getElementType();
4681
0
      bool isFloatingComplex = ElType->isRealFloatingType();
4682
4683
      // x -> y
4684
0
      if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4685
        // do nothing
4686
0
      } else if (From->getType()->isRealFloatingType()) {
4687
0
        From = ImpCastExprToType(From, ElType,
4688
0
                isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
4689
0
      } else {
4690
0
        assert(From->getType()->isIntegerType());
4691
0
        From = ImpCastExprToType(From, ElType,
4692
0
                isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
4693
0
      }
4694
      // y -> _Complex y
4695
0
      From = ImpCastExprToType(From, ToType,
4696
0
                   isFloatingComplex ? CK_FloatingRealToComplex
4697
0
                                     : CK_IntegralRealToComplex).get();
4698
4699
    // Case 2.  _Complex x -> y
4700
0
    } else {
4701
0
      auto *FromComplex = From->getType()->castAs<ComplexType>();
4702
0
      QualType ElType = FromComplex->getElementType();
4703
0
      bool isFloatingComplex = ElType->isRealFloatingType();
4704
4705
      // _Complex x -> x
4706
0
      From = ImpCastExprToType(From, ElType,
4707
0
                               isFloatingComplex ? CK_FloatingComplexToReal
4708
0
                                                 : CK_IntegralComplexToReal,
4709
0
                               VK_PRValue, /*BasePath=*/nullptr, CCK)
4710
0
                 .get();
4711
4712
      // x -> y
4713
0
      if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4714
        // do nothing
4715
0
      } else if (ToType->isRealFloatingType()) {
4716
0
        From = ImpCastExprToType(From, ToType,
4717
0
                                 isFloatingComplex ? CK_FloatingCast
4718
0
                                                   : CK_IntegralToFloating,
4719
0
                                 VK_PRValue, /*BasePath=*/nullptr, CCK)
4720
0
                   .get();
4721
0
      } else {
4722
0
        assert(ToType->isIntegerType());
4723
0
        From = ImpCastExprToType(From, ToType,
4724
0
                                 isFloatingComplex ? CK_FloatingToIntegral
4725
0
                                                   : CK_IntegralCast,
4726
0
                                 VK_PRValue, /*BasePath=*/nullptr, CCK)
4727
0
                   .get();
4728
0
      }
4729
0
    }
4730
0
    break;
4731
4732
0
  case ICK_Block_Pointer_Conversion: {
4733
0
    LangAS AddrSpaceL =
4734
0
        ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4735
0
    LangAS AddrSpaceR =
4736
0
        FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4737
0
    assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&
4738
0
           "Invalid cast");
4739
0
    CastKind Kind =
4740
0
        AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
4741
0
    From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
4742
0
                             VK_PRValue, /*BasePath=*/nullptr, CCK)
4743
0
               .get();
4744
0
    break;
4745
0
  }
4746
4747
0
  case ICK_TransparentUnionConversion: {
4748
0
    ExprResult FromRes = From;
4749
0
    Sema::AssignConvertType ConvTy =
4750
0
      CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4751
0
    if (FromRes.isInvalid())
4752
0
      return ExprError();
4753
0
    From = FromRes.get();
4754
0
    assert ((ConvTy == Sema::Compatible) &&
4755
0
            "Improper transparent union conversion");
4756
0
    (void)ConvTy;
4757
0
    break;
4758
0
  }
4759
4760
0
  case ICK_Zero_Event_Conversion:
4761
0
  case ICK_Zero_Queue_Conversion:
4762
0
    From = ImpCastExprToType(From, ToType,
4763
0
                             CK_ZeroToOCLOpaqueType,
4764
0
                             From->getValueKind()).get();
4765
0
    break;
4766
4767
0
  case ICK_Lvalue_To_Rvalue:
4768
0
  case ICK_Array_To_Pointer:
4769
0
  case ICK_Function_To_Pointer:
4770
0
  case ICK_Function_Conversion:
4771
0
  case ICK_Qualification:
4772
0
  case ICK_Num_Conversion_Kinds:
4773
0
  case ICK_C_Only_Conversion:
4774
0
  case ICK_Incompatible_Pointer_Conversion:
4775
0
    llvm_unreachable("Improper second standard conversion");
4776
0
  }
4777
4778
0
  switch (SCS.Third) {
4779
0
  case ICK_Identity:
4780
    // Nothing to do.
4781
0
    break;
4782
4783
0
  case ICK_Function_Conversion:
4784
    // If both sides are functions (or pointers/references to them), there could
4785
    // be incompatible exception declarations.
4786
0
    if (CheckExceptionSpecCompatibility(From, ToType))
4787
0
      return ExprError();
4788
4789
0
    From = ImpCastExprToType(From, ToType, CK_NoOp, VK_PRValue,
4790
0
                             /*BasePath=*/nullptr, CCK)
4791
0
               .get();
4792
0
    break;
4793
4794
0
  case ICK_Qualification: {
4795
0
    ExprValueKind VK = From->getValueKind();
4796
0
    CastKind CK = CK_NoOp;
4797
4798
0
    if (ToType->isReferenceType() &&
4799
0
        ToType->getPointeeType().getAddressSpace() !=
4800
0
            From->getType().getAddressSpace())
4801
0
      CK = CK_AddressSpaceConversion;
4802
4803
0
    if (ToType->isPointerType() &&
4804
0
        ToType->getPointeeType().getAddressSpace() !=
4805
0
            From->getType()->getPointeeType().getAddressSpace())
4806
0
      CK = CK_AddressSpaceConversion;
4807
4808
0
    if (!isCast(CCK) &&
4809
0
        !ToType->getPointeeType().getQualifiers().hasUnaligned() &&
4810
0
        From->getType()->getPointeeType().getQualifiers().hasUnaligned()) {
4811
0
      Diag(From->getBeginLoc(), diag::warn_imp_cast_drops_unaligned)
4812
0
          << InitialFromType << ToType;
4813
0
    }
4814
4815
0
    From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4816
0
                             /*BasePath=*/nullptr, CCK)
4817
0
               .get();
4818
4819
0
    if (SCS.DeprecatedStringLiteralToCharPtr &&
4820
0
        !getLangOpts().WritableStrings) {
4821
0
      Diag(From->getBeginLoc(),
4822
0
           getLangOpts().CPlusPlus11
4823
0
               ? diag::ext_deprecated_string_literal_conversion
4824
0
               : diag::warn_deprecated_string_literal_conversion)
4825
0
          << ToType.getNonReferenceType();
4826
0
    }
4827
4828
0
    break;
4829
0
  }
4830
4831
0
  default:
4832
0
    llvm_unreachable("Improper third standard conversion");
4833
0
  }
4834
4835
  // If this conversion sequence involved a scalar -> atomic conversion, perform
4836
  // that conversion now.
4837
0
  if (!ToAtomicType.isNull()) {
4838
0
    assert(Context.hasSameType(
4839
0
        ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4840
0
    From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4841
0
                             VK_PRValue, nullptr, CCK)
4842
0
               .get();
4843
0
  }
4844
4845
  // Materialize a temporary if we're implicitly converting to a reference
4846
  // type. This is not required by the C++ rules but is necessary to maintain
4847
  // AST invariants.
4848
0
  if (ToType->isReferenceType() && From->isPRValue()) {
4849
0
    ExprResult Res = TemporaryMaterializationConversion(From);
4850
0
    if (Res.isInvalid())
4851
0
      return ExprError();
4852
0
    From = Res.get();
4853
0
  }
4854
4855
  // If this conversion sequence succeeded and involved implicitly converting a
4856
  // _Nullable type to a _Nonnull one, complain.
4857
0
  if (!isCast(CCK))
4858
0
    diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4859
0
                                        From->getBeginLoc());
4860
4861
0
  return From;
4862
0
}
4863
4864
/// Check the completeness of a type in a unary type trait.
4865
///
4866
/// If the particular type trait requires a complete type, tries to complete
4867
/// it. If completing the type fails, a diagnostic is emitted and false
4868
/// returned. If completing the type succeeds or no completion was required,
4869
/// returns true.
4870
static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
4871
                                                SourceLocation Loc,
4872
0
                                                QualType ArgTy) {
4873
  // C++0x [meta.unary.prop]p3:
4874
  //   For all of the class templates X declared in this Clause, instantiating
4875
  //   that template with a template argument that is a class template
4876
  //   specialization may result in the implicit instantiation of the template
4877
  //   argument if and only if the semantics of X require that the argument
4878
  //   must be a complete type.
4879
  // We apply this rule to all the type trait expressions used to implement
4880
  // these class templates. We also try to follow any GCC documented behavior
4881
  // in these expressions to ensure portability of standard libraries.
4882
0
  switch (UTT) {
4883
0
  default: llvm_unreachable("not a UTT");
4884
    // is_complete_type somewhat obviously cannot require a complete type.
4885
0
  case UTT_IsCompleteType:
4886
    // Fall-through
4887
4888
    // These traits are modeled on the type predicates in C++0x
4889
    // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4890
    // requiring a complete type, as whether or not they return true cannot be
4891
    // impacted by the completeness of the type.
4892
0
  case UTT_IsVoid:
4893
0
  case UTT_IsIntegral:
4894
0
  case UTT_IsFloatingPoint:
4895
0
  case UTT_IsArray:
4896
0
  case UTT_IsBoundedArray:
4897
0
  case UTT_IsPointer:
4898
0
  case UTT_IsNullPointer:
4899
0
  case UTT_IsReferenceable:
4900
0
  case UTT_IsLvalueReference:
4901
0
  case UTT_IsRvalueReference:
4902
0
  case UTT_IsMemberFunctionPointer:
4903
0
  case UTT_IsMemberObjectPointer:
4904
0
  case UTT_IsEnum:
4905
0
  case UTT_IsScopedEnum:
4906
0
  case UTT_IsUnion:
4907
0
  case UTT_IsClass:
4908
0
  case UTT_IsFunction:
4909
0
  case UTT_IsReference:
4910
0
  case UTT_IsArithmetic:
4911
0
  case UTT_IsFundamental:
4912
0
  case UTT_IsObject:
4913
0
  case UTT_IsScalar:
4914
0
  case UTT_IsCompound:
4915
0
  case UTT_IsMemberPointer:
4916
    // Fall-through
4917
4918
    // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4919
    // which requires some of its traits to have the complete type. However,
4920
    // the completeness of the type cannot impact these traits' semantics, and
4921
    // so they don't require it. This matches the comments on these traits in
4922
    // Table 49.
4923
0
  case UTT_IsConst:
4924
0
  case UTT_IsVolatile:
4925
0
  case UTT_IsSigned:
4926
0
  case UTT_IsUnboundedArray:
4927
0
  case UTT_IsUnsigned:
4928
4929
  // This type trait always returns false, checking the type is moot.
4930
0
  case UTT_IsInterfaceClass:
4931
0
    return true;
4932
4933
  // C++14 [meta.unary.prop]:
4934
  //   If T is a non-union class type, T shall be a complete type.
4935
0
  case UTT_IsEmpty:
4936
0
  case UTT_IsPolymorphic:
4937
0
  case UTT_IsAbstract:
4938
0
    if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4939
0
      if (!RD->isUnion())
4940
0
        return !S.RequireCompleteType(
4941
0
            Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4942
0
    return true;
4943
4944
  // C++14 [meta.unary.prop]:
4945
  //   If T is a class type, T shall be a complete type.
4946
0
  case UTT_IsFinal:
4947
0
  case UTT_IsSealed:
4948
0
    if (ArgTy->getAsCXXRecordDecl())
4949
0
      return !S.RequireCompleteType(
4950
0
          Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4951
0
    return true;
4952
4953
  // LWG3823: T shall be an array type, a complete type, or cv void.
4954
0
  case UTT_IsAggregate:
4955
0
    if (ArgTy->isArrayType() || ArgTy->isVoidType())
4956
0
      return true;
4957
4958
0
    return !S.RequireCompleteType(
4959
0
        Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4960
4961
  // C++1z [meta.unary.prop]:
4962
  //   remove_all_extents_t<T> shall be a complete type or cv void.
4963
0
  case UTT_IsTrivial:
4964
0
  case UTT_IsTriviallyCopyable:
4965
0
  case UTT_IsStandardLayout:
4966
0
  case UTT_IsPOD:
4967
0
  case UTT_IsLiteral:
4968
  // By analogy, is_trivially_relocatable and is_trivially_equality_comparable
4969
  // impose the same constraints.
4970
0
  case UTT_IsTriviallyRelocatable:
4971
0
  case UTT_IsTriviallyEqualityComparable:
4972
0
  case UTT_CanPassInRegs:
4973
  // Per the GCC type traits documentation, T shall be a complete type, cv void,
4974
  // or an array of unknown bound. But GCC actually imposes the same constraints
4975
  // as above.
4976
0
  case UTT_HasNothrowAssign:
4977
0
  case UTT_HasNothrowMoveAssign:
4978
0
  case UTT_HasNothrowConstructor:
4979
0
  case UTT_HasNothrowCopy:
4980
0
  case UTT_HasTrivialAssign:
4981
0
  case UTT_HasTrivialMoveAssign:
4982
0
  case UTT_HasTrivialDefaultConstructor:
4983
0
  case UTT_HasTrivialMoveConstructor:
4984
0
  case UTT_HasTrivialCopy:
4985
0
  case UTT_HasTrivialDestructor:
4986
0
  case UTT_HasVirtualDestructor:
4987
0
    ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4988
0
    [[fallthrough]];
4989
4990
  // C++1z [meta.unary.prop]:
4991
  //   T shall be a complete type, cv void, or an array of unknown bound.
4992
0
  case UTT_IsDestructible:
4993
0
  case UTT_IsNothrowDestructible:
4994
0
  case UTT_IsTriviallyDestructible:
4995
0
  case UTT_HasUniqueObjectRepresentations:
4996
0
    if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
4997
0
      return true;
4998
4999
0
    return !S.RequireCompleteType(
5000
0
        Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5001
0
  }
5002
0
}
5003
5004
static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
5005
                               Sema &Self, SourceLocation KeyLoc, ASTContext &C,
5006
                               bool (CXXRecordDecl::*HasTrivial)() const,
5007
                               bool (CXXRecordDecl::*HasNonTrivial)() const,
5008
                               bool (CXXMethodDecl::*IsDesiredOp)() const)
5009
0
{
5010
0
  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5011
0
  if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
5012
0
    return true;
5013
5014
0
  DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
5015
0
  DeclarationNameInfo NameInfo(Name, KeyLoc);
5016
0
  LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
5017
0
  if (Self.LookupQualifiedName(Res, RD)) {
5018
0
    bool FoundOperator = false;
5019
0
    Res.suppressDiagnostics();
5020
0
    for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
5021
0
         Op != OpEnd; ++Op) {
5022
0
      if (isa<FunctionTemplateDecl>(*Op))
5023
0
        continue;
5024
5025
0
      CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
5026
0
      if((Operator->*IsDesiredOp)()) {
5027
0
        FoundOperator = true;
5028
0
        auto *CPT = Operator->getType()->castAs<FunctionProtoType>();
5029
0
        CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5030
0
        if (!CPT || !CPT->isNothrow())
5031
0
          return false;
5032
0
      }
5033
0
    }
5034
0
    return FoundOperator;
5035
0
  }
5036
0
  return false;
5037
0
}
5038
5039
static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
5040
0
                                   SourceLocation KeyLoc, QualType T) {
5041
0
  assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
5042
5043
0
  ASTContext &C = Self.Context;
5044
0
  switch(UTT) {
5045
0
  default: llvm_unreachable("not a UTT");
5046
    // Type trait expressions corresponding to the primary type category
5047
    // predicates in C++0x [meta.unary.cat].
5048
0
  case UTT_IsVoid:
5049
0
    return T->isVoidType();
5050
0
  case UTT_IsIntegral:
5051
0
    return T->isIntegralType(C);
5052
0
  case UTT_IsFloatingPoint:
5053
0
    return T->isFloatingType();
5054
0
  case UTT_IsArray:
5055
0
    return T->isArrayType();
5056
0
  case UTT_IsBoundedArray:
5057
0
    if (!T->isVariableArrayType()) {
5058
0
      return T->isArrayType() && !T->isIncompleteArrayType();
5059
0
    }
5060
5061
0
    Self.Diag(KeyLoc, diag::err_vla_unsupported)
5062
0
        << 1 << tok::kw___is_bounded_array;
5063
0
    return false;
5064
0
  case UTT_IsUnboundedArray:
5065
0
    if (!T->isVariableArrayType()) {
5066
0
      return T->isIncompleteArrayType();
5067
0
    }
5068
5069
0
    Self.Diag(KeyLoc, diag::err_vla_unsupported)
5070
0
        << 1 << tok::kw___is_unbounded_array;
5071
0
    return false;
5072
0
  case UTT_IsPointer:
5073
0
    return T->isAnyPointerType();
5074
0
  case UTT_IsNullPointer:
5075
0
    return T->isNullPtrType();
5076
0
  case UTT_IsLvalueReference:
5077
0
    return T->isLValueReferenceType();
5078
0
  case UTT_IsRvalueReference:
5079
0
    return T->isRValueReferenceType();
5080
0
  case UTT_IsMemberFunctionPointer:
5081
0
    return T->isMemberFunctionPointerType();
5082
0
  case UTT_IsMemberObjectPointer:
5083
0
    return T->isMemberDataPointerType();
5084
0
  case UTT_IsEnum:
5085
0
    return T->isEnumeralType();
5086
0
  case UTT_IsScopedEnum:
5087
0
    return T->isScopedEnumeralType();
5088
0
  case UTT_IsUnion:
5089
0
    return T->isUnionType();
5090
0
  case UTT_IsClass:
5091
0
    return T->isClassType() || T->isStructureType() || T->isInterfaceType();
5092
0
  case UTT_IsFunction:
5093
0
    return T->isFunctionType();
5094
5095
    // Type trait expressions which correspond to the convenient composition
5096
    // predicates in C++0x [meta.unary.comp].
5097
0
  case UTT_IsReference:
5098
0
    return T->isReferenceType();
5099
0
  case UTT_IsArithmetic:
5100
0
    return T->isArithmeticType() && !T->isEnumeralType();
5101
0
  case UTT_IsFundamental:
5102
0
    return T->isFundamentalType();
5103
0
  case UTT_IsObject:
5104
0
    return T->isObjectType();
5105
0
  case UTT_IsScalar:
5106
    // Note: semantic analysis depends on Objective-C lifetime types to be
5107
    // considered scalar types. However, such types do not actually behave
5108
    // like scalar types at run time (since they may require retain/release
5109
    // operations), so we report them as non-scalar.
5110
0
    if (T->isObjCLifetimeType()) {
5111
0
      switch (T.getObjCLifetime()) {
5112
0
      case Qualifiers::OCL_None:
5113
0
      case Qualifiers::OCL_ExplicitNone:
5114
0
        return true;
5115
5116
0
      case Qualifiers::OCL_Strong:
5117
0
      case Qualifiers::OCL_Weak:
5118
0
      case Qualifiers::OCL_Autoreleasing:
5119
0
        return false;
5120
0
      }
5121
0
    }
5122
5123
0
    return T->isScalarType();
5124
0
  case UTT_IsCompound:
5125
0
    return T->isCompoundType();
5126
0
  case UTT_IsMemberPointer:
5127
0
    return T->isMemberPointerType();
5128
5129
    // Type trait expressions which correspond to the type property predicates
5130
    // in C++0x [meta.unary.prop].
5131
0
  case UTT_IsConst:
5132
0
    return T.isConstQualified();
5133
0
  case UTT_IsVolatile:
5134
0
    return T.isVolatileQualified();
5135
0
  case UTT_IsTrivial:
5136
0
    return T.isTrivialType(C);
5137
0
  case UTT_IsTriviallyCopyable:
5138
0
    return T.isTriviallyCopyableType(C);
5139
0
  case UTT_IsStandardLayout:
5140
0
    return T->isStandardLayoutType();
5141
0
  case UTT_IsPOD:
5142
0
    return T.isPODType(C);
5143
0
  case UTT_IsLiteral:
5144
0
    return T->isLiteralType(C);
5145
0
  case UTT_IsEmpty:
5146
0
    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5147
0
      return !RD->isUnion() && RD->isEmpty();
5148
0
    return false;
5149
0
  case UTT_IsPolymorphic:
5150
0
    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5151
0
      return !RD->isUnion() && RD->isPolymorphic();
5152
0
    return false;
5153
0
  case UTT_IsAbstract:
5154
0
    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5155
0
      return !RD->isUnion() && RD->isAbstract();
5156
0
    return false;
5157
0
  case UTT_IsAggregate:
5158
    // Report vector extensions and complex types as aggregates because they
5159
    // support aggregate initialization. GCC mirrors this behavior for vectors
5160
    // but not _Complex.
5161
0
    return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
5162
0
           T->isAnyComplexType();
5163
  // __is_interface_class only returns true when CL is invoked in /CLR mode and
5164
  // even then only when it is used with the 'interface struct ...' syntax
5165
  // Clang doesn't support /CLR which makes this type trait moot.
5166
0
  case UTT_IsInterfaceClass:
5167
0
    return false;
5168
0
  case UTT_IsFinal:
5169
0
  case UTT_IsSealed:
5170
0
    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5171
0
      return RD->hasAttr<FinalAttr>();
5172
0
    return false;
5173
0
  case UTT_IsSigned:
5174
    // Enum types should always return false.
5175
    // Floating points should always return true.
5176
0
    return T->isFloatingType() ||
5177
0
           (T->isSignedIntegerType() && !T->isEnumeralType());
5178
0
  case UTT_IsUnsigned:
5179
    // Enum types should always return false.
5180
0
    return T->isUnsignedIntegerType() && !T->isEnumeralType();
5181
5182
    // Type trait expressions which query classes regarding their construction,
5183
    // destruction, and copying. Rather than being based directly on the
5184
    // related type predicates in the standard, they are specified by both
5185
    // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
5186
    // specifications.
5187
    //
5188
    //   1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
5189
    //   2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5190
    //
5191
    // Note that these builtins do not behave as documented in g++: if a class
5192
    // has both a trivial and a non-trivial special member of a particular kind,
5193
    // they return false! For now, we emulate this behavior.
5194
    // FIXME: This appears to be a g++ bug: more complex cases reveal that it
5195
    // does not correctly compute triviality in the presence of multiple special
5196
    // members of the same kind. Revisit this once the g++ bug is fixed.
5197
0
  case UTT_HasTrivialDefaultConstructor:
5198
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5199
    //   If __is_pod (type) is true then the trait is true, else if type is
5200
    //   a cv class or union type (or array thereof) with a trivial default
5201
    //   constructor ([class.ctor]) then the trait is true, else it is false.
5202
0
    if (T.isPODType(C))
5203
0
      return true;
5204
0
    if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5205
0
      return RD->hasTrivialDefaultConstructor() &&
5206
0
             !RD->hasNonTrivialDefaultConstructor();
5207
0
    return false;
5208
0
  case UTT_HasTrivialMoveConstructor:
5209
    //  This trait is implemented by MSVC 2012 and needed to parse the
5210
    //  standard library headers. Specifically this is used as the logic
5211
    //  behind std::is_trivially_move_constructible (20.9.4.3).
5212
0
    if (T.isPODType(C))
5213
0
      return true;
5214
0
    if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5215
0
      return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
5216
0
    return false;
5217
0
  case UTT_HasTrivialCopy:
5218
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5219
    //   If __is_pod (type) is true or type is a reference type then
5220
    //   the trait is true, else if type is a cv class or union type
5221
    //   with a trivial copy constructor ([class.copy]) then the trait
5222
    //   is true, else it is false.
5223
0
    if (T.isPODType(C) || T->isReferenceType())
5224
0
      return true;
5225
0
    if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5226
0
      return RD->hasTrivialCopyConstructor() &&
5227
0
             !RD->hasNonTrivialCopyConstructor();
5228
0
    return false;
5229
0
  case UTT_HasTrivialMoveAssign:
5230
    //  This trait is implemented by MSVC 2012 and needed to parse the
5231
    //  standard library headers. Specifically it is used as the logic
5232
    //  behind std::is_trivially_move_assignable (20.9.4.3)
5233
0
    if (T.isPODType(C))
5234
0
      return true;
5235
0
    if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5236
0
      return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
5237
0
    return false;
5238
0
  case UTT_HasTrivialAssign:
5239
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5240
    //   If type is const qualified or is a reference type then the
5241
    //   trait is false. Otherwise if __is_pod (type) is true then the
5242
    //   trait is true, else if type is a cv class or union type with
5243
    //   a trivial copy assignment ([class.copy]) then the trait is
5244
    //   true, else it is false.
5245
    // Note: the const and reference restrictions are interesting,
5246
    // given that const and reference members don't prevent a class
5247
    // from having a trivial copy assignment operator (but do cause
5248
    // errors if the copy assignment operator is actually used, q.v.
5249
    // [class.copy]p12).
5250
5251
0
    if (T.isConstQualified())
5252
0
      return false;
5253
0
    if (T.isPODType(C))
5254
0
      return true;
5255
0
    if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5256
0
      return RD->hasTrivialCopyAssignment() &&
5257
0
             !RD->hasNonTrivialCopyAssignment();
5258
0
    return false;
5259
0
  case UTT_IsDestructible:
5260
0
  case UTT_IsTriviallyDestructible:
5261
0
  case UTT_IsNothrowDestructible:
5262
    // C++14 [meta.unary.prop]:
5263
    //   For reference types, is_destructible<T>::value is true.
5264
0
    if (T->isReferenceType())
5265
0
      return true;
5266
5267
    // Objective-C++ ARC: autorelease types don't require destruction.
5268
0
    if (T->isObjCLifetimeType() &&
5269
0
        T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
5270
0
      return true;
5271
5272
    // C++14 [meta.unary.prop]:
5273
    //   For incomplete types and function types, is_destructible<T>::value is
5274
    //   false.
5275
0
    if (T->isIncompleteType() || T->isFunctionType())
5276
0
      return false;
5277
5278
    // A type that requires destruction (via a non-trivial destructor or ARC
5279
    // lifetime semantics) is not trivially-destructible.
5280
0
    if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
5281
0
      return false;
5282
5283
    // C++14 [meta.unary.prop]:
5284
    //   For object types and given U equal to remove_all_extents_t<T>, if the
5285
    //   expression std::declval<U&>().~U() is well-formed when treated as an
5286
    //   unevaluated operand (Clause 5), then is_destructible<T>::value is true
5287
0
    if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5288
0
      CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
5289
0
      if (!Destructor)
5290
0
        return false;
5291
      //  C++14 [dcl.fct.def.delete]p2:
5292
      //    A program that refers to a deleted function implicitly or
5293
      //    explicitly, other than to declare it, is ill-formed.
5294
0
      if (Destructor->isDeleted())
5295
0
        return false;
5296
0
      if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
5297
0
        return false;
5298
0
      if (UTT == UTT_IsNothrowDestructible) {
5299
0
        auto *CPT = Destructor->getType()->castAs<FunctionProtoType>();
5300
0
        CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5301
0
        if (!CPT || !CPT->isNothrow())
5302
0
          return false;
5303
0
      }
5304
0
    }
5305
0
    return true;
5306
5307
0
  case UTT_HasTrivialDestructor:
5308
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5309
    //   If __is_pod (type) is true or type is a reference type
5310
    //   then the trait is true, else if type is a cv class or union
5311
    //   type (or array thereof) with a trivial destructor
5312
    //   ([class.dtor]) then the trait is true, else it is
5313
    //   false.
5314
0
    if (T.isPODType(C) || T->isReferenceType())
5315
0
      return true;
5316
5317
    // Objective-C++ ARC: autorelease types don't require destruction.
5318
0
    if (T->isObjCLifetimeType() &&
5319
0
        T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
5320
0
      return true;
5321
5322
0
    if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5323
0
      return RD->hasTrivialDestructor();
5324
0
    return false;
5325
  // TODO: Propagate nothrowness for implicitly declared special members.
5326
0
  case UTT_HasNothrowAssign:
5327
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5328
    //   If type is const qualified or is a reference type then the
5329
    //   trait is false. Otherwise if __has_trivial_assign (type)
5330
    //   is true then the trait is true, else if type is a cv class
5331
    //   or union type with copy assignment operators that are known
5332
    //   not to throw an exception then the trait is true, else it is
5333
    //   false.
5334
0
    if (C.getBaseElementType(T).isConstQualified())
5335
0
      return false;
5336
0
    if (T->isReferenceType())
5337
0
      return false;
5338
0
    if (T.isPODType(C) || T->isObjCLifetimeType())
5339
0
      return true;
5340
5341
0
    if (const RecordType *RT = T->getAs<RecordType>())
5342
0
      return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
5343
0
                                &CXXRecordDecl::hasTrivialCopyAssignment,
5344
0
                                &CXXRecordDecl::hasNonTrivialCopyAssignment,
5345
0
                                &CXXMethodDecl::isCopyAssignmentOperator);
5346
0
    return false;
5347
0
  case UTT_HasNothrowMoveAssign:
5348
    //  This trait is implemented by MSVC 2012 and needed to parse the
5349
    //  standard library headers. Specifically this is used as the logic
5350
    //  behind std::is_nothrow_move_assignable (20.9.4.3).
5351
0
    if (T.isPODType(C))
5352
0
      return true;
5353
5354
0
    if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
5355
0
      return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
5356
0
                                &CXXRecordDecl::hasTrivialMoveAssignment,
5357
0
                                &CXXRecordDecl::hasNonTrivialMoveAssignment,
5358
0
                                &CXXMethodDecl::isMoveAssignmentOperator);
5359
0
    return false;
5360
0
  case UTT_HasNothrowCopy:
5361
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5362
    //   If __has_trivial_copy (type) is true then the trait is true, else
5363
    //   if type is a cv class or union type with copy constructors that are
5364
    //   known not to throw an exception then the trait is true, else it is
5365
    //   false.
5366
0
    if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
5367
0
      return true;
5368
0
    if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
5369
0
      if (RD->hasTrivialCopyConstructor() &&
5370
0
          !RD->hasNonTrivialCopyConstructor())
5371
0
        return true;
5372
5373
0
      bool FoundConstructor = false;
5374
0
      unsigned FoundTQs;
5375
0
      for (const auto *ND : Self.LookupConstructors(RD)) {
5376
        // A template constructor is never a copy constructor.
5377
        // FIXME: However, it may actually be selected at the actual overload
5378
        // resolution point.
5379
0
        if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5380
0
          continue;
5381
        // UsingDecl itself is not a constructor
5382
0
        if (isa<UsingDecl>(ND))
5383
0
          continue;
5384
0
        auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5385
0
        if (Constructor->isCopyConstructor(FoundTQs)) {
5386
0
          FoundConstructor = true;
5387
0
          auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5388
0
          CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5389
0
          if (!CPT)
5390
0
            return false;
5391
          // TODO: check whether evaluating default arguments can throw.
5392
          // For now, we'll be conservative and assume that they can throw.
5393
0
          if (!CPT->isNothrow() || CPT->getNumParams() > 1)
5394
0
            return false;
5395
0
        }
5396
0
      }
5397
5398
0
      return FoundConstructor;
5399
0
    }
5400
0
    return false;
5401
0
  case UTT_HasNothrowConstructor:
5402
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5403
    //   If __has_trivial_constructor (type) is true then the trait is
5404
    //   true, else if type is a cv class or union type (or array
5405
    //   thereof) with a default constructor that is known not to
5406
    //   throw an exception then the trait is true, else it is false.
5407
0
    if (T.isPODType(C) || T->isObjCLifetimeType())
5408
0
      return true;
5409
0
    if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5410
0
      if (RD->hasTrivialDefaultConstructor() &&
5411
0
          !RD->hasNonTrivialDefaultConstructor())
5412
0
        return true;
5413
5414
0
      bool FoundConstructor = false;
5415
0
      for (const auto *ND : Self.LookupConstructors(RD)) {
5416
        // FIXME: In C++0x, a constructor template can be a default constructor.
5417
0
        if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5418
0
          continue;
5419
        // UsingDecl itself is not a constructor
5420
0
        if (isa<UsingDecl>(ND))
5421
0
          continue;
5422
0
        auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5423
0
        if (Constructor->isDefaultConstructor()) {
5424
0
          FoundConstructor = true;
5425
0
          auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5426
0
          CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5427
0
          if (!CPT)
5428
0
            return false;
5429
          // FIXME: check whether evaluating default arguments can throw.
5430
          // For now, we'll be conservative and assume that they can throw.
5431
0
          if (!CPT->isNothrow() || CPT->getNumParams() > 0)
5432
0
            return false;
5433
0
        }
5434
0
      }
5435
0
      return FoundConstructor;
5436
0
    }
5437
0
    return false;
5438
0
  case UTT_HasVirtualDestructor:
5439
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5440
    //   If type is a class type with a virtual destructor ([class.dtor])
5441
    //   then the trait is true, else it is false.
5442
0
    if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5443
0
      if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
5444
0
        return Destructor->isVirtual();
5445
0
    return false;
5446
5447
    // These type trait expressions are modeled on the specifications for the
5448
    // Embarcadero C++0x type trait functions:
5449
    //   http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5450
0
  case UTT_IsCompleteType:
5451
    // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
5452
    //   Returns True if and only if T is a complete type at the point of the
5453
    //   function call.
5454
0
    return !T->isIncompleteType();
5455
0
  case UTT_HasUniqueObjectRepresentations:
5456
0
    return C.hasUniqueObjectRepresentations(T);
5457
0
  case UTT_IsTriviallyRelocatable:
5458
0
    return T.isTriviallyRelocatableType(C);
5459
0
  case UTT_IsReferenceable:
5460
0
    return T.isReferenceable();
5461
0
  case UTT_CanPassInRegs:
5462
0
    if (CXXRecordDecl *RD = T->getAsCXXRecordDecl(); RD && !T.hasQualifiers())
5463
0
      return RD->canPassInRegisters();
5464
0
    Self.Diag(KeyLoc, diag::err_builtin_pass_in_regs_non_class) << T;
5465
0
    return false;
5466
0
  case UTT_IsTriviallyEqualityComparable:
5467
0
    return T.isTriviallyEqualityComparableType(C);
5468
0
  }
5469
0
}
5470
5471
static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5472
                                    QualType RhsT, SourceLocation KeyLoc);
5473
5474
static bool EvaluateBooleanTypeTrait(Sema &S, TypeTrait Kind,
5475
                                     SourceLocation KWLoc,
5476
                                     ArrayRef<TypeSourceInfo *> Args,
5477
                                     SourceLocation RParenLoc,
5478
0
                                     bool IsDependent) {
5479
0
  if (IsDependent)
5480
0
    return false;
5481
5482
0
  if (Kind <= UTT_Last)
5483
0
    return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
5484
5485
  // Evaluate ReferenceBindsToTemporary and ReferenceConstructsFromTemporary
5486
  // alongside the IsConstructible traits to avoid duplication.
5487
0
  if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary && Kind != BTT_ReferenceConstructsFromTemporary)
5488
0
    return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
5489
0
                                   Args[1]->getType(), RParenLoc);
5490
5491
0
  switch (Kind) {
5492
0
  case clang::BTT_ReferenceBindsToTemporary:
5493
0
  case clang::BTT_ReferenceConstructsFromTemporary:
5494
0
  case clang::TT_IsConstructible:
5495
0
  case clang::TT_IsNothrowConstructible:
5496
0
  case clang::TT_IsTriviallyConstructible: {
5497
    // C++11 [meta.unary.prop]:
5498
    //   is_trivially_constructible is defined as:
5499
    //
5500
    //     is_constructible<T, Args...>::value is true and the variable
5501
    //     definition for is_constructible, as defined below, is known to call
5502
    //     no operation that is not trivial.
5503
    //
5504
    //   The predicate condition for a template specialization
5505
    //   is_constructible<T, Args...> shall be satisfied if and only if the
5506
    //   following variable definition would be well-formed for some invented
5507
    //   variable t:
5508
    //
5509
    //     T t(create<Args>()...);
5510
0
    assert(!Args.empty());
5511
5512
    // Precondition: T and all types in the parameter pack Args shall be
5513
    // complete types, (possibly cv-qualified) void, or arrays of
5514
    // unknown bound.
5515
0
    for (const auto *TSI : Args) {
5516
0
      QualType ArgTy = TSI->getType();
5517
0
      if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
5518
0
        continue;
5519
5520
0
      if (S.RequireCompleteType(KWLoc, ArgTy,
5521
0
          diag::err_incomplete_type_used_in_type_trait_expr))
5522
0
        return false;
5523
0
    }
5524
5525
    // Make sure the first argument is not incomplete nor a function type.
5526
0
    QualType T = Args[0]->getType();
5527
0
    if (T->isIncompleteType() || T->isFunctionType())
5528
0
      return false;
5529
5530
    // Make sure the first argument is not an abstract type.
5531
0
    CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5532
0
    if (RD && RD->isAbstract())
5533
0
      return false;
5534
5535
0
    llvm::BumpPtrAllocator OpaqueExprAllocator;
5536
0
    SmallVector<Expr *, 2> ArgExprs;
5537
0
    ArgExprs.reserve(Args.size() - 1);
5538
0
    for (unsigned I = 1, N = Args.size(); I != N; ++I) {
5539
0
      QualType ArgTy = Args[I]->getType();
5540
0
      if (ArgTy->isObjectType() || ArgTy->isFunctionType())
5541
0
        ArgTy = S.Context.getRValueReferenceType(ArgTy);
5542
0
      ArgExprs.push_back(
5543
0
          new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>())
5544
0
              OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
5545
0
                              ArgTy.getNonLValueExprType(S.Context),
5546
0
                              Expr::getValueKindForType(ArgTy)));
5547
0
    }
5548
5549
    // Perform the initialization in an unevaluated context within a SFINAE
5550
    // trap at translation unit scope.
5551
0
    EnterExpressionEvaluationContext Unevaluated(
5552
0
        S, Sema::ExpressionEvaluationContext::Unevaluated);
5553
0
    Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
5554
0
    Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
5555
0
    InitializedEntity To(
5556
0
        InitializedEntity::InitializeTemporary(S.Context, Args[0]));
5557
0
    InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
5558
0
                                                                 RParenLoc));
5559
0
    InitializationSequence Init(S, To, InitKind, ArgExprs);
5560
0
    if (Init.Failed())
5561
0
      return false;
5562
5563
0
    ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
5564
0
    if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5565
0
      return false;
5566
5567
0
    if (Kind == clang::TT_IsConstructible)
5568
0
      return true;
5569
5570
0
    if (Kind == clang::BTT_ReferenceBindsToTemporary || Kind == clang::BTT_ReferenceConstructsFromTemporary) {
5571
0
      if (!T->isReferenceType())
5572
0
        return false;
5573
5574
0
      if (!Init.isDirectReferenceBinding())
5575
0
        return true;
5576
5577
0
      if (Kind == clang::BTT_ReferenceBindsToTemporary)
5578
0
        return false;
5579
5580
0
      QualType U = Args[1]->getType();
5581
0
      if (U->isReferenceType())
5582
0
        return false;
5583
5584
0
      QualType TPtr = S.Context.getPointerType(S.BuiltinRemoveReference(T, UnaryTransformType::RemoveCVRef, {}));
5585
0
      QualType UPtr = S.Context.getPointerType(S.BuiltinRemoveReference(U, UnaryTransformType::RemoveCVRef, {}));
5586
0
      return EvaluateBinaryTypeTrait(S, TypeTrait::BTT_IsConvertibleTo, UPtr, TPtr, RParenLoc);
5587
0
    }
5588
5589
0
    if (Kind == clang::TT_IsNothrowConstructible)
5590
0
      return S.canThrow(Result.get()) == CT_Cannot;
5591
5592
0
    if (Kind == clang::TT_IsTriviallyConstructible) {
5593
      // Under Objective-C ARC and Weak, if the destination has non-trivial
5594
      // Objective-C lifetime, this is a non-trivial construction.
5595
0
      if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
5596
0
        return false;
5597
5598
      // The initialization succeeded; now make sure there are no non-trivial
5599
      // calls.
5600
0
      return !Result.get()->hasNonTrivialCall(S.Context);
5601
0
    }
5602
5603
0
    llvm_unreachable("unhandled type trait");
5604
0
    return false;
5605
0
  }
5606
0
    default: llvm_unreachable("not a TT");
5607
0
  }
5608
5609
0
  return false;
5610
0
}
5611
5612
namespace {
5613
void DiagnoseBuiltinDeprecation(Sema& S, TypeTrait Kind,
5614
0
                                SourceLocation KWLoc) {
5615
0
  TypeTrait Replacement;
5616
0
  switch (Kind) {
5617
0
    case UTT_HasNothrowAssign:
5618
0
    case UTT_HasNothrowMoveAssign:
5619
0
      Replacement = BTT_IsNothrowAssignable;
5620
0
      break;
5621
0
    case UTT_HasNothrowCopy:
5622
0
    case UTT_HasNothrowConstructor:
5623
0
      Replacement = TT_IsNothrowConstructible;
5624
0
      break;
5625
0
    case UTT_HasTrivialAssign:
5626
0
    case UTT_HasTrivialMoveAssign:
5627
0
      Replacement = BTT_IsTriviallyAssignable;
5628
0
      break;
5629
0
    case UTT_HasTrivialCopy:
5630
0
      Replacement = UTT_IsTriviallyCopyable;
5631
0
      break;
5632
0
    case UTT_HasTrivialDefaultConstructor:
5633
0
    case UTT_HasTrivialMoveConstructor:
5634
0
      Replacement = TT_IsTriviallyConstructible;
5635
0
      break;
5636
0
    case UTT_HasTrivialDestructor:
5637
0
      Replacement = UTT_IsTriviallyDestructible;
5638
0
      break;
5639
0
    default:
5640
0
      return;
5641
0
  }
5642
0
  S.Diag(KWLoc, diag::warn_deprecated_builtin)
5643
0
    << getTraitSpelling(Kind) << getTraitSpelling(Replacement);
5644
0
}
5645
}
5646
5647
0
bool Sema::CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N) {
5648
0
  if (Arity && N != Arity) {
5649
0
    Diag(Loc, diag::err_type_trait_arity)
5650
0
        << Arity << 0 << (Arity > 1) << (int)N << SourceRange(Loc);
5651
0
    return false;
5652
0
  }
5653
5654
0
  if (!Arity && N == 0) {
5655
0
    Diag(Loc, diag::err_type_trait_arity)
5656
0
        << 1 << 1 << 1 << (int)N << SourceRange(Loc);
5657
0
    return false;
5658
0
  }
5659
0
  return true;
5660
0
}
5661
5662
enum class TypeTraitReturnType {
5663
  Bool,
5664
};
5665
5666
0
static TypeTraitReturnType GetReturnType(TypeTrait Kind) {
5667
0
  return TypeTraitReturnType::Bool;
5668
0
}
5669
5670
ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5671
                                ArrayRef<TypeSourceInfo *> Args,
5672
0
                                SourceLocation RParenLoc) {
5673
0
  if (!CheckTypeTraitArity(getTypeTraitArity(Kind), KWLoc, Args.size()))
5674
0
    return ExprError();
5675
5676
0
  if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
5677
0
                               *this, Kind, KWLoc, Args[0]->getType()))
5678
0
    return ExprError();
5679
5680
0
  DiagnoseBuiltinDeprecation(*this, Kind, KWLoc);
5681
5682
0
  bool Dependent = false;
5683
0
  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5684
0
    if (Args[I]->getType()->isDependentType()) {
5685
0
      Dependent = true;
5686
0
      break;
5687
0
    }
5688
0
  }
5689
5690
0
  switch (GetReturnType(Kind)) {
5691
0
  case TypeTraitReturnType::Bool: {
5692
0
    bool Result = EvaluateBooleanTypeTrait(*this, Kind, KWLoc, Args, RParenLoc,
5693
0
                                           Dependent);
5694
0
    return TypeTraitExpr::Create(Context, Context.getLogicalOperationType(),
5695
0
                                 KWLoc, Kind, Args, RParenLoc, Result);
5696
0
  }
5697
0
  }
5698
0
  llvm_unreachable("unhandled type trait return type");
5699
0
}
5700
5701
ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5702
                                ArrayRef<ParsedType> Args,
5703
0
                                SourceLocation RParenLoc) {
5704
0
  SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
5705
0
  ConvertedArgs.reserve(Args.size());
5706
5707
0
  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5708
0
    TypeSourceInfo *TInfo;
5709
0
    QualType T = GetTypeFromParser(Args[I], &TInfo);
5710
0
    if (!TInfo)
5711
0
      TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
5712
5713
0
    ConvertedArgs.push_back(TInfo);
5714
0
  }
5715
5716
0
  return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5717
0
}
5718
5719
static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5720
0
                                    QualType RhsT, SourceLocation KeyLoc) {
5721
0
  assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
5722
0
         "Cannot evaluate traits of dependent types");
5723
5724
0
  switch(BTT) {
5725
0
  case BTT_IsBaseOf: {
5726
    // C++0x [meta.rel]p2
5727
    // Base is a base class of Derived without regard to cv-qualifiers or
5728
    // Base and Derived are not unions and name the same class type without
5729
    // regard to cv-qualifiers.
5730
5731
0
    const RecordType *lhsRecord = LhsT->getAs<RecordType>();
5732
0
    const RecordType *rhsRecord = RhsT->getAs<RecordType>();
5733
0
    if (!rhsRecord || !lhsRecord) {
5734
0
      const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5735
0
      const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5736
0
      if (!LHSObjTy || !RHSObjTy)
5737
0
        return false;
5738
5739
0
      ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5740
0
      ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5741
0
      if (!BaseInterface || !DerivedInterface)
5742
0
        return false;
5743
5744
0
      if (Self.RequireCompleteType(
5745
0
              KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5746
0
        return false;
5747
5748
0
      return BaseInterface->isSuperClassOf(DerivedInterface);
5749
0
    }
5750
5751
0
    assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
5752
0
             == (lhsRecord == rhsRecord));
5753
5754
    // Unions are never base classes, and never have base classes.
5755
    // It doesn't matter if they are complete or not. See PR#41843
5756
0
    if (lhsRecord && lhsRecord->getDecl()->isUnion())
5757
0
      return false;
5758
0
    if (rhsRecord && rhsRecord->getDecl()->isUnion())
5759
0
      return false;
5760
5761
0
    if (lhsRecord == rhsRecord)
5762
0
      return true;
5763
5764
    // C++0x [meta.rel]p2:
5765
    //   If Base and Derived are class types and are different types
5766
    //   (ignoring possible cv-qualifiers) then Derived shall be a
5767
    //   complete type.
5768
0
    if (Self.RequireCompleteType(KeyLoc, RhsT,
5769
0
                          diag::err_incomplete_type_used_in_type_trait_expr))
5770
0
      return false;
5771
5772
0
    return cast<CXXRecordDecl>(rhsRecord->getDecl())
5773
0
      ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5774
0
  }
5775
0
  case BTT_IsSame:
5776
0
    return Self.Context.hasSameType(LhsT, RhsT);
5777
0
  case BTT_TypeCompatible: {
5778
    // GCC ignores cv-qualifiers on arrays for this builtin.
5779
0
    Qualifiers LhsQuals, RhsQuals;
5780
0
    QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5781
0
    QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5782
0
    return Self.Context.typesAreCompatible(Lhs, Rhs);
5783
0
  }
5784
0
  case BTT_IsConvertible:
5785
0
  case BTT_IsConvertibleTo: {
5786
    // C++0x [meta.rel]p4:
5787
    //   Given the following function prototype:
5788
    //
5789
    //     template <class T>
5790
    //       typename add_rvalue_reference<T>::type create();
5791
    //
5792
    //   the predicate condition for a template specialization
5793
    //   is_convertible<From, To> shall be satisfied if and only if
5794
    //   the return expression in the following code would be
5795
    //   well-formed, including any implicit conversions to the return
5796
    //   type of the function:
5797
    //
5798
    //     To test() {
5799
    //       return create<From>();
5800
    //     }
5801
    //
5802
    //   Access checking is performed as if in a context unrelated to To and
5803
    //   From. Only the validity of the immediate context of the expression
5804
    //   of the return-statement (including conversions to the return type)
5805
    //   is considered.
5806
    //
5807
    // We model the initialization as a copy-initialization of a temporary
5808
    // of the appropriate type, which for this expression is identical to the
5809
    // return statement (since NRVO doesn't apply).
5810
5811
    // Functions aren't allowed to return function or array types.
5812
0
    if (RhsT->isFunctionType() || RhsT->isArrayType())
5813
0
      return false;
5814
5815
    // A return statement in a void function must have void type.
5816
0
    if (RhsT->isVoidType())
5817
0
      return LhsT->isVoidType();
5818
5819
    // A function definition requires a complete, non-abstract return type.
5820
0
    if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
5821
0
      return false;
5822
5823
    // Compute the result of add_rvalue_reference.
5824
0
    if (LhsT->isObjectType() || LhsT->isFunctionType())
5825
0
      LhsT = Self.Context.getRValueReferenceType(LhsT);
5826
5827
    // Build a fake source and destination for initialization.
5828
0
    InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
5829
0
    OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5830
0
                         Expr::getValueKindForType(LhsT));
5831
0
    Expr *FromPtr = &From;
5832
0
    InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
5833
0
                                                           SourceLocation()));
5834
5835
    // Perform the initialization in an unevaluated context within a SFINAE
5836
    // trap at translation unit scope.
5837
0
    EnterExpressionEvaluationContext Unevaluated(
5838
0
        Self, Sema::ExpressionEvaluationContext::Unevaluated);
5839
0
    Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5840
0
    Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5841
0
    InitializationSequence Init(Self, To, Kind, FromPtr);
5842
0
    if (Init.Failed())
5843
0
      return false;
5844
5845
0
    ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
5846
0
    return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5847
0
  }
5848
5849
0
  case BTT_IsAssignable:
5850
0
  case BTT_IsNothrowAssignable:
5851
0
  case BTT_IsTriviallyAssignable: {
5852
    // C++11 [meta.unary.prop]p3:
5853
    //   is_trivially_assignable is defined as:
5854
    //     is_assignable<T, U>::value is true and the assignment, as defined by
5855
    //     is_assignable, is known to call no operation that is not trivial
5856
    //
5857
    //   is_assignable is defined as:
5858
    //     The expression declval<T>() = declval<U>() is well-formed when
5859
    //     treated as an unevaluated operand (Clause 5).
5860
    //
5861
    //   For both, T and U shall be complete types, (possibly cv-qualified)
5862
    //   void, or arrays of unknown bound.
5863
0
    if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
5864
0
        Self.RequireCompleteType(KeyLoc, LhsT,
5865
0
          diag::err_incomplete_type_used_in_type_trait_expr))
5866
0
      return false;
5867
0
    if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
5868
0
        Self.RequireCompleteType(KeyLoc, RhsT,
5869
0
          diag::err_incomplete_type_used_in_type_trait_expr))
5870
0
      return false;
5871
5872
    // cv void is never assignable.
5873
0
    if (LhsT->isVoidType() || RhsT->isVoidType())
5874
0
      return false;
5875
5876
    // Build expressions that emulate the effect of declval<T>() and
5877
    // declval<U>().
5878
0
    if (LhsT->isObjectType() || LhsT->isFunctionType())
5879
0
      LhsT = Self.Context.getRValueReferenceType(LhsT);
5880
0
    if (RhsT->isObjectType() || RhsT->isFunctionType())
5881
0
      RhsT = Self.Context.getRValueReferenceType(RhsT);
5882
0
    OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5883
0
                        Expr::getValueKindForType(LhsT));
5884
0
    OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5885
0
                        Expr::getValueKindForType(RhsT));
5886
5887
    // Attempt the assignment in an unevaluated context within a SFINAE
5888
    // trap at translation unit scope.
5889
0
    EnterExpressionEvaluationContext Unevaluated(
5890
0
        Self, Sema::ExpressionEvaluationContext::Unevaluated);
5891
0
    Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5892
0
    Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5893
0
    ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5894
0
                                        &Rhs);
5895
0
    if (Result.isInvalid())
5896
0
      return false;
5897
5898
    // Treat the assignment as unused for the purpose of -Wdeprecated-volatile.
5899
0
    Self.CheckUnusedVolatileAssignment(Result.get());
5900
5901
0
    if (SFINAE.hasErrorOccurred())
5902
0
      return false;
5903
5904
0
    if (BTT == BTT_IsAssignable)
5905
0
      return true;
5906
5907
0
    if (BTT == BTT_IsNothrowAssignable)
5908
0
      return Self.canThrow(Result.get()) == CT_Cannot;
5909
5910
0
    if (BTT == BTT_IsTriviallyAssignable) {
5911
      // Under Objective-C ARC and Weak, if the destination has non-trivial
5912
      // Objective-C lifetime, this is a non-trivial assignment.
5913
0
      if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
5914
0
        return false;
5915
5916
0
      return !Result.get()->hasNonTrivialCall(Self.Context);
5917
0
    }
5918
5919
0
    llvm_unreachable("unhandled type trait");
5920
0
    return false;
5921
0
  }
5922
0
    default: llvm_unreachable("not a BTT");
5923
0
  }
5924
0
  llvm_unreachable("Unknown type trait or not implemented");
5925
0
}
5926
5927
ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5928
                                     SourceLocation KWLoc,
5929
                                     ParsedType Ty,
5930
                                     Expr* DimExpr,
5931
0
                                     SourceLocation RParen) {
5932
0
  TypeSourceInfo *TSInfo;
5933
0
  QualType T = GetTypeFromParser(Ty, &TSInfo);
5934
0
  if (!TSInfo)
5935
0
    TSInfo = Context.getTrivialTypeSourceInfo(T);
5936
5937
0
  return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5938
0
}
5939
5940
static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5941
                                           QualType T, Expr *DimExpr,
5942
0
                                           SourceLocation KeyLoc) {
5943
0
  assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
5944
5945
0
  switch(ATT) {
5946
0
  case ATT_ArrayRank:
5947
0
    if (T->isArrayType()) {
5948
0
      unsigned Dim = 0;
5949
0
      while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5950
0
        ++Dim;
5951
0
        T = AT->getElementType();
5952
0
      }
5953
0
      return Dim;
5954
0
    }
5955
0
    return 0;
5956
5957
0
  case ATT_ArrayExtent: {
5958
0
    llvm::APSInt Value;
5959
0
    uint64_t Dim;
5960
0
    if (Self.VerifyIntegerConstantExpression(
5961
0
                DimExpr, &Value, diag::err_dimension_expr_not_constant_integer)
5962
0
            .isInvalid())
5963
0
      return 0;
5964
0
    if (Value.isSigned() && Value.isNegative()) {
5965
0
      Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5966
0
        << DimExpr->getSourceRange();
5967
0
      return 0;
5968
0
    }
5969
0
    Dim = Value.getLimitedValue();
5970
5971
0
    if (T->isArrayType()) {
5972
0
      unsigned D = 0;
5973
0
      bool Matched = false;
5974
0
      while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5975
0
        if (Dim == D) {
5976
0
          Matched = true;
5977
0
          break;
5978
0
        }
5979
0
        ++D;
5980
0
        T = AT->getElementType();
5981
0
      }
5982
5983
0
      if (Matched && T->isArrayType()) {
5984
0
        if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5985
0
          return CAT->getSize().getLimitedValue();
5986
0
      }
5987
0
    }
5988
0
    return 0;
5989
0
  }
5990
0
  }
5991
0
  llvm_unreachable("Unknown type trait or not implemented");
5992
0
}
5993
5994
ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5995
                                     SourceLocation KWLoc,
5996
                                     TypeSourceInfo *TSInfo,
5997
                                     Expr* DimExpr,
5998
0
                                     SourceLocation RParen) {
5999
0
  QualType T = TSInfo->getType();
6000
6001
  // FIXME: This should likely be tracked as an APInt to remove any host
6002
  // assumptions about the width of size_t on the target.
6003
0
  uint64_t Value = 0;
6004
0
  if (!T->isDependentType())
6005
0
    Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
6006
6007
  // While the specification for these traits from the Embarcadero C++
6008
  // compiler's documentation says the return type is 'unsigned int', Clang
6009
  // returns 'size_t'. On Windows, the primary platform for the Embarcadero
6010
  // compiler, there is no difference. On several other platforms this is an
6011
  // important distinction.
6012
0
  return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
6013
0
                                          RParen, Context.getSizeType());
6014
0
}
6015
6016
ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
6017
                                      SourceLocation KWLoc,
6018
                                      Expr *Queried,
6019
0
                                      SourceLocation RParen) {
6020
  // If error parsing the expression, ignore.
6021
0
  if (!Queried)
6022
0
    return ExprError();
6023
6024
0
  ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
6025
6026
0
  return Result;
6027
0
}
6028
6029
0
static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
6030
0
  switch (ET) {
6031
0
  case ET_IsLValueExpr: return E->isLValue();
6032
0
  case ET_IsRValueExpr:
6033
0
    return E->isPRValue();
6034
0
  }
6035
0
  llvm_unreachable("Expression trait not covered by switch");
6036
0
}
6037
6038
ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
6039
                                      SourceLocation KWLoc,
6040
                                      Expr *Queried,
6041
0
                                      SourceLocation RParen) {
6042
0
  if (Queried->isTypeDependent()) {
6043
    // Delay type-checking for type-dependent expressions.
6044
0
  } else if (Queried->hasPlaceholderType()) {
6045
0
    ExprResult PE = CheckPlaceholderExpr(Queried);
6046
0
    if (PE.isInvalid()) return ExprError();
6047
0
    return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
6048
0
  }
6049
6050
0
  bool Value = EvaluateExpressionTrait(ET, Queried);
6051
6052
0
  return new (Context)
6053
0
      ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
6054
0
}
6055
6056
QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
6057
                                            ExprValueKind &VK,
6058
                                            SourceLocation Loc,
6059
0
                                            bool isIndirect) {
6060
0
  assert(!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() &&
6061
0
         "placeholders should have been weeded out by now");
6062
6063
  // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
6064
  // temporary materialization conversion otherwise.
6065
0
  if (isIndirect)
6066
0
    LHS = DefaultLvalueConversion(LHS.get());
6067
0
  else if (LHS.get()->isPRValue())
6068
0
    LHS = TemporaryMaterializationConversion(LHS.get());
6069
0
  if (LHS.isInvalid())
6070
0
    return QualType();
6071
6072
  // The RHS always undergoes lvalue conversions.
6073
0
  RHS = DefaultLvalueConversion(RHS.get());
6074
0
  if (RHS.isInvalid()) return QualType();
6075
6076
0
  const char *OpSpelling = isIndirect ? "->*" : ".*";
6077
  // C++ 5.5p2
6078
  //   The binary operator .* [p3: ->*] binds its second operand, which shall
6079
  //   be of type "pointer to member of T" (where T is a completely-defined
6080
  //   class type) [...]
6081
0
  QualType RHSType = RHS.get()->getType();
6082
0
  const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
6083
0
  if (!MemPtr) {
6084
0
    Diag(Loc, diag::err_bad_memptr_rhs)
6085
0
      << OpSpelling << RHSType << RHS.get()->getSourceRange();
6086
0
    return QualType();
6087
0
  }
6088
6089
0
  QualType Class(MemPtr->getClass(), 0);
6090
6091
  // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
6092
  // member pointer points must be completely-defined. However, there is no
6093
  // reason for this semantic distinction, and the rule is not enforced by
6094
  // other compilers. Therefore, we do not check this property, as it is
6095
  // likely to be considered a defect.
6096
6097
  // C++ 5.5p2
6098
  //   [...] to its first operand, which shall be of class T or of a class of
6099
  //   which T is an unambiguous and accessible base class. [p3: a pointer to
6100
  //   such a class]
6101
0
  QualType LHSType = LHS.get()->getType();
6102
0
  if (isIndirect) {
6103
0
    if (const PointerType *Ptr = LHSType->getAs<PointerType>())
6104
0
      LHSType = Ptr->getPointeeType();
6105
0
    else {
6106
0
      Diag(Loc, diag::err_bad_memptr_lhs)
6107
0
        << OpSpelling << 1 << LHSType
6108
0
        << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
6109
0
      return QualType();
6110
0
    }
6111
0
  }
6112
6113
0
  if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
6114
    // If we want to check the hierarchy, we need a complete type.
6115
0
    if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
6116
0
                            OpSpelling, (int)isIndirect)) {
6117
0
      return QualType();
6118
0
    }
6119
6120
0
    if (!IsDerivedFrom(Loc, LHSType, Class)) {
6121
0
      Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
6122
0
        << (int)isIndirect << LHS.get()->getType();
6123
0
      return QualType();
6124
0
    }
6125
6126
0
    CXXCastPath BasePath;
6127
0
    if (CheckDerivedToBaseConversion(
6128
0
            LHSType, Class, Loc,
6129
0
            SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
6130
0
            &BasePath))
6131
0
      return QualType();
6132
6133
    // Cast LHS to type of use.
6134
0
    QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
6135
0
    if (isIndirect)
6136
0
      UseType = Context.getPointerType(UseType);
6137
0
    ExprValueKind VK = isIndirect ? VK_PRValue : LHS.get()->getValueKind();
6138
0
    LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
6139
0
                            &BasePath);
6140
0
  }
6141
6142
0
  if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
6143
    // Diagnose use of pointer-to-member type which when used as
6144
    // the functional cast in a pointer-to-member expression.
6145
0
    Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
6146
0
     return QualType();
6147
0
  }
6148
6149
  // C++ 5.5p2
6150
  //   The result is an object or a function of the type specified by the
6151
  //   second operand.
6152
  // The cv qualifiers are the union of those in the pointer and the left side,
6153
  // in accordance with 5.5p5 and 5.2.5.
6154
0
  QualType Result = MemPtr->getPointeeType();
6155
0
  Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
6156
6157
  // C++0x [expr.mptr.oper]p6:
6158
  //   In a .* expression whose object expression is an rvalue, the program is
6159
  //   ill-formed if the second operand is a pointer to member function with
6160
  //   ref-qualifier &. In a ->* expression or in a .* expression whose object
6161
  //   expression is an lvalue, the program is ill-formed if the second operand
6162
  //   is a pointer to member function with ref-qualifier &&.
6163
0
  if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
6164
0
    switch (Proto->getRefQualifier()) {
6165
0
    case RQ_None:
6166
      // Do nothing
6167
0
      break;
6168
6169
0
    case RQ_LValue:
6170
0
      if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
6171
        // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
6172
        // is (exactly) 'const'.
6173
0
        if (Proto->isConst() && !Proto->isVolatile())
6174
0
          Diag(Loc, getLangOpts().CPlusPlus20
6175
0
                        ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
6176
0
                        : diag::ext_pointer_to_const_ref_member_on_rvalue);
6177
0
        else
6178
0
          Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
6179
0
              << RHSType << 1 << LHS.get()->getSourceRange();
6180
0
      }
6181
0
      break;
6182
6183
0
    case RQ_RValue:
6184
0
      if (isIndirect || !LHS.get()->Classify(Context).isRValue())
6185
0
        Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
6186
0
          << RHSType << 0 << LHS.get()->getSourceRange();
6187
0
      break;
6188
0
    }
6189
0
  }
6190
6191
  // C++ [expr.mptr.oper]p6:
6192
  //   The result of a .* expression whose second operand is a pointer
6193
  //   to a data member is of the same value category as its
6194
  //   first operand. The result of a .* expression whose second
6195
  //   operand is a pointer to a member function is a prvalue. The
6196
  //   result of an ->* expression is an lvalue if its second operand
6197
  //   is a pointer to data member and a prvalue otherwise.
6198
0
  if (Result->isFunctionType()) {
6199
0
    VK = VK_PRValue;
6200
0
    return Context.BoundMemberTy;
6201
0
  } else if (isIndirect) {
6202
0
    VK = VK_LValue;
6203
0
  } else {
6204
0
    VK = LHS.get()->getValueKind();
6205
0
  }
6206
6207
0
  return Result;
6208
0
}
6209
6210
/// Try to convert a type to another according to C++11 5.16p3.
6211
///
6212
/// This is part of the parameter validation for the ? operator. If either
6213
/// value operand is a class type, the two operands are attempted to be
6214
/// converted to each other. This function does the conversion in one direction.
6215
/// It returns true if the program is ill-formed and has already been diagnosed
6216
/// as such.
6217
static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
6218
                                SourceLocation QuestionLoc,
6219
                                bool &HaveConversion,
6220
0
                                QualType &ToType) {
6221
0
  HaveConversion = false;
6222
0
  ToType = To->getType();
6223
6224
0
  InitializationKind Kind =
6225
0
      InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation());
6226
  // C++11 5.16p3
6227
  //   The process for determining whether an operand expression E1 of type T1
6228
  //   can be converted to match an operand expression E2 of type T2 is defined
6229
  //   as follows:
6230
  //   -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
6231
  //      implicitly converted to type "lvalue reference to T2", subject to the
6232
  //      constraint that in the conversion the reference must bind directly to
6233
  //      an lvalue.
6234
  //   -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
6235
  //      implicitly converted to the type "rvalue reference to R2", subject to
6236
  //      the constraint that the reference must bind directly.
6237
0
  if (To->isGLValue()) {
6238
0
    QualType T = Self.Context.getReferenceQualifiedType(To);
6239
0
    InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
6240
6241
0
    InitializationSequence InitSeq(Self, Entity, Kind, From);
6242
0
    if (InitSeq.isDirectReferenceBinding()) {
6243
0
      ToType = T;
6244
0
      HaveConversion = true;
6245
0
      return false;
6246
0
    }
6247
6248
0
    if (InitSeq.isAmbiguous())
6249
0
      return InitSeq.Diagnose(Self, Entity, Kind, From);
6250
0
  }
6251
6252
  //   -- If E2 is an rvalue, or if the conversion above cannot be done:
6253
  //      -- if E1 and E2 have class type, and the underlying class types are
6254
  //         the same or one is a base class of the other:
6255
0
  QualType FTy = From->getType();
6256
0
  QualType TTy = To->getType();
6257
0
  const RecordType *FRec = FTy->getAs<RecordType>();
6258
0
  const RecordType *TRec = TTy->getAs<RecordType>();
6259
0
  bool FDerivedFromT = FRec && TRec && FRec != TRec &&
6260
0
                       Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
6261
0
  if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
6262
0
                       Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
6263
    //         E1 can be converted to match E2 if the class of T2 is the
6264
    //         same type as, or a base class of, the class of T1, and
6265
    //         [cv2 > cv1].
6266
0
    if (FRec == TRec || FDerivedFromT) {
6267
0
      if (TTy.isAtLeastAsQualifiedAs(FTy)) {
6268
0
        InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
6269
0
        InitializationSequence InitSeq(Self, Entity, Kind, From);
6270
0
        if (InitSeq) {
6271
0
          HaveConversion = true;
6272
0
          return false;
6273
0
        }
6274
6275
0
        if (InitSeq.isAmbiguous())
6276
0
          return InitSeq.Diagnose(Self, Entity, Kind, From);
6277
0
      }
6278
0
    }
6279
6280
0
    return false;
6281
0
  }
6282
6283
  //     -- Otherwise: E1 can be converted to match E2 if E1 can be
6284
  //        implicitly converted to the type that expression E2 would have
6285
  //        if E2 were converted to an rvalue (or the type it has, if E2 is
6286
  //        an rvalue).
6287
  //
6288
  // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
6289
  // to the array-to-pointer or function-to-pointer conversions.
6290
0
  TTy = TTy.getNonLValueExprType(Self.Context);
6291
6292
0
  InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
6293
0
  InitializationSequence InitSeq(Self, Entity, Kind, From);
6294
0
  HaveConversion = !InitSeq.Failed();
6295
0
  ToType = TTy;
6296
0
  if (InitSeq.isAmbiguous())
6297
0
    return InitSeq.Diagnose(Self, Entity, Kind, From);
6298
6299
0
  return false;
6300
0
}
6301
6302
/// Try to find a common type for two according to C++0x 5.16p5.
6303
///
6304
/// This is part of the parameter validation for the ? operator. If either
6305
/// value operand is a class type, overload resolution is used to find a
6306
/// conversion to a common type.
6307
static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
6308
0
                                    SourceLocation QuestionLoc) {
6309
0
  Expr *Args[2] = { LHS.get(), RHS.get() };
6310
0
  OverloadCandidateSet CandidateSet(QuestionLoc,
6311
0
                                    OverloadCandidateSet::CSK_Operator);
6312
0
  Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
6313
0
                                    CandidateSet);
6314
6315
0
  OverloadCandidateSet::iterator Best;
6316
0
  switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
6317
0
    case OR_Success: {
6318
      // We found a match. Perform the conversions on the arguments and move on.
6319
0
      ExprResult LHSRes = Self.PerformImplicitConversion(
6320
0
          LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
6321
0
          Sema::AA_Converting);
6322
0
      if (LHSRes.isInvalid())
6323
0
        break;
6324
0
      LHS = LHSRes;
6325
6326
0
      ExprResult RHSRes = Self.PerformImplicitConversion(
6327
0
          RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
6328
0
          Sema::AA_Converting);
6329
0
      if (RHSRes.isInvalid())
6330
0
        break;
6331
0
      RHS = RHSRes;
6332
0
      if (Best->Function)
6333
0
        Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
6334
0
      return false;
6335
0
    }
6336
6337
0
    case OR_No_Viable_Function:
6338
6339
      // Emit a better diagnostic if one of the expressions is a null pointer
6340
      // constant and the other is a pointer type. In this case, the user most
6341
      // likely forgot to take the address of the other expression.
6342
0
      if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6343
0
        return true;
6344
6345
0
      Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6346
0
        << LHS.get()->getType() << RHS.get()->getType()
6347
0
        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6348
0
      return true;
6349
6350
0
    case OR_Ambiguous:
6351
0
      Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
6352
0
        << LHS.get()->getType() << RHS.get()->getType()
6353
0
        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6354
      // FIXME: Print the possible common types by printing the return types of
6355
      // the viable candidates.
6356
0
      break;
6357
6358
0
    case OR_Deleted:
6359
0
      llvm_unreachable("Conditional operator has only built-in overloads");
6360
0
  }
6361
0
  return true;
6362
0
}
6363
6364
/// Perform an "extended" implicit conversion as returned by
6365
/// TryClassUnification.
6366
0
static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
6367
0
  InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
6368
0
  InitializationKind Kind =
6369
0
      InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation());
6370
0
  Expr *Arg = E.get();
6371
0
  InitializationSequence InitSeq(Self, Entity, Kind, Arg);
6372
0
  ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
6373
0
  if (Result.isInvalid())
6374
0
    return true;
6375
6376
0
  E = Result;
6377
0
  return false;
6378
0
}
6379
6380
// Check the condition operand of ?: to see if it is valid for the GCC
6381
// extension.
6382
static bool isValidVectorForConditionalCondition(ASTContext &Ctx,
6383
2
                                                 QualType CondTy) {
6384
2
  if (!CondTy->isVectorType() && !CondTy->isExtVectorType())
6385
2
    return false;
6386
0
  const QualType EltTy =
6387
0
      cast<VectorType>(CondTy.getCanonicalType())->getElementType();
6388
0
  assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");
6389
0
  return EltTy->isIntegralType(Ctx);
6390
2
}
6391
6392
static bool isValidSizelessVectorForConditionalCondition(ASTContext &Ctx,
6393
2
                                                         QualType CondTy) {
6394
2
  if (!CondTy->isSveVLSBuiltinType())
6395
2
    return false;
6396
0
  const QualType EltTy =
6397
0
      cast<BuiltinType>(CondTy.getCanonicalType())->getSveEltType(Ctx);
6398
0
  assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");
6399
0
  return EltTy->isIntegralType(Ctx);
6400
2
}
6401
6402
QualType Sema::CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
6403
                                           ExprResult &RHS,
6404
0
                                           SourceLocation QuestionLoc) {
6405
0
  LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6406
0
  RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6407
6408
0
  QualType CondType = Cond.get()->getType();
6409
0
  const auto *CondVT = CondType->castAs<VectorType>();
6410
0
  QualType CondElementTy = CondVT->getElementType();
6411
0
  unsigned CondElementCount = CondVT->getNumElements();
6412
0
  QualType LHSType = LHS.get()->getType();
6413
0
  const auto *LHSVT = LHSType->getAs<VectorType>();
6414
0
  QualType RHSType = RHS.get()->getType();
6415
0
  const auto *RHSVT = RHSType->getAs<VectorType>();
6416
6417
0
  QualType ResultType;
6418
6419
6420
0
  if (LHSVT && RHSVT) {
6421
0
    if (isa<ExtVectorType>(CondVT) != isa<ExtVectorType>(LHSVT)) {
6422
0
      Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch)
6423
0
          << /*isExtVector*/ isa<ExtVectorType>(CondVT);
6424
0
      return {};
6425
0
    }
6426
6427
    // If both are vector types, they must be the same type.
6428
0
    if (!Context.hasSameType(LHSType, RHSType)) {
6429
0
      Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
6430
0
          << LHSType << RHSType;
6431
0
      return {};
6432
0
    }
6433
0
    ResultType = Context.getCommonSugaredType(LHSType, RHSType);
6434
0
  } else if (LHSVT || RHSVT) {
6435
0
    ResultType = CheckVectorOperands(
6436
0
        LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true,
6437
0
        /*AllowBoolConversions*/ false,
6438
0
        /*AllowBoolOperation*/ true,
6439
0
        /*ReportInvalid*/ true);
6440
0
    if (ResultType.isNull())
6441
0
      return {};
6442
0
  } else {
6443
    // Both are scalar.
6444
0
    LHSType = LHSType.getUnqualifiedType();
6445
0
    RHSType = RHSType.getUnqualifiedType();
6446
0
    QualType ResultElementTy =
6447
0
        Context.hasSameType(LHSType, RHSType)
6448
0
            ? Context.getCommonSugaredType(LHSType, RHSType)
6449
0
            : UsualArithmeticConversions(LHS, RHS, QuestionLoc,
6450
0
                                         ACK_Conditional);
6451
6452
0
    if (ResultElementTy->isEnumeralType()) {
6453
0
      Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
6454
0
          << ResultElementTy;
6455
0
      return {};
6456
0
    }
6457
0
    if (CondType->isExtVectorType())
6458
0
      ResultType =
6459
0
          Context.getExtVectorType(ResultElementTy, CondVT->getNumElements());
6460
0
    else
6461
0
      ResultType = Context.getVectorType(
6462
0
          ResultElementTy, CondVT->getNumElements(), VectorKind::Generic);
6463
6464
0
    LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
6465
0
    RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
6466
0
  }
6467
6468
0
  assert(!ResultType.isNull() && ResultType->isVectorType() &&
6469
0
         (!CondType->isExtVectorType() || ResultType->isExtVectorType()) &&
6470
0
         "Result should have been a vector type");
6471
0
  auto *ResultVectorTy = ResultType->castAs<VectorType>();
6472
0
  QualType ResultElementTy = ResultVectorTy->getElementType();
6473
0
  unsigned ResultElementCount = ResultVectorTy->getNumElements();
6474
6475
0
  if (ResultElementCount != CondElementCount) {
6476
0
    Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType
6477
0
                                                         << ResultType;
6478
0
    return {};
6479
0
  }
6480
6481
0
  if (Context.getTypeSize(ResultElementTy) !=
6482
0
      Context.getTypeSize(CondElementTy)) {
6483
0
    Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType
6484
0
                                                                 << ResultType;
6485
0
    return {};
6486
0
  }
6487
6488
0
  return ResultType;
6489
0
}
6490
6491
QualType Sema::CheckSizelessVectorConditionalTypes(ExprResult &Cond,
6492
                                                   ExprResult &LHS,
6493
                                                   ExprResult &RHS,
6494
0
                                                   SourceLocation QuestionLoc) {
6495
0
  LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6496
0
  RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6497
6498
0
  QualType CondType = Cond.get()->getType();
6499
0
  const auto *CondBT = CondType->castAs<BuiltinType>();
6500
0
  QualType CondElementTy = CondBT->getSveEltType(Context);
6501
0
  llvm::ElementCount CondElementCount =
6502
0
      Context.getBuiltinVectorTypeInfo(CondBT).EC;
6503
6504
0
  QualType LHSType = LHS.get()->getType();
6505
0
  const auto *LHSBT =
6506
0
      LHSType->isSveVLSBuiltinType() ? LHSType->getAs<BuiltinType>() : nullptr;
6507
0
  QualType RHSType = RHS.get()->getType();
6508
0
  const auto *RHSBT =
6509
0
      RHSType->isSveVLSBuiltinType() ? RHSType->getAs<BuiltinType>() : nullptr;
6510
6511
0
  QualType ResultType;
6512
6513
0
  if (LHSBT && RHSBT) {
6514
    // If both are sizeless vector types, they must be the same type.
6515
0
    if (!Context.hasSameType(LHSType, RHSType)) {
6516
0
      Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
6517
0
          << LHSType << RHSType;
6518
0
      return QualType();
6519
0
    }
6520
0
    ResultType = LHSType;
6521
0
  } else if (LHSBT || RHSBT) {
6522
0
    ResultType = CheckSizelessVectorOperands(
6523
0
        LHS, RHS, QuestionLoc, /*IsCompAssign*/ false, ACK_Conditional);
6524
0
    if (ResultType.isNull())
6525
0
      return QualType();
6526
0
  } else {
6527
    // Both are scalar so splat
6528
0
    QualType ResultElementTy;
6529
0
    LHSType = LHSType.getCanonicalType().getUnqualifiedType();
6530
0
    RHSType = RHSType.getCanonicalType().getUnqualifiedType();
6531
6532
0
    if (Context.hasSameType(LHSType, RHSType))
6533
0
      ResultElementTy = LHSType;
6534
0
    else
6535
0
      ResultElementTy =
6536
0
          UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
6537
6538
0
    if (ResultElementTy->isEnumeralType()) {
6539
0
      Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
6540
0
          << ResultElementTy;
6541
0
      return QualType();
6542
0
    }
6543
6544
0
    ResultType = Context.getScalableVectorType(
6545
0
        ResultElementTy, CondElementCount.getKnownMinValue());
6546
6547
0
    LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
6548
0
    RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
6549
0
  }
6550
6551
0
  assert(!ResultType.isNull() && ResultType->isSveVLSBuiltinType() &&
6552
0
         "Result should have been a vector type");
6553
0
  auto *ResultBuiltinTy = ResultType->castAs<BuiltinType>();
6554
0
  QualType ResultElementTy = ResultBuiltinTy->getSveEltType(Context);
6555
0
  llvm::ElementCount ResultElementCount =
6556
0
      Context.getBuiltinVectorTypeInfo(ResultBuiltinTy).EC;
6557
6558
0
  if (ResultElementCount != CondElementCount) {
6559
0
    Diag(QuestionLoc, diag::err_conditional_vector_size)
6560
0
        << CondType << ResultType;
6561
0
    return QualType();
6562
0
  }
6563
6564
0
  if (Context.getTypeSize(ResultElementTy) !=
6565
0
      Context.getTypeSize(CondElementTy)) {
6566
0
    Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6567
0
        << CondType << ResultType;
6568
0
    return QualType();
6569
0
  }
6570
6571
0
  return ResultType;
6572
0
}
6573
6574
/// Check the operands of ?: under C++ semantics.
6575
///
6576
/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
6577
/// extension. In this case, LHS == Cond. (But they're not aliases.)
6578
///
6579
/// This function also implements GCC's vector extension and the
6580
/// OpenCL/ext_vector_type extension for conditionals. The vector extensions
6581
/// permit the use of a?b:c where the type of a is that of a integer vector with
6582
/// the same number of elements and size as the vectors of b and c. If one of
6583
/// either b or c is a scalar it is implicitly converted to match the type of
6584
/// the vector. Otherwise the expression is ill-formed. If both b and c are
6585
/// scalars, then b and c are checked and converted to the type of a if
6586
/// possible.
6587
///
6588
/// The expressions are evaluated differently for GCC's and OpenCL's extensions.
6589
/// For the GCC extension, the ?: operator is evaluated as
6590
///   (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
6591
/// For the OpenCL extensions, the ?: operator is evaluated as
6592
///   (most-significant-bit-set(a[0])  ? b[0] : c[0], .. ,
6593
///    most-significant-bit-set(a[n]) ? b[n] : c[n]).
6594
QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6595
                                           ExprResult &RHS, ExprValueKind &VK,
6596
                                           ExprObjectKind &OK,
6597
2
                                           SourceLocation QuestionLoc) {
6598
  // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface
6599
  // pointers.
6600
6601
  // Assume r-value.
6602
2
  VK = VK_PRValue;
6603
2
  OK = OK_Ordinary;
6604
2
  bool IsVectorConditional =
6605
2
      isValidVectorForConditionalCondition(Context, Cond.get()->getType());
6606
6607
2
  bool IsSizelessVectorConditional =
6608
2
      isValidSizelessVectorForConditionalCondition(Context,
6609
2
                                                   Cond.get()->getType());
6610
6611
  // C++11 [expr.cond]p1
6612
  //   The first expression is contextually converted to bool.
6613
2
  if (!Cond.get()->isTypeDependent()) {
6614
0
    ExprResult CondRes = IsVectorConditional || IsSizelessVectorConditional
6615
0
                             ? DefaultFunctionArrayLvalueConversion(Cond.get())
6616
0
                             : CheckCXXBooleanCondition(Cond.get());
6617
0
    if (CondRes.isInvalid())
6618
0
      return QualType();
6619
0
    Cond = CondRes;
6620
2
  } else {
6621
    // To implement C++, the first expression typically doesn't alter the result
6622
    // type of the conditional, however the GCC compatible vector extension
6623
    // changes the result type to be that of the conditional. Since we cannot
6624
    // know if this is a vector extension here, delay the conversion of the
6625
    // LHS/RHS below until later.
6626
2
    return Context.DependentTy;
6627
2
  }
6628
6629
6630
  // Either of the arguments dependent?
6631
0
  if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
6632
0
    return Context.DependentTy;
6633
6634
  // C++11 [expr.cond]p2
6635
  //   If either the second or the third operand has type (cv) void, ...
6636
0
  QualType LTy = LHS.get()->getType();
6637
0
  QualType RTy = RHS.get()->getType();
6638
0
  bool LVoid = LTy->isVoidType();
6639
0
  bool RVoid = RTy->isVoidType();
6640
0
  if (LVoid || RVoid) {
6641
    //   ... one of the following shall hold:
6642
    //   -- The second or the third operand (but not both) is a (possibly
6643
    //      parenthesized) throw-expression; the result is of the type
6644
    //      and value category of the other.
6645
0
    bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
6646
0
    bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
6647
6648
    // Void expressions aren't legal in the vector-conditional expressions.
6649
0
    if (IsVectorConditional) {
6650
0
      SourceRange DiagLoc =
6651
0
          LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange();
6652
0
      bool IsThrow = LVoid ? LThrow : RThrow;
6653
0
      Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void)
6654
0
          << DiagLoc << IsThrow;
6655
0
      return QualType();
6656
0
    }
6657
6658
0
    if (LThrow != RThrow) {
6659
0
      Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
6660
0
      VK = NonThrow->getValueKind();
6661
      // DR (no number yet): the result is a bit-field if the
6662
      // non-throw-expression operand is a bit-field.
6663
0
      OK = NonThrow->getObjectKind();
6664
0
      return NonThrow->getType();
6665
0
    }
6666
6667
    //   -- Both the second and third operands have type void; the result is of
6668
    //      type void and is a prvalue.
6669
0
    if (LVoid && RVoid)
6670
0
      return Context.getCommonSugaredType(LTy, RTy);
6671
6672
    // Neither holds, error.
6673
0
    Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
6674
0
      << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
6675
0
      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6676
0
    return QualType();
6677
0
  }
6678
6679
  // Neither is void.
6680
0
  if (IsVectorConditional)
6681
0
    return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
6682
6683
0
  if (IsSizelessVectorConditional)
6684
0
    return CheckSizelessVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
6685
6686
  // WebAssembly tables are not allowed as conditional LHS or RHS.
6687
0
  if (LTy->isWebAssemblyTableType() || RTy->isWebAssemblyTableType()) {
6688
0
    Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
6689
0
        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6690
0
    return QualType();
6691
0
  }
6692
6693
  // C++11 [expr.cond]p3
6694
  //   Otherwise, if the second and third operand have different types, and
6695
  //   either has (cv) class type [...] an attempt is made to convert each of
6696
  //   those operands to the type of the other.
6697
0
  if (!Context.hasSameType(LTy, RTy) &&
6698
0
      (LTy->isRecordType() || RTy->isRecordType())) {
6699
    // These return true if a single direction is already ambiguous.
6700
0
    QualType L2RType, R2LType;
6701
0
    bool HaveL2R, HaveR2L;
6702
0
    if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
6703
0
      return QualType();
6704
0
    if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
6705
0
      return QualType();
6706
6707
    //   If both can be converted, [...] the program is ill-formed.
6708
0
    if (HaveL2R && HaveR2L) {
6709
0
      Diag(QuestionLoc, diag::err_conditional_ambiguous)
6710
0
        << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6711
0
      return QualType();
6712
0
    }
6713
6714
    //   If exactly one conversion is possible, that conversion is applied to
6715
    //   the chosen operand and the converted operands are used in place of the
6716
    //   original operands for the remainder of this section.
6717
0
    if (HaveL2R) {
6718
0
      if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
6719
0
        return QualType();
6720
0
      LTy = LHS.get()->getType();
6721
0
    } else if (HaveR2L) {
6722
0
      if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
6723
0
        return QualType();
6724
0
      RTy = RHS.get()->getType();
6725
0
    }
6726
0
  }
6727
6728
  // C++11 [expr.cond]p3
6729
  //   if both are glvalues of the same value category and the same type except
6730
  //   for cv-qualification, an attempt is made to convert each of those
6731
  //   operands to the type of the other.
6732
  // FIXME:
6733
  //   Resolving a defect in P0012R1: we extend this to cover all cases where
6734
  //   one of the operands is reference-compatible with the other, in order
6735
  //   to support conditionals between functions differing in noexcept. This
6736
  //   will similarly cover difference in array bounds after P0388R4.
6737
  // FIXME: If LTy and RTy have a composite pointer type, should we convert to
6738
  //   that instead?
6739
0
  ExprValueKind LVK = LHS.get()->getValueKind();
6740
0
  ExprValueKind RVK = RHS.get()->getValueKind();
6741
0
  if (!Context.hasSameType(LTy, RTy) && LVK == RVK && LVK != VK_PRValue) {
6742
    // DerivedToBase was already handled by the class-specific case above.
6743
    // FIXME: Should we allow ObjC conversions here?
6744
0
    const ReferenceConversions AllowedConversions =
6745
0
        ReferenceConversions::Qualification |
6746
0
        ReferenceConversions::NestedQualification |
6747
0
        ReferenceConversions::Function;
6748
6749
0
    ReferenceConversions RefConv;
6750
0
    if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) ==
6751
0
            Ref_Compatible &&
6752
0
        !(RefConv & ~AllowedConversions) &&
6753
        // [...] subject to the constraint that the reference must bind
6754
        // directly [...]
6755
0
        !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) {
6756
0
      RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
6757
0
      RTy = RHS.get()->getType();
6758
0
    } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) ==
6759
0
                   Ref_Compatible &&
6760
0
               !(RefConv & ~AllowedConversions) &&
6761
0
               !LHS.get()->refersToBitField() &&
6762
0
               !LHS.get()->refersToVectorElement()) {
6763
0
      LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
6764
0
      LTy = LHS.get()->getType();
6765
0
    }
6766
0
  }
6767
6768
  // C++11 [expr.cond]p4
6769
  //   If the second and third operands are glvalues of the same value
6770
  //   category and have the same type, the result is of that type and
6771
  //   value category and it is a bit-field if the second or the third
6772
  //   operand is a bit-field, or if both are bit-fields.
6773
  // We only extend this to bitfields, not to the crazy other kinds of
6774
  // l-values.
6775
0
  bool Same = Context.hasSameType(LTy, RTy);
6776
0
  if (Same && LVK == RVK && LVK != VK_PRValue &&
6777
0
      LHS.get()->isOrdinaryOrBitFieldObject() &&
6778
0
      RHS.get()->isOrdinaryOrBitFieldObject()) {
6779
0
    VK = LHS.get()->getValueKind();
6780
0
    if (LHS.get()->getObjectKind() == OK_BitField ||
6781
0
        RHS.get()->getObjectKind() == OK_BitField)
6782
0
      OK = OK_BitField;
6783
0
    return Context.getCommonSugaredType(LTy, RTy);
6784
0
  }
6785
6786
  // C++11 [expr.cond]p5
6787
  //   Otherwise, the result is a prvalue. If the second and third operands
6788
  //   do not have the same type, and either has (cv) class type, ...
6789
0
  if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
6790
    //   ... overload resolution is used to determine the conversions (if any)
6791
    //   to be applied to the operands. If the overload resolution fails, the
6792
    //   program is ill-formed.
6793
0
    if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
6794
0
      return QualType();
6795
0
  }
6796
6797
  // C++11 [expr.cond]p6
6798
  //   Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
6799
  //   conversions are performed on the second and third operands.
6800
0
  LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6801
0
  RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6802
0
  if (LHS.isInvalid() || RHS.isInvalid())
6803
0
    return QualType();
6804
0
  LTy = LHS.get()->getType();
6805
0
  RTy = RHS.get()->getType();
6806
6807
  //   After those conversions, one of the following shall hold:
6808
  //   -- The second and third operands have the same type; the result
6809
  //      is of that type. If the operands have class type, the result
6810
  //      is a prvalue temporary of the result type, which is
6811
  //      copy-initialized from either the second operand or the third
6812
  //      operand depending on the value of the first operand.
6813
0
  if (Context.hasSameType(LTy, RTy)) {
6814
0
    if (LTy->isRecordType()) {
6815
      // The operands have class type. Make a temporary copy.
6816
0
      ExprResult LHSCopy = PerformCopyInitialization(
6817
0
          InitializedEntity::InitializeTemporary(LTy), SourceLocation(), LHS);
6818
0
      if (LHSCopy.isInvalid())
6819
0
        return QualType();
6820
6821
0
      ExprResult RHSCopy = PerformCopyInitialization(
6822
0
          InitializedEntity::InitializeTemporary(RTy), SourceLocation(), RHS);
6823
0
      if (RHSCopy.isInvalid())
6824
0
        return QualType();
6825
6826
0
      LHS = LHSCopy;
6827
0
      RHS = RHSCopy;
6828
0
    }
6829
0
    return Context.getCommonSugaredType(LTy, RTy);
6830
0
  }
6831
6832
  // Extension: conditional operator involving vector types.
6833
0
  if (LTy->isVectorType() || RTy->isVectorType())
6834
0
    return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
6835
0
                               /*AllowBothBool*/ true,
6836
0
                               /*AllowBoolConversions*/ false,
6837
0
                               /*AllowBoolOperation*/ false,
6838
0
                               /*ReportInvalid*/ true);
6839
6840
  //   -- The second and third operands have arithmetic or enumeration type;
6841
  //      the usual arithmetic conversions are performed to bring them to a
6842
  //      common type, and the result is of that type.
6843
0
  if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
6844
0
    QualType ResTy =
6845
0
        UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
6846
0
    if (LHS.isInvalid() || RHS.isInvalid())
6847
0
      return QualType();
6848
0
    if (ResTy.isNull()) {
6849
0
      Diag(QuestionLoc,
6850
0
           diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
6851
0
        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6852
0
      return QualType();
6853
0
    }
6854
6855
0
    LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6856
0
    RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6857
6858
0
    return ResTy;
6859
0
  }
6860
6861
  //   -- The second and third operands have pointer type, or one has pointer
6862
  //      type and the other is a null pointer constant, or both are null
6863
  //      pointer constants, at least one of which is non-integral; pointer
6864
  //      conversions and qualification conversions are performed to bring them
6865
  //      to their composite pointer type. The result is of the composite
6866
  //      pointer type.
6867
  //   -- The second and third operands have pointer to member type, or one has
6868
  //      pointer to member type and the other is a null pointer constant;
6869
  //      pointer to member conversions and qualification conversions are
6870
  //      performed to bring them to a common type, whose cv-qualification
6871
  //      shall match the cv-qualification of either the second or the third
6872
  //      operand. The result is of the common type.
6873
0
  QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
6874
0
  if (!Composite.isNull())
6875
0
    return Composite;
6876
6877
  // Similarly, attempt to find composite type of two objective-c pointers.
6878
0
  Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
6879
0
  if (LHS.isInvalid() || RHS.isInvalid())
6880
0
    return QualType();
6881
0
  if (!Composite.isNull())
6882
0
    return Composite;
6883
6884
  // Check if we are using a null with a non-pointer type.
6885
0
  if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6886
0
    return QualType();
6887
6888
0
  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6889
0
    << LHS.get()->getType() << RHS.get()->getType()
6890
0
    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6891
0
  return QualType();
6892
0
}
6893
6894
/// Find a merged pointer type and convert the two expressions to it.
6895
///
6896
/// This finds the composite pointer type for \p E1 and \p E2 according to
6897
/// C++2a [expr.type]p3. It converts both expressions to this type and returns
6898
/// it.  It does not emit diagnostics (FIXME: that's not true if \p ConvertArgs
6899
/// is \c true).
6900
///
6901
/// \param Loc The location of the operator requiring these two expressions to
6902
/// be converted to the composite pointer type.
6903
///
6904
/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
6905
QualType Sema::FindCompositePointerType(SourceLocation Loc,
6906
                                        Expr *&E1, Expr *&E2,
6907
0
                                        bool ConvertArgs) {
6908
0
  assert(getLangOpts().CPlusPlus && "This function assumes C++");
6909
6910
  // C++1z [expr]p14:
6911
  //   The composite pointer type of two operands p1 and p2 having types T1
6912
  //   and T2
6913
0
  QualType T1 = E1->getType(), T2 = E2->getType();
6914
6915
  //   where at least one is a pointer or pointer to member type or
6916
  //   std::nullptr_t is:
6917
0
  bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
6918
0
                         T1->isNullPtrType();
6919
0
  bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
6920
0
                         T2->isNullPtrType();
6921
0
  if (!T1IsPointerLike && !T2IsPointerLike)
6922
0
    return QualType();
6923
6924
  //   - if both p1 and p2 are null pointer constants, std::nullptr_t;
6925
  // This can't actually happen, following the standard, but we also use this
6926
  // to implement the end of [expr.conv], which hits this case.
6927
  //
6928
  //   - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6929
0
  if (T1IsPointerLike &&
6930
0
      E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
6931
0
    if (ConvertArgs)
6932
0
      E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
6933
0
                                         ? CK_NullToMemberPointer
6934
0
                                         : CK_NullToPointer).get();
6935
0
    return T1;
6936
0
  }
6937
0
  if (T2IsPointerLike &&
6938
0
      E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
6939
0
    if (ConvertArgs)
6940
0
      E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
6941
0
                                         ? CK_NullToMemberPointer
6942
0
                                         : CK_NullToPointer).get();
6943
0
    return T2;
6944
0
  }
6945
6946
  // Now both have to be pointers or member pointers.
6947
0
  if (!T1IsPointerLike || !T2IsPointerLike)
6948
0
    return QualType();
6949
0
  assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
6950
0
         "nullptr_t should be a null pointer constant");
6951
6952
0
  struct Step {
6953
0
    enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K;
6954
    // Qualifiers to apply under the step kind.
6955
0
    Qualifiers Quals;
6956
    /// The class for a pointer-to-member; a constant array type with a bound
6957
    /// (if any) for an array.
6958
0
    const Type *ClassOrBound;
6959
6960
0
    Step(Kind K, const Type *ClassOrBound = nullptr)
6961
0
        : K(K), ClassOrBound(ClassOrBound) {}
6962
0
    QualType rebuild(ASTContext &Ctx, QualType T) const {
6963
0
      T = Ctx.getQualifiedType(T, Quals);
6964
0
      switch (K) {
6965
0
      case Pointer:
6966
0
        return Ctx.getPointerType(T);
6967
0
      case MemberPointer:
6968
0
        return Ctx.getMemberPointerType(T, ClassOrBound);
6969
0
      case ObjCPointer:
6970
0
        return Ctx.getObjCObjectPointerType(T);
6971
0
      case Array:
6972
0
        if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound))
6973
0
          return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr,
6974
0
                                          ArraySizeModifier::Normal, 0);
6975
0
        else
6976
0
          return Ctx.getIncompleteArrayType(T, ArraySizeModifier::Normal, 0);
6977
0
      }
6978
0
      llvm_unreachable("unknown step kind");
6979
0
    }
6980
0
  };
6981
6982
0
  SmallVector<Step, 8> Steps;
6983
6984
  //  - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6985
  //    is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6986
  //    the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6987
  //    respectively;
6988
  //  - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
6989
  //    to member of C2 of type cv2 U2" for some non-function type U, where
6990
  //    C1 is reference-related to C2 or C2 is reference-related to C1, the
6991
  //    cv-combined type of T2 and T1 or the cv-combined type of T1 and T2,
6992
  //    respectively;
6993
  //  - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6994
  //    T2;
6995
  //
6996
  // Dismantle T1 and T2 to simultaneously determine whether they are similar
6997
  // and to prepare to form the cv-combined type if so.
6998
0
  QualType Composite1 = T1;
6999
0
  QualType Composite2 = T2;
7000
0
  unsigned NeedConstBefore = 0;
7001
0
  while (true) {
7002
0
    assert(!Composite1.isNull() && !Composite2.isNull());
7003
7004
0
    Qualifiers Q1, Q2;
7005
0
    Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1);
7006
0
    Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2);
7007
7008
    // Top-level qualifiers are ignored. Merge at all lower levels.
7009
0
    if (!Steps.empty()) {
7010
      // Find the qualifier union: (approximately) the unique minimal set of
7011
      // qualifiers that is compatible with both types.
7012
0
      Qualifiers Quals = Qualifiers::fromCVRUMask(Q1.getCVRUQualifiers() |
7013
0
                                                  Q2.getCVRUQualifiers());
7014
7015
      // Under one level of pointer or pointer-to-member, we can change to an
7016
      // unambiguous compatible address space.
7017
0
      if (Q1.getAddressSpace() == Q2.getAddressSpace()) {
7018
0
        Quals.setAddressSpace(Q1.getAddressSpace());
7019
0
      } else if (Steps.size() == 1) {
7020
0
        bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2);
7021
0
        bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1);
7022
0
        if (MaybeQ1 == MaybeQ2) {
7023
          // Exception for ptr size address spaces. Should be able to choose
7024
          // either address space during comparison.
7025
0
          if (isPtrSizeAddressSpace(Q1.getAddressSpace()) ||
7026
0
              isPtrSizeAddressSpace(Q2.getAddressSpace()))
7027
0
            MaybeQ1 = true;
7028
0
          else
7029
0
            return QualType(); // No unique best address space.
7030
0
        }
7031
0
        Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace()
7032
0
                                      : Q2.getAddressSpace());
7033
0
      } else {
7034
0
        return QualType();
7035
0
      }
7036
7037
      // FIXME: In C, we merge __strong and none to __strong at the top level.
7038
0
      if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr())
7039
0
        Quals.setObjCGCAttr(Q1.getObjCGCAttr());
7040
0
      else if (T1->isVoidPointerType() || T2->isVoidPointerType())
7041
0
        assert(Steps.size() == 1);
7042
0
      else
7043
0
        return QualType();
7044
7045
      // Mismatched lifetime qualifiers never compatibly include each other.
7046
0
      if (Q1.getObjCLifetime() == Q2.getObjCLifetime())
7047
0
        Quals.setObjCLifetime(Q1.getObjCLifetime());
7048
0
      else if (T1->isVoidPointerType() || T2->isVoidPointerType())
7049
0
        assert(Steps.size() == 1);
7050
0
      else
7051
0
        return QualType();
7052
7053
0
      Steps.back().Quals = Quals;
7054
0
      if (Q1 != Quals || Q2 != Quals)
7055
0
        NeedConstBefore = Steps.size() - 1;
7056
0
    }
7057
7058
    // FIXME: Can we unify the following with UnwrapSimilarTypes?
7059
7060
0
    const ArrayType *Arr1, *Arr2;
7061
0
    if ((Arr1 = Context.getAsArrayType(Composite1)) &&
7062
0
        (Arr2 = Context.getAsArrayType(Composite2))) {
7063
0
      auto *CAT1 = dyn_cast<ConstantArrayType>(Arr1);
7064
0
      auto *CAT2 = dyn_cast<ConstantArrayType>(Arr2);
7065
0
      if (CAT1 && CAT2 && CAT1->getSize() == CAT2->getSize()) {
7066
0
        Composite1 = Arr1->getElementType();
7067
0
        Composite2 = Arr2->getElementType();
7068
0
        Steps.emplace_back(Step::Array, CAT1);
7069
0
        continue;
7070
0
      }
7071
0
      bool IAT1 = isa<IncompleteArrayType>(Arr1);
7072
0
      bool IAT2 = isa<IncompleteArrayType>(Arr2);
7073
0
      if ((IAT1 && IAT2) ||
7074
0
          (getLangOpts().CPlusPlus20 && (IAT1 != IAT2) &&
7075
0
           ((bool)CAT1 != (bool)CAT2) &&
7076
0
           (Steps.empty() || Steps.back().K != Step::Array))) {
7077
        // In C++20 onwards, we can unify an array of N T with an array of
7078
        // a different or unknown bound. But we can't form an array whose
7079
        // element type is an array of unknown bound by doing so.
7080
0
        Composite1 = Arr1->getElementType();
7081
0
        Composite2 = Arr2->getElementType();
7082
0
        Steps.emplace_back(Step::Array);
7083
0
        if (CAT1 || CAT2)
7084
0
          NeedConstBefore = Steps.size();
7085
0
        continue;
7086
0
      }
7087
0
    }
7088
7089
0
    const PointerType *Ptr1, *Ptr2;
7090
0
    if ((Ptr1 = Composite1->getAs<PointerType>()) &&
7091
0
        (Ptr2 = Composite2->getAs<PointerType>())) {
7092
0
      Composite1 = Ptr1->getPointeeType();
7093
0
      Composite2 = Ptr2->getPointeeType();
7094
0
      Steps.emplace_back(Step::Pointer);
7095
0
      continue;
7096
0
    }
7097
7098
0
    const ObjCObjectPointerType *ObjPtr1, *ObjPtr2;
7099
0
    if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) &&
7100
0
        (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) {
7101
0
      Composite1 = ObjPtr1->getPointeeType();
7102
0
      Composite2 = ObjPtr2->getPointeeType();
7103
0
      Steps.emplace_back(Step::ObjCPointer);
7104
0
      continue;
7105
0
    }
7106
7107
0
    const MemberPointerType *MemPtr1, *MemPtr2;
7108
0
    if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
7109
0
        (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
7110
0
      Composite1 = MemPtr1->getPointeeType();
7111
0
      Composite2 = MemPtr2->getPointeeType();
7112
7113
      // At the top level, we can perform a base-to-derived pointer-to-member
7114
      // conversion:
7115
      //
7116
      //  - [...] where C1 is reference-related to C2 or C2 is
7117
      //    reference-related to C1
7118
      //
7119
      // (Note that the only kinds of reference-relatedness in scope here are
7120
      // "same type or derived from".) At any other level, the class must
7121
      // exactly match.
7122
0
      const Type *Class = nullptr;
7123
0
      QualType Cls1(MemPtr1->getClass(), 0);
7124
0
      QualType Cls2(MemPtr2->getClass(), 0);
7125
0
      if (Context.hasSameType(Cls1, Cls2))
7126
0
        Class = MemPtr1->getClass();
7127
0
      else if (Steps.empty())
7128
0
        Class = IsDerivedFrom(Loc, Cls1, Cls2) ? MemPtr1->getClass() :
7129
0
                IsDerivedFrom(Loc, Cls2, Cls1) ? MemPtr2->getClass() : nullptr;
7130
0
      if (!Class)
7131
0
        return QualType();
7132
7133
0
      Steps.emplace_back(Step::MemberPointer, Class);
7134
0
      continue;
7135
0
    }
7136
7137
    // Special case: at the top level, we can decompose an Objective-C pointer
7138
    // and a 'cv void *'. Unify the qualifiers.
7139
0
    if (Steps.empty() && ((Composite1->isVoidPointerType() &&
7140
0
                           Composite2->isObjCObjectPointerType()) ||
7141
0
                          (Composite1->isObjCObjectPointerType() &&
7142
0
                           Composite2->isVoidPointerType()))) {
7143
0
      Composite1 = Composite1->getPointeeType();
7144
0
      Composite2 = Composite2->getPointeeType();
7145
0
      Steps.emplace_back(Step::Pointer);
7146
0
      continue;
7147
0
    }
7148
7149
    // FIXME: block pointer types?
7150
7151
    // Cannot unwrap any more types.
7152
0
    break;
7153
0
  }
7154
7155
  //  - if T1 or T2 is "pointer to noexcept function" and the other type is
7156
  //    "pointer to function", where the function types are otherwise the same,
7157
  //    "pointer to function";
7158
  //  - if T1 or T2 is "pointer to member of C1 of type function", the other
7159
  //    type is "pointer to member of C2 of type noexcept function", and C1
7160
  //    is reference-related to C2 or C2 is reference-related to C1, where
7161
  //    the function types are otherwise the same, "pointer to member of C2 of
7162
  //    type function" or "pointer to member of C1 of type function",
7163
  //    respectively;
7164
  //
7165
  // We also support 'noreturn' here, so as a Clang extension we generalize the
7166
  // above to:
7167
  //
7168
  //  - [Clang] If T1 and T2 are both of type "pointer to function" or
7169
  //    "pointer to member function" and the pointee types can be unified
7170
  //    by a function pointer conversion, that conversion is applied
7171
  //    before checking the following rules.
7172
  //
7173
  // We've already unwrapped down to the function types, and we want to merge
7174
  // rather than just convert, so do this ourselves rather than calling
7175
  // IsFunctionConversion.
7176
  //
7177
  // FIXME: In order to match the standard wording as closely as possible, we
7178
  // currently only do this under a single level of pointers. Ideally, we would
7179
  // allow this in general, and set NeedConstBefore to the relevant depth on
7180
  // the side(s) where we changed anything. If we permit that, we should also
7181
  // consider this conversion when determining type similarity and model it as
7182
  // a qualification conversion.
7183
0
  if (Steps.size() == 1) {
7184
0
    if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
7185
0
      if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
7186
0
        FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
7187
0
        FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
7188
7189
        // The result is noreturn if both operands are.
7190
0
        bool Noreturn =
7191
0
            EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
7192
0
        EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
7193
0
        EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
7194
7195
        // The result is nothrow if both operands are.
7196
0
        SmallVector<QualType, 8> ExceptionTypeStorage;
7197
0
        EPI1.ExceptionSpec = EPI2.ExceptionSpec = Context.mergeExceptionSpecs(
7198
0
            EPI1.ExceptionSpec, EPI2.ExceptionSpec, ExceptionTypeStorage,
7199
0
            getLangOpts().CPlusPlus17);
7200
7201
0
        Composite1 = Context.getFunctionType(FPT1->getReturnType(),
7202
0
                                             FPT1->getParamTypes(), EPI1);
7203
0
        Composite2 = Context.getFunctionType(FPT2->getReturnType(),
7204
0
                                             FPT2->getParamTypes(), EPI2);
7205
0
      }
7206
0
    }
7207
0
  }
7208
7209
  // There are some more conversions we can perform under exactly one pointer.
7210
0
  if (Steps.size() == 1 && Steps.front().K == Step::Pointer &&
7211
0
      !Context.hasSameType(Composite1, Composite2)) {
7212
    //  - if T1 or T2 is "pointer to cv1 void" and the other type is
7213
    //    "pointer to cv2 T", where T is an object type or void,
7214
    //    "pointer to cv12 void", where cv12 is the union of cv1 and cv2;
7215
0
    if (Composite1->isVoidType() && Composite2->isObjectType())
7216
0
      Composite2 = Composite1;
7217
0
    else if (Composite2->isVoidType() && Composite1->isObjectType())
7218
0
      Composite1 = Composite2;
7219
    //  - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
7220
    //    is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
7221
    //    the cv-combined type of T1 and T2 or the cv-combined type of T2 and
7222
    //    T1, respectively;
7223
    //
7224
    // The "similar type" handling covers all of this except for the "T1 is a
7225
    // base class of T2" case in the definition of reference-related.
7226
0
    else if (IsDerivedFrom(Loc, Composite1, Composite2))
7227
0
      Composite1 = Composite2;
7228
0
    else if (IsDerivedFrom(Loc, Composite2, Composite1))
7229
0
      Composite2 = Composite1;
7230
0
  }
7231
7232
  // At this point, either the inner types are the same or we have failed to
7233
  // find a composite pointer type.
7234
0
  if (!Context.hasSameType(Composite1, Composite2))
7235
0
    return QualType();
7236
7237
  // Per C++ [conv.qual]p3, add 'const' to every level before the last
7238
  // differing qualifier.
7239
0
  for (unsigned I = 0; I != NeedConstBefore; ++I)
7240
0
    Steps[I].Quals.addConst();
7241
7242
  // Rebuild the composite type.
7243
0
  QualType Composite = Context.getCommonSugaredType(Composite1, Composite2);
7244
0
  for (auto &S : llvm::reverse(Steps))
7245
0
    Composite = S.rebuild(Context, Composite);
7246
7247
0
  if (ConvertArgs) {
7248
    // Convert the expressions to the composite pointer type.
7249
0
    InitializedEntity Entity =
7250
0
        InitializedEntity::InitializeTemporary(Composite);
7251
0
    InitializationKind Kind =
7252
0
        InitializationKind::CreateCopy(Loc, SourceLocation());
7253
7254
0
    InitializationSequence E1ToC(*this, Entity, Kind, E1);
7255
0
    if (!E1ToC)
7256
0
      return QualType();
7257
7258
0
    InitializationSequence E2ToC(*this, Entity, Kind, E2);
7259
0
    if (!E2ToC)
7260
0
      return QualType();
7261
7262
    // FIXME: Let the caller know if these fail to avoid duplicate diagnostics.
7263
0
    ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1);
7264
0
    if (E1Result.isInvalid())
7265
0
      return QualType();
7266
0
    E1 = E1Result.get();
7267
7268
0
    ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2);
7269
0
    if (E2Result.isInvalid())
7270
0
      return QualType();
7271
0
    E2 = E2Result.get();
7272
0
  }
7273
7274
0
  return Composite;
7275
0
}
7276
7277
0
ExprResult Sema::MaybeBindToTemporary(Expr *E) {
7278
0
  if (!E)
7279
0
    return ExprError();
7280
7281
0
  assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
7282
7283
  // If the result is a glvalue, we shouldn't bind it.
7284
0
  if (E->isGLValue())
7285
0
    return E;
7286
7287
  // In ARC, calls that return a retainable type can return retained,
7288
  // in which case we have to insert a consuming cast.
7289
0
  if (getLangOpts().ObjCAutoRefCount &&
7290
0
      E->getType()->isObjCRetainableType()) {
7291
7292
0
    bool ReturnsRetained;
7293
7294
    // For actual calls, we compute this by examining the type of the
7295
    // called value.
7296
0
    if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
7297
0
      Expr *Callee = Call->getCallee()->IgnoreParens();
7298
0
      QualType T = Callee->getType();
7299
7300
0
      if (T == Context.BoundMemberTy) {
7301
        // Handle pointer-to-members.
7302
0
        if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
7303
0
          T = BinOp->getRHS()->getType();
7304
0
        else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
7305
0
          T = Mem->getMemberDecl()->getType();
7306
0
      }
7307
7308
0
      if (const PointerType *Ptr = T->getAs<PointerType>())
7309
0
        T = Ptr->getPointeeType();
7310
0
      else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
7311
0
        T = Ptr->getPointeeType();
7312
0
      else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
7313
0
        T = MemPtr->getPointeeType();
7314
7315
0
      auto *FTy = T->castAs<FunctionType>();
7316
0
      ReturnsRetained = FTy->getExtInfo().getProducesResult();
7317
7318
    // ActOnStmtExpr arranges things so that StmtExprs of retainable
7319
    // type always produce a +1 object.
7320
0
    } else if (isa<StmtExpr>(E)) {
7321
0
      ReturnsRetained = true;
7322
7323
    // We hit this case with the lambda conversion-to-block optimization;
7324
    // we don't want any extra casts here.
7325
0
    } else if (isa<CastExpr>(E) &&
7326
0
               isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
7327
0
      return E;
7328
7329
    // For message sends and property references, we try to find an
7330
    // actual method.  FIXME: we should infer retention by selector in
7331
    // cases where we don't have an actual method.
7332
0
    } else {
7333
0
      ObjCMethodDecl *D = nullptr;
7334
0
      if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
7335
0
        D = Send->getMethodDecl();
7336
0
      } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
7337
0
        D = BoxedExpr->getBoxingMethod();
7338
0
      } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
7339
        // Don't do reclaims if we're using the zero-element array
7340
        // constant.
7341
0
        if (ArrayLit->getNumElements() == 0 &&
7342
0
            Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
7343
0
          return E;
7344
7345
0
        D = ArrayLit->getArrayWithObjectsMethod();
7346
0
      } else if (ObjCDictionaryLiteral *DictLit
7347
0
                                        = dyn_cast<ObjCDictionaryLiteral>(E)) {
7348
        // Don't do reclaims if we're using the zero-element dictionary
7349
        // constant.
7350
0
        if (DictLit->getNumElements() == 0 &&
7351
0
            Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
7352
0
          return E;
7353
7354
0
        D = DictLit->getDictWithObjectsMethod();
7355
0
      }
7356
7357
0
      ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
7358
7359
      // Don't do reclaims on performSelector calls; despite their
7360
      // return type, the invoked method doesn't necessarily actually
7361
      // return an object.
7362
0
      if (!ReturnsRetained &&
7363
0
          D && D->getMethodFamily() == OMF_performSelector)
7364
0
        return E;
7365
0
    }
7366
7367
    // Don't reclaim an object of Class type.
7368
0
    if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
7369
0
      return E;
7370
7371
0
    Cleanup.setExprNeedsCleanups(true);
7372
7373
0
    CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
7374
0
                                   : CK_ARCReclaimReturnedObject);
7375
0
    return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
7376
0
                                    VK_PRValue, FPOptionsOverride());
7377
0
  }
7378
7379
0
  if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
7380
0
    Cleanup.setExprNeedsCleanups(true);
7381
7382
0
  if (!getLangOpts().CPlusPlus)
7383
0
    return E;
7384
7385
  // Search for the base element type (cf. ASTContext::getBaseElementType) with
7386
  // a fast path for the common case that the type is directly a RecordType.
7387
0
  const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
7388
0
  const RecordType *RT = nullptr;
7389
0
  while (!RT) {
7390
0
    switch (T->getTypeClass()) {
7391
0
    case Type::Record:
7392
0
      RT = cast<RecordType>(T);
7393
0
      break;
7394
0
    case Type::ConstantArray:
7395
0
    case Type::IncompleteArray:
7396
0
    case Type::VariableArray:
7397
0
    case Type::DependentSizedArray:
7398
0
      T = cast<ArrayType>(T)->getElementType().getTypePtr();
7399
0
      break;
7400
0
    default:
7401
0
      return E;
7402
0
    }
7403
0
  }
7404
7405
  // That should be enough to guarantee that this type is complete, if we're
7406
  // not processing a decltype expression.
7407
0
  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
7408
0
  if (RD->isInvalidDecl() || RD->isDependentContext())
7409
0
    return E;
7410
7411
0
  bool IsDecltype = ExprEvalContexts.back().ExprContext ==
7412
0
                    ExpressionEvaluationContextRecord::EK_Decltype;
7413
0
  CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
7414
7415
0
  if (Destructor) {
7416
0
    MarkFunctionReferenced(E->getExprLoc(), Destructor);
7417
0
    CheckDestructorAccess(E->getExprLoc(), Destructor,
7418
0
                          PDiag(diag::err_access_dtor_temp)
7419
0
                            << E->getType());
7420
0
    if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
7421
0
      return ExprError();
7422
7423
    // If destructor is trivial, we can avoid the extra copy.
7424
0
    if (Destructor->isTrivial())
7425
0
      return E;
7426
7427
    // We need a cleanup, but we don't need to remember the temporary.
7428
0
    Cleanup.setExprNeedsCleanups(true);
7429
0
  }
7430
7431
0
  CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
7432
0
  CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
7433
7434
0
  if (IsDecltype)
7435
0
    ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
7436
7437
0
  return Bind;
7438
0
}
7439
7440
ExprResult
7441
20
Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
7442
20
  if (SubExpr.isInvalid())
7443
0
    return ExprError();
7444
7445
20
  return MaybeCreateExprWithCleanups(SubExpr.get());
7446
20
}
7447
7448
20
Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
7449
20
  assert(SubExpr && "subexpression can't be null!");
7450
7451
0
  CleanupVarDeclMarking();
7452
7453
20
  unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
7454
20
  assert(ExprCleanupObjects.size() >= FirstCleanup);
7455
0
  assert(Cleanup.exprNeedsCleanups() ||
7456
20
         ExprCleanupObjects.size() == FirstCleanup);
7457
20
  if (!Cleanup.exprNeedsCleanups())
7458
20
    return SubExpr;
7459
7460
0
  auto Cleanups = llvm::ArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
7461
0
                                 ExprCleanupObjects.size() - FirstCleanup);
7462
7463
0
  auto *E = ExprWithCleanups::Create(
7464
0
      Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
7465
0
  DiscardCleanupsInEvaluationContext();
7466
7467
0
  return E;
7468
20
}
7469
7470
0
Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
7471
0
  assert(SubStmt && "sub-statement can't be null!");
7472
7473
0
  CleanupVarDeclMarking();
7474
7475
0
  if (!Cleanup.exprNeedsCleanups())
7476
0
    return SubStmt;
7477
7478
  // FIXME: In order to attach the temporaries, wrap the statement into
7479
  // a StmtExpr; currently this is only used for asm statements.
7480
  // This is hacky, either create a new CXXStmtWithTemporaries statement or
7481
  // a new AsmStmtWithTemporaries.
7482
0
  CompoundStmt *CompStmt =
7483
0
      CompoundStmt::Create(Context, SubStmt, FPOptionsOverride(),
7484
0
                           SourceLocation(), SourceLocation());
7485
0
  Expr *E = new (Context)
7486
0
      StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), SourceLocation(),
7487
0
               /*FIXME TemplateDepth=*/0);
7488
0
  return MaybeCreateExprWithCleanups(E);
7489
0
}
7490
7491
/// Process the expression contained within a decltype. For such expressions,
7492
/// certain semantic checks on temporaries are delayed until this point, and
7493
/// are omitted for the 'topmost' call in the decltype expression. If the
7494
/// topmost call bound a temporary, strip that temporary off the expression.
7495
0
ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
7496
0
  assert(ExprEvalContexts.back().ExprContext ==
7497
0
             ExpressionEvaluationContextRecord::EK_Decltype &&
7498
0
         "not in a decltype expression");
7499
7500
0
  ExprResult Result = CheckPlaceholderExpr(E);
7501
0
  if (Result.isInvalid())
7502
0
    return ExprError();
7503
0
  E = Result.get();
7504
7505
  // C++11 [expr.call]p11:
7506
  //   If a function call is a prvalue of object type,
7507
  // -- if the function call is either
7508
  //   -- the operand of a decltype-specifier, or
7509
  //   -- the right operand of a comma operator that is the operand of a
7510
  //      decltype-specifier,
7511
  //   a temporary object is not introduced for the prvalue.
7512
7513
  // Recursively rebuild ParenExprs and comma expressions to strip out the
7514
  // outermost CXXBindTemporaryExpr, if any.
7515
0
  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
7516
0
    ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
7517
0
    if (SubExpr.isInvalid())
7518
0
      return ExprError();
7519
0
    if (SubExpr.get() == PE->getSubExpr())
7520
0
      return E;
7521
0
    return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
7522
0
  }
7523
0
  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7524
0
    if (BO->getOpcode() == BO_Comma) {
7525
0
      ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
7526
0
      if (RHS.isInvalid())
7527
0
        return ExprError();
7528
0
      if (RHS.get() == BO->getRHS())
7529
0
        return E;
7530
0
      return BinaryOperator::Create(Context, BO->getLHS(), RHS.get(), BO_Comma,
7531
0
                                    BO->getType(), BO->getValueKind(),
7532
0
                                    BO->getObjectKind(), BO->getOperatorLoc(),
7533
0
                                    BO->getFPFeatures());
7534
0
    }
7535
0
  }
7536
7537
0
  CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
7538
0
  CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
7539
0
                              : nullptr;
7540
0
  if (TopCall)
7541
0
    E = TopCall;
7542
0
  else
7543
0
    TopBind = nullptr;
7544
7545
  // Disable the special decltype handling now.
7546
0
  ExprEvalContexts.back().ExprContext =
7547
0
      ExpressionEvaluationContextRecord::EK_Other;
7548
7549
0
  Result = CheckUnevaluatedOperand(E);
7550
0
  if (Result.isInvalid())
7551
0
    return ExprError();
7552
0
  E = Result.get();
7553
7554
  // In MS mode, don't perform any extra checking of call return types within a
7555
  // decltype expression.
7556
0
  if (getLangOpts().MSVCCompat)
7557
0
    return E;
7558
7559
  // Perform the semantic checks we delayed until this point.
7560
0
  for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
7561
0
       I != N; ++I) {
7562
0
    CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
7563
0
    if (Call == TopCall)
7564
0
      continue;
7565
7566
0
    if (CheckCallReturnType(Call->getCallReturnType(Context),
7567
0
                            Call->getBeginLoc(), Call, Call->getDirectCallee()))
7568
0
      return ExprError();
7569
0
  }
7570
7571
  // Now all relevant types are complete, check the destructors are accessible
7572
  // and non-deleted, and annotate them on the temporaries.
7573
0
  for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
7574
0
       I != N; ++I) {
7575
0
    CXXBindTemporaryExpr *Bind =
7576
0
      ExprEvalContexts.back().DelayedDecltypeBinds[I];
7577
0
    if (Bind == TopBind)
7578
0
      continue;
7579
7580
0
    CXXTemporary *Temp = Bind->getTemporary();
7581
7582
0
    CXXRecordDecl *RD =
7583
0
      Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7584
0
    CXXDestructorDecl *Destructor = LookupDestructor(RD);
7585
0
    Temp->setDestructor(Destructor);
7586
7587
0
    MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
7588
0
    CheckDestructorAccess(Bind->getExprLoc(), Destructor,
7589
0
                          PDiag(diag::err_access_dtor_temp)
7590
0
                            << Bind->getType());
7591
0
    if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
7592
0
      return ExprError();
7593
7594
    // We need a cleanup, but we don't need to remember the temporary.
7595
0
    Cleanup.setExprNeedsCleanups(true);
7596
0
  }
7597
7598
  // Possibly strip off the top CXXBindTemporaryExpr.
7599
0
  return E;
7600
0
}
7601
7602
/// Note a set of 'operator->' functions that were used for a member access.
7603
static void noteOperatorArrows(Sema &S,
7604
0
                               ArrayRef<FunctionDecl *> OperatorArrows) {
7605
0
  unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
7606
  // FIXME: Make this configurable?
7607
0
  unsigned Limit = 9;
7608
0
  if (OperatorArrows.size() > Limit) {
7609
    // Produce Limit-1 normal notes and one 'skipping' note.
7610
0
    SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
7611
0
    SkipCount = OperatorArrows.size() - (Limit - 1);
7612
0
  }
7613
7614
0
  for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
7615
0
    if (I == SkipStart) {
7616
0
      S.Diag(OperatorArrows[I]->getLocation(),
7617
0
             diag::note_operator_arrows_suppressed)
7618
0
          << SkipCount;
7619
0
      I += SkipCount;
7620
0
    } else {
7621
0
      S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
7622
0
          << OperatorArrows[I]->getCallResultType();
7623
0
      ++I;
7624
0
    }
7625
0
  }
7626
0
}
7627
7628
ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
7629
                                              SourceLocation OpLoc,
7630
                                              tok::TokenKind OpKind,
7631
                                              ParsedType &ObjectType,
7632
2
                                              bool &MayBePseudoDestructor) {
7633
  // Since this might be a postfix expression, get rid of ParenListExprs.
7634
2
  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
7635
2
  if (Result.isInvalid()) return ExprError();
7636
2
  Base = Result.get();
7637
7638
2
  Result = CheckPlaceholderExpr(Base);
7639
2
  if (Result.isInvalid()) return ExprError();
7640
2
  Base = Result.get();
7641
7642
2
  QualType BaseType = Base->getType();
7643
2
  MayBePseudoDestructor = false;
7644
2
  if (BaseType->isDependentType()) {
7645
    // If we have a pointer to a dependent type and are using the -> operator,
7646
    // the object type is the type that the pointer points to. We might still
7647
    // have enough information about that type to do something useful.
7648
2
    if (OpKind == tok::arrow)
7649
0
      if (const PointerType *Ptr = BaseType->getAs<PointerType>())
7650
0
        BaseType = Ptr->getPointeeType();
7651
7652
2
    ObjectType = ParsedType::make(BaseType);
7653
2
    MayBePseudoDestructor = true;
7654
2
    return Base;
7655
2
  }
7656
7657
  // C++ [over.match.oper]p8:
7658
  //   [...] When operator->returns, the operator-> is applied  to the value
7659
  //   returned, with the original second operand.
7660
0
  if (OpKind == tok::arrow) {
7661
0
    QualType StartingType = BaseType;
7662
0
    bool NoArrowOperatorFound = false;
7663
0
    bool FirstIteration = true;
7664
0
    FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
7665
    // The set of types we've considered so far.
7666
0
    llvm::SmallPtrSet<CanQualType,8> CTypes;
7667
0
    SmallVector<FunctionDecl*, 8> OperatorArrows;
7668
0
    CTypes.insert(Context.getCanonicalType(BaseType));
7669
7670
0
    while (BaseType->isRecordType()) {
7671
0
      if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
7672
0
        Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
7673
0
          << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
7674
0
        noteOperatorArrows(*this, OperatorArrows);
7675
0
        Diag(OpLoc, diag::note_operator_arrow_depth)
7676
0
          << getLangOpts().ArrowDepth;
7677
0
        return ExprError();
7678
0
      }
7679
7680
0
      Result = BuildOverloadedArrowExpr(
7681
0
          S, Base, OpLoc,
7682
          // When in a template specialization and on the first loop iteration,
7683
          // potentially give the default diagnostic (with the fixit in a
7684
          // separate note) instead of having the error reported back to here
7685
          // and giving a diagnostic with a fixit attached to the error itself.
7686
0
          (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
7687
0
              ? nullptr
7688
0
              : &NoArrowOperatorFound);
7689
0
      if (Result.isInvalid()) {
7690
0
        if (NoArrowOperatorFound) {
7691
0
          if (FirstIteration) {
7692
0
            Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7693
0
              << BaseType << 1 << Base->getSourceRange()
7694
0
              << FixItHint::CreateReplacement(OpLoc, ".");
7695
0
            OpKind = tok::period;
7696
0
            break;
7697
0
          }
7698
0
          Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
7699
0
            << BaseType << Base->getSourceRange();
7700
0
          CallExpr *CE = dyn_cast<CallExpr>(Base);
7701
0
          if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
7702
0
            Diag(CD->getBeginLoc(),
7703
0
                 diag::note_member_reference_arrow_from_operator_arrow);
7704
0
          }
7705
0
        }
7706
0
        return ExprError();
7707
0
      }
7708
0
      Base = Result.get();
7709
0
      if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
7710
0
        OperatorArrows.push_back(OpCall->getDirectCallee());
7711
0
      BaseType = Base->getType();
7712
0
      CanQualType CBaseType = Context.getCanonicalType(BaseType);
7713
0
      if (!CTypes.insert(CBaseType).second) {
7714
0
        Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
7715
0
        noteOperatorArrows(*this, OperatorArrows);
7716
0
        return ExprError();
7717
0
      }
7718
0
      FirstIteration = false;
7719
0
    }
7720
7721
0
    if (OpKind == tok::arrow) {
7722
0
      if (BaseType->isPointerType())
7723
0
        BaseType = BaseType->getPointeeType();
7724
0
      else if (auto *AT = Context.getAsArrayType(BaseType))
7725
0
        BaseType = AT->getElementType();
7726
0
    }
7727
0
  }
7728
7729
  // Objective-C properties allow "." access on Objective-C pointer types,
7730
  // so adjust the base type to the object type itself.
7731
0
  if (BaseType->isObjCObjectPointerType())
7732
0
    BaseType = BaseType->getPointeeType();
7733
7734
  // C++ [basic.lookup.classref]p2:
7735
  //   [...] If the type of the object expression is of pointer to scalar
7736
  //   type, the unqualified-id is looked up in the context of the complete
7737
  //   postfix-expression.
7738
  //
7739
  // This also indicates that we could be parsing a pseudo-destructor-name.
7740
  // Note that Objective-C class and object types can be pseudo-destructor
7741
  // expressions or normal member (ivar or property) access expressions, and
7742
  // it's legal for the type to be incomplete if this is a pseudo-destructor
7743
  // call.  We'll do more incomplete-type checks later in the lookup process,
7744
  // so just skip this check for ObjC types.
7745
0
  if (!BaseType->isRecordType()) {
7746
0
    ObjectType = ParsedType::make(BaseType);
7747
0
    MayBePseudoDestructor = true;
7748
0
    return Base;
7749
0
  }
7750
7751
  // The object type must be complete (or dependent), or
7752
  // C++11 [expr.prim.general]p3:
7753
  //   Unlike the object expression in other contexts, *this is not required to
7754
  //   be of complete type for purposes of class member access (5.2.5) outside
7755
  //   the member function body.
7756
0
  if (!BaseType->isDependentType() &&
7757
0
      !isThisOutsideMemberFunctionBody(BaseType) &&
7758
0
      RequireCompleteType(OpLoc, BaseType,
7759
0
                          diag::err_incomplete_member_access)) {
7760
0
    return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base});
7761
0
  }
7762
7763
  // C++ [basic.lookup.classref]p2:
7764
  //   If the id-expression in a class member access (5.2.5) is an
7765
  //   unqualified-id, and the type of the object expression is of a class
7766
  //   type C (or of pointer to a class type C), the unqualified-id is looked
7767
  //   up in the scope of class C. [...]
7768
0
  ObjectType = ParsedType::make(BaseType);
7769
0
  return Base;
7770
0
}
7771
7772
static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base,
7773
0
                       tok::TokenKind &OpKind, SourceLocation OpLoc) {
7774
0
  if (Base->hasPlaceholderType()) {
7775
0
    ExprResult result = S.CheckPlaceholderExpr(Base);
7776
0
    if (result.isInvalid()) return true;
7777
0
    Base = result.get();
7778
0
  }
7779
0
  ObjectType = Base->getType();
7780
7781
  // C++ [expr.pseudo]p2:
7782
  //   The left-hand side of the dot operator shall be of scalar type. The
7783
  //   left-hand side of the arrow operator shall be of pointer to scalar type.
7784
  //   This scalar type is the object type.
7785
  // Note that this is rather different from the normal handling for the
7786
  // arrow operator.
7787
0
  if (OpKind == tok::arrow) {
7788
    // The operator requires a prvalue, so perform lvalue conversions.
7789
    // Only do this if we might plausibly end with a pointer, as otherwise
7790
    // this was likely to be intended to be a '.'.
7791
0
    if (ObjectType->isPointerType() || ObjectType->isArrayType() ||
7792
0
        ObjectType->isFunctionType()) {
7793
0
      ExprResult BaseResult = S.DefaultFunctionArrayLvalueConversion(Base);
7794
0
      if (BaseResult.isInvalid())
7795
0
        return true;
7796
0
      Base = BaseResult.get();
7797
0
      ObjectType = Base->getType();
7798
0
    }
7799
7800
0
    if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
7801
0
      ObjectType = Ptr->getPointeeType();
7802
0
    } else if (!Base->isTypeDependent()) {
7803
      // The user wrote "p->" when they probably meant "p."; fix it.
7804
0
      S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7805
0
        << ObjectType << true
7806
0
        << FixItHint::CreateReplacement(OpLoc, ".");
7807
0
      if (S.isSFINAEContext())
7808
0
        return true;
7809
7810
0
      OpKind = tok::period;
7811
0
    }
7812
0
  }
7813
7814
0
  return false;
7815
0
}
7816
7817
/// Check if it's ok to try and recover dot pseudo destructor calls on
7818
/// pointer objects.
7819
static bool
7820
canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
7821
0
                                                   QualType DestructedType) {
7822
  // If this is a record type, check if its destructor is callable.
7823
0
  if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
7824
0
    if (RD->hasDefinition())
7825
0
      if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
7826
0
        return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
7827
0
    return false;
7828
0
  }
7829
7830
  // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
7831
0
  return DestructedType->isDependentType() || DestructedType->isScalarType() ||
7832
0
         DestructedType->isVectorType();
7833
0
}
7834
7835
ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
7836
                                           SourceLocation OpLoc,
7837
                                           tok::TokenKind OpKind,
7838
                                           const CXXScopeSpec &SS,
7839
                                           TypeSourceInfo *ScopeTypeInfo,
7840
                                           SourceLocation CCLoc,
7841
                                           SourceLocation TildeLoc,
7842
0
                                         PseudoDestructorTypeStorage Destructed) {
7843
0
  TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
7844
7845
0
  QualType ObjectType;
7846
0
  if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7847
0
    return ExprError();
7848
7849
0
  if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
7850
0
      !ObjectType->isVectorType()) {
7851
0
    if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
7852
0
      Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
7853
0
    else {
7854
0
      Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
7855
0
        << ObjectType << Base->getSourceRange();
7856
0
      return ExprError();
7857
0
    }
7858
0
  }
7859
7860
  // C++ [expr.pseudo]p2:
7861
  //   [...] The cv-unqualified versions of the object type and of the type
7862
  //   designated by the pseudo-destructor-name shall be the same type.
7863
0
  if (DestructedTypeInfo) {
7864
0
    QualType DestructedType = DestructedTypeInfo->getType();
7865
0
    SourceLocation DestructedTypeStart =
7866
0
        DestructedTypeInfo->getTypeLoc().getBeginLoc();
7867
0
    if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
7868
0
      if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
7869
        // Detect dot pseudo destructor calls on pointer objects, e.g.:
7870
        //   Foo *foo;
7871
        //   foo.~Foo();
7872
0
        if (OpKind == tok::period && ObjectType->isPointerType() &&
7873
0
            Context.hasSameUnqualifiedType(DestructedType,
7874
0
                                           ObjectType->getPointeeType())) {
7875
0
          auto Diagnostic =
7876
0
              Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7877
0
              << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
7878
7879
          // Issue a fixit only when the destructor is valid.
7880
0
          if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
7881
0
                  *this, DestructedType))
7882
0
            Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
7883
7884
          // Recover by setting the object type to the destructed type and the
7885
          // operator to '->'.
7886
0
          ObjectType = DestructedType;
7887
0
          OpKind = tok::arrow;
7888
0
        } else {
7889
0
          Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
7890
0
              << ObjectType << DestructedType << Base->getSourceRange()
7891
0
              << DestructedTypeInfo->getTypeLoc().getSourceRange();
7892
7893
          // Recover by setting the destructed type to the object type.
7894
0
          DestructedType = ObjectType;
7895
0
          DestructedTypeInfo =
7896
0
              Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
7897
0
          Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7898
0
        }
7899
0
      } else if (DestructedType.getObjCLifetime() !=
7900
0
                                                ObjectType.getObjCLifetime()) {
7901
7902
0
        if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
7903
          // Okay: just pretend that the user provided the correctly-qualified
7904
          // type.
7905
0
        } else {
7906
0
          Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
7907
0
              << ObjectType << DestructedType << Base->getSourceRange()
7908
0
              << DestructedTypeInfo->getTypeLoc().getSourceRange();
7909
0
        }
7910
7911
        // Recover by setting the destructed type to the object type.
7912
0
        DestructedType = ObjectType;
7913
0
        DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
7914
0
                                                           DestructedTypeStart);
7915
0
        Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7916
0
      }
7917
0
    }
7918
0
  }
7919
7920
  // C++ [expr.pseudo]p2:
7921
  //   [...] Furthermore, the two type-names in a pseudo-destructor-name of the
7922
  //   form
7923
  //
7924
  //     ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
7925
  //
7926
  //   shall designate the same scalar type.
7927
0
  if (ScopeTypeInfo) {
7928
0
    QualType ScopeType = ScopeTypeInfo->getType();
7929
0
    if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
7930
0
        !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
7931
7932
0
      Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
7933
0
           diag::err_pseudo_dtor_type_mismatch)
7934
0
          << ObjectType << ScopeType << Base->getSourceRange()
7935
0
          << ScopeTypeInfo->getTypeLoc().getSourceRange();
7936
7937
0
      ScopeType = QualType();
7938
0
      ScopeTypeInfo = nullptr;
7939
0
    }
7940
0
  }
7941
7942
0
  Expr *Result
7943
0
    = new (Context) CXXPseudoDestructorExpr(Context, Base,
7944
0
                                            OpKind == tok::arrow, OpLoc,
7945
0
                                            SS.getWithLocInContext(Context),
7946
0
                                            ScopeTypeInfo,
7947
0
                                            CCLoc,
7948
0
                                            TildeLoc,
7949
0
                                            Destructed);
7950
7951
0
  return Result;
7952
0
}
7953
7954
ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7955
                                           SourceLocation OpLoc,
7956
                                           tok::TokenKind OpKind,
7957
                                           CXXScopeSpec &SS,
7958
                                           UnqualifiedId &FirstTypeName,
7959
                                           SourceLocation CCLoc,
7960
                                           SourceLocation TildeLoc,
7961
0
                                           UnqualifiedId &SecondTypeName) {
7962
0
  assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7963
0
          FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
7964
0
         "Invalid first type name in pseudo-destructor");
7965
0
  assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7966
0
          SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
7967
0
         "Invalid second type name in pseudo-destructor");
7968
7969
0
  QualType ObjectType;
7970
0
  if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7971
0
    return ExprError();
7972
7973
  // Compute the object type that we should use for name lookup purposes. Only
7974
  // record types and dependent types matter.
7975
0
  ParsedType ObjectTypePtrForLookup;
7976
0
  if (!SS.isSet()) {
7977
0
    if (ObjectType->isRecordType())
7978
0
      ObjectTypePtrForLookup = ParsedType::make(ObjectType);
7979
0
    else if (ObjectType->isDependentType())
7980
0
      ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
7981
0
  }
7982
7983
  // Convert the name of the type being destructed (following the ~) into a
7984
  // type (with source-location information).
7985
0
  QualType DestructedType;
7986
0
  TypeSourceInfo *DestructedTypeInfo = nullptr;
7987
0
  PseudoDestructorTypeStorage Destructed;
7988
0
  if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7989
0
    ParsedType T = getTypeName(*SecondTypeName.Identifier,
7990
0
                               SecondTypeName.StartLocation,
7991
0
                               S, &SS, true, false, ObjectTypePtrForLookup,
7992
0
                               /*IsCtorOrDtorName*/true);
7993
0
    if (!T &&
7994
0
        ((SS.isSet() && !computeDeclContext(SS, false)) ||
7995
0
         (!SS.isSet() && ObjectType->isDependentType()))) {
7996
      // The name of the type being destroyed is a dependent name, and we
7997
      // couldn't find anything useful in scope. Just store the identifier and
7998
      // it's location, and we'll perform (qualified) name lookup again at
7999
      // template instantiation time.
8000
0
      Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
8001
0
                                               SecondTypeName.StartLocation);
8002
0
    } else if (!T) {
8003
0
      Diag(SecondTypeName.StartLocation,
8004
0
           diag::err_pseudo_dtor_destructor_non_type)
8005
0
        << SecondTypeName.Identifier << ObjectType;
8006
0
      if (isSFINAEContext())
8007
0
        return ExprError();
8008
8009
      // Recover by assuming we had the right type all along.
8010
0
      DestructedType = ObjectType;
8011
0
    } else
8012
0
      DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
8013
0
  } else {
8014
    // Resolve the template-id to a type.
8015
0
    TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
8016
0
    ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8017
0
                                       TemplateId->NumArgs);
8018
0
    TypeResult T = ActOnTemplateIdType(S,
8019
0
                                       SS,
8020
0
                                       TemplateId->TemplateKWLoc,
8021
0
                                       TemplateId->Template,
8022
0
                                       TemplateId->Name,
8023
0
                                       TemplateId->TemplateNameLoc,
8024
0
                                       TemplateId->LAngleLoc,
8025
0
                                       TemplateArgsPtr,
8026
0
                                       TemplateId->RAngleLoc,
8027
0
                                       /*IsCtorOrDtorName*/true);
8028
0
    if (T.isInvalid() || !T.get()) {
8029
      // Recover by assuming we had the right type all along.
8030
0
      DestructedType = ObjectType;
8031
0
    } else
8032
0
      DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
8033
0
  }
8034
8035
  // If we've performed some kind of recovery, (re-)build the type source
8036
  // information.
8037
0
  if (!DestructedType.isNull()) {
8038
0
    if (!DestructedTypeInfo)
8039
0
      DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
8040
0
                                                  SecondTypeName.StartLocation);
8041
0
    Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
8042
0
  }
8043
8044
  // Convert the name of the scope type (the type prior to '::') into a type.
8045
0
  TypeSourceInfo *ScopeTypeInfo = nullptr;
8046
0
  QualType ScopeType;
8047
0
  if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
8048
0
      FirstTypeName.Identifier) {
8049
0
    if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
8050
0
      ParsedType T = getTypeName(*FirstTypeName.Identifier,
8051
0
                                 FirstTypeName.StartLocation,
8052
0
                                 S, &SS, true, false, ObjectTypePtrForLookup,
8053
0
                                 /*IsCtorOrDtorName*/true);
8054
0
      if (!T) {
8055
0
        Diag(FirstTypeName.StartLocation,
8056
0
             diag::err_pseudo_dtor_destructor_non_type)
8057
0
          << FirstTypeName.Identifier << ObjectType;
8058
8059
0
        if (isSFINAEContext())
8060
0
          return ExprError();
8061
8062
        // Just drop this type. It's unnecessary anyway.
8063
0
        ScopeType = QualType();
8064
0
      } else
8065
0
        ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
8066
0
    } else {
8067
      // Resolve the template-id to a type.
8068
0
      TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
8069
0
      ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8070
0
                                         TemplateId->NumArgs);
8071
0
      TypeResult T = ActOnTemplateIdType(S,
8072
0
                                         SS,
8073
0
                                         TemplateId->TemplateKWLoc,
8074
0
                                         TemplateId->Template,
8075
0
                                         TemplateId->Name,
8076
0
                                         TemplateId->TemplateNameLoc,
8077
0
                                         TemplateId->LAngleLoc,
8078
0
                                         TemplateArgsPtr,
8079
0
                                         TemplateId->RAngleLoc,
8080
0
                                         /*IsCtorOrDtorName*/true);
8081
0
      if (T.isInvalid() || !T.get()) {
8082
        // Recover by dropping this type.
8083
0
        ScopeType = QualType();
8084
0
      } else
8085
0
        ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
8086
0
    }
8087
0
  }
8088
8089
0
  if (!ScopeType.isNull() && !ScopeTypeInfo)
8090
0
    ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
8091
0
                                                  FirstTypeName.StartLocation);
8092
8093
8094
0
  return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
8095
0
                                   ScopeTypeInfo, CCLoc, TildeLoc,
8096
0
                                   Destructed);
8097
0
}
8098
8099
ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
8100
                                           SourceLocation OpLoc,
8101
                                           tok::TokenKind OpKind,
8102
                                           SourceLocation TildeLoc,
8103
0
                                           const DeclSpec& DS) {
8104
0
  QualType ObjectType;
8105
0
  if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
8106
0
    return ExprError();
8107
8108
0
  if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
8109
0
    Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
8110
0
    return true;
8111
0
  }
8112
8113
0
  QualType T = BuildDecltypeType(DS.getRepAsExpr(), /*AsUnevaluated=*/false);
8114
8115
0
  TypeLocBuilder TLB;
8116
0
  DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
8117
0
  DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
8118
0
  DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd());
8119
0
  TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
8120
0
  PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
8121
8122
0
  return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
8123
0
                                   nullptr, SourceLocation(), TildeLoc,
8124
0
                                   Destructed);
8125
0
}
8126
8127
ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
8128
0
                                      SourceLocation RParen) {
8129
  // If the operand is an unresolved lookup expression, the expression is ill-
8130
  // formed per [over.over]p1, because overloaded function names cannot be used
8131
  // without arguments except in explicit contexts.
8132
0
  ExprResult R = CheckPlaceholderExpr(Operand);
8133
0
  if (R.isInvalid())
8134
0
    return R;
8135
8136
0
  R = CheckUnevaluatedOperand(R.get());
8137
0
  if (R.isInvalid())
8138
0
    return ExprError();
8139
8140
0
  Operand = R.get();
8141
8142
0
  if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() &&
8143
0
      Operand->HasSideEffects(Context, false)) {
8144
    // The expression operand for noexcept is in an unevaluated expression
8145
    // context, so side effects could result in unintended consequences.
8146
0
    Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
8147
0
  }
8148
8149
0
  CanThrowResult CanThrow = canThrow(Operand);
8150
0
  return new (Context)
8151
0
      CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
8152
0
}
8153
8154
ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
8155
0
                                   Expr *Operand, SourceLocation RParen) {
8156
0
  return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
8157
0
}
8158
8159
static void MaybeDecrementCount(
8160
0
    Expr *E, llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
8161
0
  DeclRefExpr *LHS = nullptr;
8162
0
  bool IsCompoundAssign = false;
8163
0
  bool isIncrementDecrementUnaryOp = false;
8164
0
  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8165
0
    if (BO->getLHS()->getType()->isDependentType() ||
8166
0
        BO->getRHS()->getType()->isDependentType()) {
8167
0
      if (BO->getOpcode() != BO_Assign)
8168
0
        return;
8169
0
    } else if (!BO->isAssignmentOp())
8170
0
      return;
8171
0
    else
8172
0
      IsCompoundAssign = BO->isCompoundAssignmentOp();
8173
0
    LHS = dyn_cast<DeclRefExpr>(BO->getLHS());
8174
0
  } else if (CXXOperatorCallExpr *COCE = dyn_cast<CXXOperatorCallExpr>(E)) {
8175
0
    if (COCE->getOperator() != OO_Equal)
8176
0
      return;
8177
0
    LHS = dyn_cast<DeclRefExpr>(COCE->getArg(0));
8178
0
  } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8179
0
    if (!UO->isIncrementDecrementOp())
8180
0
      return;
8181
0
    isIncrementDecrementUnaryOp = true;
8182
0
    LHS = dyn_cast<DeclRefExpr>(UO->getSubExpr());
8183
0
  }
8184
0
  if (!LHS)
8185
0
    return;
8186
0
  VarDecl *VD = dyn_cast<VarDecl>(LHS->getDecl());
8187
0
  if (!VD)
8188
0
    return;
8189
  // Don't decrement RefsMinusAssignments if volatile variable with compound
8190
  // assignment (+=, ...) or increment/decrement unary operator to avoid
8191
  // potential unused-but-set-variable warning.
8192
0
  if ((IsCompoundAssign || isIncrementDecrementUnaryOp) &&
8193
0
      VD->getType().isVolatileQualified())
8194
0
    return;
8195
0
  auto iter = RefsMinusAssignments.find(VD);
8196
0
  if (iter == RefsMinusAssignments.end())
8197
0
    return;
8198
0
  iter->getSecond()--;
8199
0
}
8200
8201
/// Perform the conversions required for an expression used in a
8202
/// context that ignores the result.
8203
0
ExprResult Sema::IgnoredValueConversions(Expr *E) {
8204
0
  MaybeDecrementCount(E, RefsMinusAssignments);
8205
8206
0
  if (E->hasPlaceholderType()) {
8207
0
    ExprResult result = CheckPlaceholderExpr(E);
8208
0
    if (result.isInvalid()) return E;
8209
0
    E = result.get();
8210
0
  }
8211
8212
  // C99 6.3.2.1:
8213
  //   [Except in specific positions,] an lvalue that does not have
8214
  //   array type is converted to the value stored in the
8215
  //   designated object (and is no longer an lvalue).
8216
0
  if (E->isPRValue()) {
8217
    // In C, function designators (i.e. expressions of function type)
8218
    // are r-values, but we still want to do function-to-pointer decay
8219
    // on them.  This is both technically correct and convenient for
8220
    // some clients.
8221
0
    if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
8222
0
      return DefaultFunctionArrayConversion(E);
8223
8224
0
    return E;
8225
0
  }
8226
8227
0
  if (getLangOpts().CPlusPlus) {
8228
    // The C++11 standard defines the notion of a discarded-value expression;
8229
    // normally, we don't need to do anything to handle it, but if it is a
8230
    // volatile lvalue with a special form, we perform an lvalue-to-rvalue
8231
    // conversion.
8232
0
    if (getLangOpts().CPlusPlus11 && E->isReadIfDiscardedInCPlusPlus11()) {
8233
0
      ExprResult Res = DefaultLvalueConversion(E);
8234
0
      if (Res.isInvalid())
8235
0
        return E;
8236
0
      E = Res.get();
8237
0
    } else {
8238
      // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
8239
      // it occurs as a discarded-value expression.
8240
0
      CheckUnusedVolatileAssignment(E);
8241
0
    }
8242
8243
    // C++1z:
8244
    //   If the expression is a prvalue after this optional conversion, the
8245
    //   temporary materialization conversion is applied.
8246
    //
8247
    // We skip this step: IR generation is able to synthesize the storage for
8248
    // itself in the aggregate case, and adding the extra node to the AST is
8249
    // just clutter.
8250
    // FIXME: We don't emit lifetime markers for the temporaries due to this.
8251
    // FIXME: Do any other AST consumers care about this?
8252
0
    return E;
8253
0
  }
8254
8255
  // GCC seems to also exclude expressions of incomplete enum type.
8256
0
  if (const EnumType *T = E->getType()->getAs<EnumType>()) {
8257
0
    if (!T->getDecl()->isComplete()) {
8258
      // FIXME: stupid workaround for a codegen bug!
8259
0
      E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
8260
0
      return E;
8261
0
    }
8262
0
  }
8263
8264
0
  ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
8265
0
  if (Res.isInvalid())
8266
0
    return E;
8267
0
  E = Res.get();
8268
8269
0
  if (!E->getType()->isVoidType())
8270
0
    RequireCompleteType(E->getExprLoc(), E->getType(),
8271
0
                        diag::err_incomplete_type);
8272
0
  return E;
8273
0
}
8274
8275
0
ExprResult Sema::CheckUnevaluatedOperand(Expr *E) {
8276
  // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
8277
  // it occurs as an unevaluated operand.
8278
0
  CheckUnusedVolatileAssignment(E);
8279
8280
0
  return E;
8281
0
}
8282
8283
// If we can unambiguously determine whether Var can never be used
8284
// in a constant expression, return true.
8285
//  - if the variable and its initializer are non-dependent, then
8286
//    we can unambiguously check if the variable is a constant expression.
8287
//  - if the initializer is not value dependent - we can determine whether
8288
//    it can be used to initialize a constant expression.  If Init can not
8289
//    be used to initialize a constant expression we conclude that Var can
8290
//    never be a constant expression.
8291
//  - FXIME: if the initializer is dependent, we can still do some analysis and
8292
//    identify certain cases unambiguously as non-const by using a Visitor:
8293
//      - such as those that involve odr-use of a ParmVarDecl, involve a new
8294
//        delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
8295
static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
8296
0
    ASTContext &Context) {
8297
0
  if (isa<ParmVarDecl>(Var)) return true;
8298
0
  const VarDecl *DefVD = nullptr;
8299
8300
  // If there is no initializer - this can not be a constant expression.
8301
0
  const Expr *Init = Var->getAnyInitializer(DefVD);
8302
0
  if (!Init)
8303
0
    return true;
8304
0
  assert(DefVD);
8305
0
  if (DefVD->isWeak())
8306
0
    return false;
8307
8308
0
  if (Var->getType()->isDependentType() || Init->isValueDependent()) {
8309
    // FIXME: Teach the constant evaluator to deal with the non-dependent parts
8310
    // of value-dependent expressions, and use it here to determine whether the
8311
    // initializer is a potential constant expression.
8312
0
    return false;
8313
0
  }
8314
8315
0
  return !Var->isUsableInConstantExpressions(Context);
8316
0
}
8317
8318
/// Check if the current lambda has any potential captures
8319
/// that must be captured by any of its enclosing lambdas that are ready to
8320
/// capture. If there is a lambda that can capture a nested
8321
/// potential-capture, go ahead and do so.  Also, check to see if any
8322
/// variables are uncaptureable or do not involve an odr-use so do not
8323
/// need to be captured.
8324
8325
static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
8326
0
    Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
8327
8328
0
  assert(!S.isUnevaluatedContext());
8329
0
  assert(S.CurContext->isDependentContext());
8330
0
#ifndef NDEBUG
8331
0
  DeclContext *DC = S.CurContext;
8332
0
  while (DC && isa<CapturedDecl>(DC))
8333
0
    DC = DC->getParent();
8334
0
  assert(
8335
0
      CurrentLSI->CallOperator == DC &&
8336
0
      "The current call operator must be synchronized with Sema's CurContext");
8337
0
#endif // NDEBUG
8338
8339
0
  const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
8340
8341
  // All the potentially captureable variables in the current nested
8342
  // lambda (within a generic outer lambda), must be captured by an
8343
  // outer lambda that is enclosed within a non-dependent context.
8344
0
  CurrentLSI->visitPotentialCaptures([&](ValueDecl *Var, Expr *VarExpr) {
8345
    // If the variable is clearly identified as non-odr-used and the full
8346
    // expression is not instantiation dependent, only then do we not
8347
    // need to check enclosing lambda's for speculative captures.
8348
    // For e.g.:
8349
    // Even though 'x' is not odr-used, it should be captured.
8350
    // int test() {
8351
    //   const int x = 10;
8352
    //   auto L = [=](auto a) {
8353
    //     (void) +x + a;
8354
    //   };
8355
    // }
8356
0
    if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
8357
0
        !IsFullExprInstantiationDependent)
8358
0
      return;
8359
8360
0
    VarDecl *UnderlyingVar = Var->getPotentiallyDecomposedVarDecl();
8361
0
    if (!UnderlyingVar)
8362
0
      return;
8363
8364
    // If we have a capture-capable lambda for the variable, go ahead and
8365
    // capture the variable in that lambda (and all its enclosing lambdas).
8366
0
    if (const std::optional<unsigned> Index =
8367
0
            getStackIndexOfNearestEnclosingCaptureCapableLambda(
8368
0
                S.FunctionScopes, Var, S))
8369
0
      S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(), *Index);
8370
0
    const bool IsVarNeverAConstantExpression =
8371
0
        VariableCanNeverBeAConstantExpression(UnderlyingVar, S.Context);
8372
0
    if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
8373
      // This full expression is not instantiation dependent or the variable
8374
      // can not be used in a constant expression - which means
8375
      // this variable must be odr-used here, so diagnose a
8376
      // capture violation early, if the variable is un-captureable.
8377
      // This is purely for diagnosing errors early.  Otherwise, this
8378
      // error would get diagnosed when the lambda becomes capture ready.
8379
0
      QualType CaptureType, DeclRefType;
8380
0
      SourceLocation ExprLoc = VarExpr->getExprLoc();
8381
0
      if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
8382
0
                          /*EllipsisLoc*/ SourceLocation(),
8383
0
                          /*BuildAndDiagnose*/false, CaptureType,
8384
0
                          DeclRefType, nullptr)) {
8385
        // We will never be able to capture this variable, and we need
8386
        // to be able to in any and all instantiations, so diagnose it.
8387
0
        S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
8388
0
                          /*EllipsisLoc*/ SourceLocation(),
8389
0
                          /*BuildAndDiagnose*/true, CaptureType,
8390
0
                          DeclRefType, nullptr);
8391
0
      }
8392
0
    }
8393
0
  });
8394
8395
  // Check if 'this' needs to be captured.
8396
0
  if (CurrentLSI->hasPotentialThisCapture()) {
8397
    // If we have a capture-capable lambda for 'this', go ahead and capture
8398
    // 'this' in that lambda (and all its enclosing lambdas).
8399
0
    if (const std::optional<unsigned> Index =
8400
0
            getStackIndexOfNearestEnclosingCaptureCapableLambda(
8401
0
                S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
8402
0
      const unsigned FunctionScopeIndexOfCapturableLambda = *Index;
8403
0
      S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
8404
0
                            /*Explicit*/ false, /*BuildAndDiagnose*/ true,
8405
0
                            &FunctionScopeIndexOfCapturableLambda);
8406
0
    }
8407
0
  }
8408
8409
  // Reset all the potential captures at the end of each full-expression.
8410
0
  CurrentLSI->clearPotentialCaptures();
8411
0
}
8412
8413
static ExprResult attemptRecovery(Sema &SemaRef,
8414
                                  const TypoCorrectionConsumer &Consumer,
8415
0
                                  const TypoCorrection &TC) {
8416
0
  LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
8417
0
                 Consumer.getLookupResult().getLookupKind());
8418
0
  const CXXScopeSpec *SS = Consumer.getSS();
8419
0
  CXXScopeSpec NewSS;
8420
8421
  // Use an approprate CXXScopeSpec for building the expr.
8422
0
  if (auto *NNS = TC.getCorrectionSpecifier())
8423
0
    NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
8424
0
  else if (SS && !TC.WillReplaceSpecifier())
8425
0
    NewSS = *SS;
8426
8427
0
  if (auto *ND = TC.getFoundDecl()) {
8428
0
    R.setLookupName(ND->getDeclName());
8429
0
    R.addDecl(ND);
8430
0
    if (ND->isCXXClassMember()) {
8431
      // Figure out the correct naming class to add to the LookupResult.
8432
0
      CXXRecordDecl *Record = nullptr;
8433
0
      if (auto *NNS = TC.getCorrectionSpecifier())
8434
0
        Record = NNS->getAsType()->getAsCXXRecordDecl();
8435
0
      if (!Record)
8436
0
        Record =
8437
0
            dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
8438
0
      if (Record)
8439
0
        R.setNamingClass(Record);
8440
8441
      // Detect and handle the case where the decl might be an implicit
8442
      // member.
8443
0
      bool MightBeImplicitMember;
8444
0
      if (!Consumer.isAddressOfOperand())
8445
0
        MightBeImplicitMember = true;
8446
0
      else if (!NewSS.isEmpty())
8447
0
        MightBeImplicitMember = false;
8448
0
      else if (R.isOverloadedResult())
8449
0
        MightBeImplicitMember = false;
8450
0
      else if (R.isUnresolvableResult())
8451
0
        MightBeImplicitMember = true;
8452
0
      else
8453
0
        MightBeImplicitMember = isa<FieldDecl>(ND) ||
8454
0
                                isa<IndirectFieldDecl>(ND) ||
8455
0
                                isa<MSPropertyDecl>(ND);
8456
8457
0
      if (MightBeImplicitMember)
8458
0
        return SemaRef.BuildPossibleImplicitMemberExpr(
8459
0
            NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
8460
0
            /*TemplateArgs*/ nullptr, /*S*/ nullptr);
8461
0
    } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
8462
0
      return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
8463
0
                                        Ivar->getIdentifier());
8464
0
    }
8465
0
  }
8466
8467
0
  return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
8468
0
                                          /*AcceptInvalidDecl*/ true);
8469
0
}
8470
8471
namespace {
8472
class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
8473
  llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
8474
8475
public:
8476
  explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
8477
63
      : TypoExprs(TypoExprs) {}
8478
68
  bool VisitTypoExpr(TypoExpr *TE) {
8479
68
    TypoExprs.insert(TE);
8480
68
    return true;
8481
68
  }
8482
};
8483
8484
class TransformTypos : public TreeTransform<TransformTypos> {
8485
  typedef TreeTransform<TransformTypos> BaseTransform;
8486
8487
  VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
8488
                     // process of being initialized.
8489
  llvm::function_ref<ExprResult(Expr *)> ExprFilter;
8490
  llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
8491
  llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
8492
  llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
8493
8494
  /// Emit diagnostics for all of the TypoExprs encountered.
8495
  ///
8496
  /// If the TypoExprs were successfully corrected, then the diagnostics should
8497
  /// suggest the corrections. Otherwise the diagnostics will not suggest
8498
  /// anything (having been passed an empty TypoCorrection).
8499
  ///
8500
  /// If we've failed to correct due to ambiguous corrections, we need to
8501
  /// be sure to pass empty corrections and replacements. Otherwise it's
8502
  /// possible that the Consumer has a TypoCorrection that failed to ambiguity
8503
  /// and we don't want to report those diagnostics.
8504
63
  void EmitAllDiagnostics(bool IsAmbiguous) {
8505
68
    for (TypoExpr *TE : TypoExprs) {
8506
68
      auto &State = SemaRef.getTypoExprState(TE);
8507
68
      if (State.DiagHandler) {
8508
68
        TypoCorrection TC = IsAmbiguous
8509
68
            ? TypoCorrection() : State.Consumer->getCurrentCorrection();
8510
68
        ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE];
8511
8512
        // Extract the NamedDecl from the transformed TypoExpr and add it to the
8513
        // TypoCorrection, replacing the existing decls. This ensures the right
8514
        // NamedDecl is used in diagnostics e.g. in the case where overload
8515
        // resolution was used to select one from several possible decls that
8516
        // had been stored in the TypoCorrection.
8517
68
        if (auto *ND = getDeclFromExpr(
8518
68
                Replacement.isInvalid() ? nullptr : Replacement.get()))
8519
0
          TC.setCorrectionDecl(ND);
8520
8521
68
        State.DiagHandler(TC);
8522
68
      }
8523
68
      SemaRef.clearDelayedTypo(TE);
8524
68
    }
8525
63
  }
8526
8527
  /// Try to advance the typo correction state of the first unfinished TypoExpr.
8528
  /// We allow advancement of the correction stream by removing it from the
8529
  /// TransformCache which allows `TransformTypoExpr` to advance during the
8530
  /// next transformation attempt.
8531
  ///
8532
  /// Any substitution attempts for the previous TypoExprs (which must have been
8533
  /// finished) will need to be retried since it's possible that they will now
8534
  /// be invalid given the latest advancement.
8535
  ///
8536
  /// We need to be sure that we're making progress - it's possible that the
8537
  /// tree is so malformed that the transform never makes it to the
8538
  /// `TransformTypoExpr`.
8539
  ///
8540
  /// Returns true if there are any untried correction combinations.
8541
63
  bool CheckAndAdvanceTypoExprCorrectionStreams() {
8542
63
    for (auto *TE : TypoExprs) {
8543
63
      auto &State = SemaRef.getTypoExprState(TE);
8544
63
      TransformCache.erase(TE);
8545
63
      if (!State.Consumer->hasMadeAnyCorrectionProgress())
8546
0
        return false;
8547
63
      if (!State.Consumer->finished())
8548
0
        return true;
8549
63
      State.Consumer->resetCorrectionStream();
8550
63
    }
8551
63
    return false;
8552
63
  }
8553
8554
68
  NamedDecl *getDeclFromExpr(Expr *E) {
8555
68
    if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
8556
0
      E = OverloadResolution[OE];
8557
8558
68
    if (!E)
8559
68
      return nullptr;
8560
0
    if (auto *DRE = dyn_cast<DeclRefExpr>(E))
8561
0
      return DRE->getFoundDecl();
8562
0
    if (auto *ME = dyn_cast<MemberExpr>(E))
8563
0
      return ME->getFoundDecl();
8564
    // FIXME: Add any other expr types that could be seen by the delayed typo
8565
    // correction TreeTransform for which the corresponding TypoCorrection could
8566
    // contain multiple decls.
8567
0
    return nullptr;
8568
0
  }
8569
8570
63
  ExprResult TryTransform(Expr *E) {
8571
63
    Sema::SFINAETrap Trap(SemaRef);
8572
63
    ExprResult Res = TransformExpr(E);
8573
63
    if (Trap.hasErrorOccurred() || Res.isInvalid())
8574
63
      return ExprError();
8575
8576
0
    return ExprFilter(Res.get());
8577
63
  }
8578
8579
  // Since correcting typos may intoduce new TypoExprs, this function
8580
  // checks for new TypoExprs and recurses if it finds any. Note that it will
8581
  // only succeed if it is able to correct all typos in the given expression.
8582
63
  ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) {
8583
63
    if (Res.isInvalid()) {
8584
63
      return Res;
8585
63
    }
8586
    // Check to see if any new TypoExprs were created. If so, we need to recurse
8587
    // to check their validity.
8588
0
    Expr *FixedExpr = Res.get();
8589
8590
0
    auto SavedTypoExprs = std::move(TypoExprs);
8591
0
    auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs);
8592
0
    TypoExprs.clear();
8593
0
    AmbiguousTypoExprs.clear();
8594
8595
0
    FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr);
8596
0
    if (!TypoExprs.empty()) {
8597
      // Recurse to handle newly created TypoExprs. If we're not able to
8598
      // handle them, discard these TypoExprs.
8599
0
      ExprResult RecurResult =
8600
0
          RecursiveTransformLoop(FixedExpr, IsAmbiguous);
8601
0
      if (RecurResult.isInvalid()) {
8602
0
        Res = ExprError();
8603
        // Recursive corrections didn't work, wipe them away and don't add
8604
        // them to the TypoExprs set. Remove them from Sema's TypoExpr list
8605
        // since we don't want to clear them twice. Note: it's possible the
8606
        // TypoExprs were created recursively and thus won't be in our
8607
        // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`.
8608
0
        auto &SemaTypoExprs = SemaRef.TypoExprs;
8609
0
        for (auto *TE : TypoExprs) {
8610
0
          TransformCache.erase(TE);
8611
0
          SemaRef.clearDelayedTypo(TE);
8612
8613
0
          auto SI = find(SemaTypoExprs, TE);
8614
0
          if (SI != SemaTypoExprs.end()) {
8615
0
            SemaTypoExprs.erase(SI);
8616
0
          }
8617
0
        }
8618
0
      } else {
8619
        // TypoExpr is valid: add newly created TypoExprs since we were
8620
        // able to correct them.
8621
0
        Res = RecurResult;
8622
0
        SavedTypoExprs.set_union(TypoExprs);
8623
0
      }
8624
0
    }
8625
8626
0
    TypoExprs = std::move(SavedTypoExprs);
8627
0
    AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs);
8628
8629
0
    return Res;
8630
63
  }
8631
8632
  // Try to transform the given expression, looping through the correction
8633
  // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`.
8634
  //
8635
  // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to
8636
  // true and this method immediately will return an `ExprError`.
8637
63
  ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) {
8638
63
    ExprResult Res;
8639
63
    auto SavedTypoExprs = std::move(SemaRef.TypoExprs);
8640
63
    SemaRef.TypoExprs.clear();
8641
8642
63
    while (true) {
8643
63
      Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8644
8645
      // Recursion encountered an ambiguous correction. This means that our
8646
      // correction itself is ambiguous, so stop now.
8647
63
      if (IsAmbiguous)
8648
0
        break;
8649
8650
      // If the transform is still valid after checking for any new typos,
8651
      // it's good to go.
8652
63
      if (!Res.isInvalid())
8653
0
        break;
8654
8655
      // The transform was invalid, see if we have any TypoExprs with untried
8656
      // correction candidates.
8657
63
      if (!CheckAndAdvanceTypoExprCorrectionStreams())
8658
63
        break;
8659
63
    }
8660
8661
    // If we found a valid result, double check to make sure it's not ambiguous.
8662
63
    if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) {
8663
0
      auto SavedTransformCache =
8664
0
          llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache);
8665
8666
      // Ensure none of the TypoExprs have multiple typo correction candidates
8667
      // with the same edit length that pass all the checks and filters.
8668
0
      while (!AmbiguousTypoExprs.empty()) {
8669
0
        auto TE  = AmbiguousTypoExprs.back();
8670
8671
        // TryTransform itself can create new Typos, adding them to the TypoExpr map
8672
        // and invalidating our TypoExprState, so always fetch it instead of storing.
8673
0
        SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition();
8674
8675
0
        TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection();
8676
0
        TypoCorrection Next;
8677
0
        do {
8678
          // Fetch the next correction by erasing the typo from the cache and calling
8679
          // `TryTransform` which will iterate through corrections in
8680
          // `TransformTypoExpr`.
8681
0
          TransformCache.erase(TE);
8682
0
          ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8683
8684
0
          if (!AmbigRes.isInvalid() || IsAmbiguous) {
8685
0
            SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream();
8686
0
            SavedTransformCache.erase(TE);
8687
0
            Res = ExprError();
8688
0
            IsAmbiguous = true;
8689
0
            break;
8690
0
          }
8691
0
        } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) &&
8692
0
                 Next.getEditDistance(false) == TC.getEditDistance(false));
8693
8694
0
        if (IsAmbiguous)
8695
0
          break;
8696
8697
0
        AmbiguousTypoExprs.remove(TE);
8698
0
        SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition();
8699
0
        TransformCache[TE] = SavedTransformCache[TE];
8700
0
      }
8701
0
      TransformCache = std::move(SavedTransformCache);
8702
0
    }
8703
8704
    // Wipe away any newly created TypoExprs that we don't know about. Since we
8705
    // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only
8706
    // possible if a `TypoExpr` is created during a transformation but then
8707
    // fails before we can discover it.
8708
63
    auto &SemaTypoExprs = SemaRef.TypoExprs;
8709
63
    for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) {
8710
0
      auto TE = *Iterator;
8711
0
      auto FI = find(TypoExprs, TE);
8712
0
      if (FI != TypoExprs.end()) {
8713
0
        Iterator++;
8714
0
        continue;
8715
0
      }
8716
0
      SemaRef.clearDelayedTypo(TE);
8717
0
      Iterator = SemaTypoExprs.erase(Iterator);
8718
0
    }
8719
63
    SemaRef.TypoExprs = std::move(SavedTypoExprs);
8720
8721
63
    return Res;
8722
63
  }
8723
8724
public:
8725
  TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
8726
63
      : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
8727
8728
  ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
8729
                                   MultiExprArg Args,
8730
                                   SourceLocation RParenLoc,
8731
0
                                   Expr *ExecConfig = nullptr) {
8732
0
    auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
8733
0
                                                 RParenLoc, ExecConfig);
8734
0
    if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
8735
0
      if (Result.isUsable()) {
8736
0
        Expr *ResultCall = Result.get();
8737
0
        if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
8738
0
          ResultCall = BE->getSubExpr();
8739
0
        if (auto *CE = dyn_cast<CallExpr>(ResultCall))
8740
0
          OverloadResolution[OE] = CE->getCallee();
8741
0
      }
8742
0
    }
8743
0
    return Result;
8744
0
  }
8745
8746
0
  ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
8747
8748
0
  ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
8749
8750
63
  ExprResult Transform(Expr *E) {
8751
63
    bool IsAmbiguous = false;
8752
63
    ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous);
8753
8754
63
    if (!Res.isUsable())
8755
63
      FindTypoExprs(TypoExprs).TraverseStmt(E);
8756
8757
63
    EmitAllDiagnostics(IsAmbiguous);
8758
8759
63
    return Res;
8760
63
  }
8761
8762
63
  ExprResult TransformTypoExpr(TypoExpr *E) {
8763
    // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
8764
    // cached transformation result if there is one and the TypoExpr isn't the
8765
    // first one that was encountered.
8766
63
    auto &CacheEntry = TransformCache[E];
8767
63
    if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
8768
0
      return CacheEntry;
8769
0
    }
8770
8771
63
    auto &State = SemaRef.getTypoExprState(E);
8772
63
    assert(State.Consumer && "Cannot transform a cleared TypoExpr");
8773
8774
    // For the first TypoExpr and an uncached TypoExpr, find the next likely
8775
    // typo correction and return it.
8776
63
    while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
8777
0
      if (InitDecl && TC.getFoundDecl() == InitDecl)
8778
0
        continue;
8779
      // FIXME: If we would typo-correct to an invalid declaration, it's
8780
      // probably best to just suppress all errors from this typo correction.
8781
0
      ExprResult NE = State.RecoveryHandler ?
8782
0
          State.RecoveryHandler(SemaRef, E, TC) :
8783
0
          attemptRecovery(SemaRef, *State.Consumer, TC);
8784
0
      if (!NE.isInvalid()) {
8785
        // Check whether there may be a second viable correction with the same
8786
        // edit distance; if so, remember this TypoExpr may have an ambiguous
8787
        // correction so it can be more thoroughly vetted later.
8788
0
        TypoCorrection Next;
8789
0
        if ((Next = State.Consumer->peekNextCorrection()) &&
8790
0
            Next.getEditDistance(false) == TC.getEditDistance(false)) {
8791
0
          AmbiguousTypoExprs.insert(E);
8792
0
        } else {
8793
0
          AmbiguousTypoExprs.remove(E);
8794
0
        }
8795
0
        assert(!NE.isUnset() &&
8796
0
               "Typo was transformed into a valid-but-null ExprResult");
8797
0
        return CacheEntry = NE;
8798
0
      }
8799
0
    }
8800
63
    return CacheEntry = ExprError();
8801
63
  }
8802
};
8803
}
8804
8805
ExprResult
8806
Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
8807
                                bool RecoverUncorrectedTypos,
8808
492
                                llvm::function_ref<ExprResult(Expr *)> Filter) {
8809
  // If the current evaluation context indicates there are uncorrected typos
8810
  // and the current expression isn't guaranteed to not have typos, try to
8811
  // resolve any TypoExpr nodes that might be in the expression.
8812
492
  if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
8813
492
      (E->isTypeDependent() || E->isValueDependent() ||
8814
63
       E->isInstantiationDependent())) {
8815
63
    auto TyposResolved = DelayedTypos.size();
8816
63
    auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
8817
63
    TyposResolved -= DelayedTypos.size();
8818
63
    if (Result.isInvalid() || Result.get() != E) {
8819
63
      ExprEvalContexts.back().NumTypos -= TyposResolved;
8820
63
      if (Result.isInvalid() && RecoverUncorrectedTypos) {
8821
6
        struct TyposReplace : TreeTransform<TyposReplace> {
8822
6
          TyposReplace(Sema &SemaRef) : TreeTransform(SemaRef) {}
8823
6
          ExprResult TransformTypoExpr(clang::TypoExpr *E) {
8824
6
            return this->SemaRef.CreateRecoveryExpr(E->getBeginLoc(),
8825
6
                                                    E->getEndLoc(), {});
8826
6
          }
8827
6
        } TT(*this);
8828
6
        return TT.TransformExpr(E);
8829
6
      }
8830
57
      return Result;
8831
63
    }
8832
0
    assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
8833
0
  }
8834
429
  return E;
8835
492
}
8836
8837
ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
8838
                                     bool DiscardedValue, bool IsConstexpr,
8839
20
                                     bool IsTemplateArgument) {
8840
20
  ExprResult FullExpr = FE;
8841
8842
20
  if (!FullExpr.get())
8843
0
    return ExprError();
8844
8845
20
  if (!IsTemplateArgument && DiagnoseUnexpandedParameterPack(FullExpr.get()))
8846
0
    return ExprError();
8847
8848
20
  if (DiscardedValue) {
8849
    // Top-level expressions default to 'id' when we're in a debugger.
8850
0
    if (getLangOpts().DebuggerCastResultToId &&
8851
0
        FullExpr.get()->getType() == Context.UnknownAnyTy) {
8852
0
      FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
8853
0
      if (FullExpr.isInvalid())
8854
0
        return ExprError();
8855
0
    }
8856
8857
0
    FullExpr = CheckPlaceholderExpr(FullExpr.get());
8858
0
    if (FullExpr.isInvalid())
8859
0
      return ExprError();
8860
8861
0
    FullExpr = IgnoredValueConversions(FullExpr.get());
8862
0
    if (FullExpr.isInvalid())
8863
0
      return ExprError();
8864
8865
0
    DiagnoseUnusedExprResult(FullExpr.get(), diag::warn_unused_expr);
8866
0
  }
8867
8868
20
  FullExpr = CorrectDelayedTyposInExpr(FullExpr.get(), /*InitDecl=*/nullptr,
8869
20
                                       /*RecoverUncorrectedTypos=*/true);
8870
20
  if (FullExpr.isInvalid())
8871
0
    return ExprError();
8872
8873
20
  CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
8874
8875
  // At the end of this full expression (which could be a deeply nested
8876
  // lambda), if there is a potential capture within the nested lambda,
8877
  // have the outer capture-able lambda try and capture it.
8878
  // Consider the following code:
8879
  // void f(int, int);
8880
  // void f(const int&, double);
8881
  // void foo() {
8882
  //  const int x = 10, y = 20;
8883
  //  auto L = [=](auto a) {
8884
  //      auto M = [=](auto b) {
8885
  //         f(x, b); <-- requires x to be captured by L and M
8886
  //         f(y, a); <-- requires y to be captured by L, but not all Ms
8887
  //      };
8888
  //   };
8889
  // }
8890
8891
  // FIXME: Also consider what happens for something like this that involves
8892
  // the gnu-extension statement-expressions or even lambda-init-captures:
8893
  //   void f() {
8894
  //     const int n = 0;
8895
  //     auto L =  [&](auto a) {
8896
  //       +n + ({ 0; a; });
8897
  //     };
8898
  //   }
8899
  //
8900
  // Here, we see +n, and then the full-expression 0; ends, so we don't
8901
  // capture n (and instead remove it from our list of potential captures),
8902
  // and then the full-expression +n + ({ 0; }); ends, but it's too late
8903
  // for us to see that we need to capture n after all.
8904
8905
20
  LambdaScopeInfo *const CurrentLSI =
8906
20
      getCurLambda(/*IgnoreCapturedRegions=*/true);
8907
  // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
8908
  // even if CurContext is not a lambda call operator. Refer to that Bug Report
8909
  // for an example of the code that might cause this asynchrony.
8910
  // By ensuring we are in the context of a lambda's call operator
8911
  // we can fix the bug (we only need to check whether we need to capture
8912
  // if we are within a lambda's body); but per the comments in that
8913
  // PR, a proper fix would entail :
8914
  //   "Alternative suggestion:
8915
  //   - Add to Sema an integer holding the smallest (outermost) scope
8916
  //     index that we are *lexically* within, and save/restore/set to
8917
  //     FunctionScopes.size() in InstantiatingTemplate's
8918
  //     constructor/destructor.
8919
  //  - Teach the handful of places that iterate over FunctionScopes to
8920
  //    stop at the outermost enclosing lexical scope."
8921
20
  DeclContext *DC = CurContext;
8922
20
  while (DC && isa<CapturedDecl>(DC))
8923
0
    DC = DC->getParent();
8924
20
  const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
8925
20
  if (IsInLambdaDeclContext && CurrentLSI &&
8926
20
      CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
8927
0
    CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
8928
0
                                                              *this);
8929
20
  return MaybeCreateExprWithCleanups(FullExpr);
8930
20
}
8931
8932
0
StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
8933
0
  if (!FullStmt) return StmtError();
8934
8935
0
  return MaybeCreateStmtWithCleanups(FullStmt);
8936
0
}
8937
8938
Sema::IfExistsResult
8939
Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
8940
                                   CXXScopeSpec &SS,
8941
0
                                   const DeclarationNameInfo &TargetNameInfo) {
8942
0
  DeclarationName TargetName = TargetNameInfo.getName();
8943
0
  if (!TargetName)
8944
0
    return IER_DoesNotExist;
8945
8946
  // If the name itself is dependent, then the result is dependent.
8947
0
  if (TargetName.isDependentName())
8948
0
    return IER_Dependent;
8949
8950
  // Do the redeclaration lookup in the current scope.
8951
0
  LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
8952
0
                 Sema::NotForRedeclaration);
8953
0
  LookupParsedName(R, S, &SS);
8954
0
  R.suppressDiagnostics();
8955
8956
0
  switch (R.getResultKind()) {
8957
0
  case LookupResult::Found:
8958
0
  case LookupResult::FoundOverloaded:
8959
0
  case LookupResult::FoundUnresolvedValue:
8960
0
  case LookupResult::Ambiguous:
8961
0
    return IER_Exists;
8962
8963
0
  case LookupResult::NotFound:
8964
0
    return IER_DoesNotExist;
8965
8966
0
  case LookupResult::NotFoundInCurrentInstantiation:
8967
0
    return IER_Dependent;
8968
0
  }
8969
8970
0
  llvm_unreachable("Invalid LookupResult Kind!");
8971
0
}
8972
8973
Sema::IfExistsResult
8974
Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
8975
                                   bool IsIfExists, CXXScopeSpec &SS,
8976
0
                                   UnqualifiedId &Name) {
8977
0
  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
8978
8979
  // Check for an unexpanded parameter pack.
8980
0
  auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
8981
0
  if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
8982
0
      DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
8983
0
    return IER_Error;
8984
8985
0
  return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
8986
0
}
8987
8988
0
concepts::Requirement *Sema::ActOnSimpleRequirement(Expr *E) {
8989
0
  return BuildExprRequirement(E, /*IsSimple=*/true,
8990
0
                              /*NoexceptLoc=*/SourceLocation(),
8991
0
                              /*ReturnTypeRequirement=*/{});
8992
0
}
8993
8994
concepts::Requirement *
8995
Sema::ActOnTypeRequirement(SourceLocation TypenameKWLoc, CXXScopeSpec &SS,
8996
                           SourceLocation NameLoc, IdentifierInfo *TypeName,
8997
0
                           TemplateIdAnnotation *TemplateId) {
8998
0
  assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) &&
8999
0
         "Exactly one of TypeName and TemplateId must be specified.");
9000
0
  TypeSourceInfo *TSI = nullptr;
9001
0
  if (TypeName) {
9002
0
    QualType T =
9003
0
        CheckTypenameType(ElaboratedTypeKeyword::Typename, TypenameKWLoc,
9004
0
                          SS.getWithLocInContext(Context), *TypeName, NameLoc,
9005
0
                          &TSI, /*DeducedTSTContext=*/false);
9006
0
    if (T.isNull())
9007
0
      return nullptr;
9008
0
  } else {
9009
0
    ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(),
9010
0
                               TemplateId->NumArgs);
9011
0
    TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS,
9012
0
                                     TemplateId->TemplateKWLoc,
9013
0
                                     TemplateId->Template, TemplateId->Name,
9014
0
                                     TemplateId->TemplateNameLoc,
9015
0
                                     TemplateId->LAngleLoc, ArgsPtr,
9016
0
                                     TemplateId->RAngleLoc);
9017
0
    if (T.isInvalid())
9018
0
      return nullptr;
9019
0
    if (GetTypeFromParser(T.get(), &TSI).isNull())
9020
0
      return nullptr;
9021
0
  }
9022
0
  return BuildTypeRequirement(TSI);
9023
0
}
9024
9025
concepts::Requirement *
9026
0
Sema::ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc) {
9027
0
  return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc,
9028
0
                              /*ReturnTypeRequirement=*/{});
9029
0
}
9030
9031
concepts::Requirement *
9032
Sema::ActOnCompoundRequirement(
9033
    Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
9034
0
    TemplateIdAnnotation *TypeConstraint, unsigned Depth) {
9035
  // C++2a [expr.prim.req.compound] p1.3.3
9036
  //   [..] the expression is deduced against an invented function template
9037
  //   F [...] F is a void function template with a single type template
9038
  //   parameter T declared with the constrained-parameter. Form a new
9039
  //   cv-qualifier-seq cv by taking the union of const and volatile specifiers
9040
  //   around the constrained-parameter. F has a single parameter whose
9041
  //   type-specifier is cv T followed by the abstract-declarator. [...]
9042
  //
9043
  // The cv part is done in the calling function - we get the concept with
9044
  // arguments and the abstract declarator with the correct CV qualification and
9045
  // have to synthesize T and the single parameter of F.
9046
0
  auto &II = Context.Idents.get("expr-type");
9047
0
  auto *TParam = TemplateTypeParmDecl::Create(Context, CurContext,
9048
0
                                              SourceLocation(),
9049
0
                                              SourceLocation(), Depth,
9050
0
                                              /*Index=*/0, &II,
9051
0
                                              /*Typename=*/true,
9052
0
                                              /*ParameterPack=*/false,
9053
0
                                              /*HasTypeConstraint=*/true);
9054
9055
0
  if (BuildTypeConstraint(SS, TypeConstraint, TParam,
9056
0
                          /*EllipsisLoc=*/SourceLocation(),
9057
0
                          /*AllowUnexpandedPack=*/true))
9058
    // Just produce a requirement with no type requirements.
9059
0
    return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {});
9060
9061
0
  auto *TPL = TemplateParameterList::Create(Context, SourceLocation(),
9062
0
                                            SourceLocation(),
9063
0
                                            ArrayRef<NamedDecl *>(TParam),
9064
0
                                            SourceLocation(),
9065
0
                                            /*RequiresClause=*/nullptr);
9066
0
  return BuildExprRequirement(
9067
0
      E, /*IsSimple=*/false, NoexceptLoc,
9068
0
      concepts::ExprRequirement::ReturnTypeRequirement(TPL));
9069
0
}
9070
9071
concepts::ExprRequirement *
9072
Sema::BuildExprRequirement(
9073
    Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
9074
0
    concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {
9075
0
  auto Status = concepts::ExprRequirement::SS_Satisfied;
9076
0
  ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr;
9077
0
  if (E->isInstantiationDependent() || E->getType()->isPlaceholderType() ||
9078
0
      ReturnTypeRequirement.isDependent())
9079
0
    Status = concepts::ExprRequirement::SS_Dependent;
9080
0
  else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can)
9081
0
    Status = concepts::ExprRequirement::SS_NoexceptNotMet;
9082
0
  else if (ReturnTypeRequirement.isSubstitutionFailure())
9083
0
    Status = concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure;
9084
0
  else if (ReturnTypeRequirement.isTypeConstraint()) {
9085
    // C++2a [expr.prim.req]p1.3.3
9086
    //     The immediately-declared constraint ([temp]) of decltype((E)) shall
9087
    //     be satisfied.
9088
0
    TemplateParameterList *TPL =
9089
0
        ReturnTypeRequirement.getTypeConstraintTemplateParameterList();
9090
0
    QualType MatchedType =
9091
0
        Context.getReferenceQualifiedType(E).getCanonicalType();
9092
0
    llvm::SmallVector<TemplateArgument, 1> Args;
9093
0
    Args.push_back(TemplateArgument(MatchedType));
9094
9095
0
    auto *Param = cast<TemplateTypeParmDecl>(TPL->getParam(0));
9096
9097
0
    TemplateArgumentList TAL(TemplateArgumentList::OnStack, Args);
9098
0
    MultiLevelTemplateArgumentList MLTAL(Param, TAL.asArray(),
9099
0
                                         /*Final=*/false);
9100
0
    MLTAL.addOuterRetainedLevels(TPL->getDepth());
9101
0
    const TypeConstraint *TC = Param->getTypeConstraint();
9102
0
    assert(TC && "Type Constraint cannot be null here");
9103
0
    auto *IDC = TC->getImmediatelyDeclaredConstraint();
9104
0
    assert(IDC && "ImmediatelyDeclaredConstraint can't be null here.");
9105
0
    ExprResult Constraint = SubstExpr(IDC, MLTAL);
9106
0
    if (Constraint.isInvalid()) {
9107
0
      return new (Context) concepts::ExprRequirement(
9108
0
          concepts::createSubstDiagAt(*this, IDC->getExprLoc(),
9109
0
                                      [&](llvm::raw_ostream &OS) {
9110
0
                                        IDC->printPretty(OS, /*Helper=*/nullptr,
9111
0
                                                         getPrintingPolicy());
9112
0
                                      }),
9113
0
          IsSimple, NoexceptLoc, ReturnTypeRequirement);
9114
0
    }
9115
0
    SubstitutedConstraintExpr =
9116
0
        cast<ConceptSpecializationExpr>(Constraint.get());
9117
0
    if (!SubstitutedConstraintExpr->isSatisfied())
9118
0
      Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied;
9119
0
  }
9120
0
  return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc,
9121
0
                                                 ReturnTypeRequirement, Status,
9122
0
                                                 SubstitutedConstraintExpr);
9123
0
}
9124
9125
concepts::ExprRequirement *
9126
Sema::BuildExprRequirement(
9127
    concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic,
9128
    bool IsSimple, SourceLocation NoexceptLoc,
9129
0
    concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {
9130
0
  return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic,
9131
0
                                                 IsSimple, NoexceptLoc,
9132
0
                                                 ReturnTypeRequirement);
9133
0
}
9134
9135
concepts::TypeRequirement *
9136
0
Sema::BuildTypeRequirement(TypeSourceInfo *Type) {
9137
0
  return new (Context) concepts::TypeRequirement(Type);
9138
0
}
9139
9140
concepts::TypeRequirement *
9141
Sema::BuildTypeRequirement(
9142
0
    concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
9143
0
  return new (Context) concepts::TypeRequirement(SubstDiag);
9144
0
}
9145
9146
0
concepts::Requirement *Sema::ActOnNestedRequirement(Expr *Constraint) {
9147
0
  return BuildNestedRequirement(Constraint);
9148
0
}
9149
9150
concepts::NestedRequirement *
9151
0
Sema::BuildNestedRequirement(Expr *Constraint) {
9152
0
  ConstraintSatisfaction Satisfaction;
9153
0
  if (!Constraint->isInstantiationDependent() &&
9154
0
      CheckConstraintSatisfaction(nullptr, {Constraint}, /*TemplateArgs=*/{},
9155
0
                                  Constraint->getSourceRange(), Satisfaction))
9156
0
    return nullptr;
9157
0
  return new (Context) concepts::NestedRequirement(Context, Constraint,
9158
0
                                                   Satisfaction);
9159
0
}
9160
9161
concepts::NestedRequirement *
9162
Sema::BuildNestedRequirement(StringRef InvalidConstraintEntity,
9163
0
                       const ASTConstraintSatisfaction &Satisfaction) {
9164
0
  return new (Context) concepts::NestedRequirement(
9165
0
      InvalidConstraintEntity,
9166
0
      ASTConstraintSatisfaction::Rebuild(Context, Satisfaction));
9167
0
}
9168
9169
RequiresExprBodyDecl *
9170
Sema::ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
9171
                             ArrayRef<ParmVarDecl *> LocalParameters,
9172
0
                             Scope *BodyScope) {
9173
0
  assert(BodyScope);
9174
9175
0
  RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(Context, CurContext,
9176
0
                                                            RequiresKWLoc);
9177
9178
0
  PushDeclContext(BodyScope, Body);
9179
9180
0
  for (ParmVarDecl *Param : LocalParameters) {
9181
0
    if (Param->hasDefaultArg())
9182
      // C++2a [expr.prim.req] p4
9183
      //     [...] A local parameter of a requires-expression shall not have a
9184
      //     default argument. [...]
9185
0
      Diag(Param->getDefaultArgRange().getBegin(),
9186
0
           diag::err_requires_expr_local_parameter_default_argument);
9187
    // Ignore default argument and move on
9188
9189
0
    Param->setDeclContext(Body);
9190
    // If this has an identifier, add it to the scope stack.
9191
0
    if (Param->getIdentifier()) {
9192
0
      CheckShadow(BodyScope, Param);
9193
0
      PushOnScopeChains(Param, BodyScope);
9194
0
    }
9195
0
  }
9196
0
  return Body;
9197
0
}
9198
9199
0
void Sema::ActOnFinishRequiresExpr() {
9200
0
  assert(CurContext && "DeclContext imbalance!");
9201
0
  CurContext = CurContext->getLexicalParent();
9202
0
  assert(CurContext && "Popped translation unit!");
9203
0
}
9204
9205
ExprResult Sema::ActOnRequiresExpr(
9206
    SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body,
9207
    SourceLocation LParenLoc, ArrayRef<ParmVarDecl *> LocalParameters,
9208
    SourceLocation RParenLoc, ArrayRef<concepts::Requirement *> Requirements,
9209
0
    SourceLocation ClosingBraceLoc) {
9210
0
  auto *RE = RequiresExpr::Create(Context, RequiresKWLoc, Body, LParenLoc,
9211
0
                                  LocalParameters, RParenLoc, Requirements,
9212
0
                                  ClosingBraceLoc);
9213
0
  if (DiagnoseUnexpandedParameterPackInRequiresExpr(RE))
9214
0
    return ExprError();
9215
0
  return RE;
9216
0
}