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