Coverage Report

Created: 2020-09-19 12:23

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaExprCXX.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
///
9
/// \file
10
/// Implements semantic analysis for C++ expressions.
11
///
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/Sema/Template.h"
15
#include "clang/Sema/SemaInternal.h"
16
#include "TreeTransform.h"
17
#include "TypeLocBuilder.h"
18
#include "clang/AST/ASTContext.h"
19
#include "clang/AST/ASTLambda.h"
20
#include "clang/AST/CXXInheritance.h"
21
#include "clang/AST/CharUnits.h"
22
#include "clang/AST/DeclObjC.h"
23
#include "clang/AST/ExprCXX.h"
24
#include "clang/AST/ExprObjC.h"
25
#include "clang/AST/RecursiveASTVisitor.h"
26
#include "clang/AST/TypeLoc.h"
27
#include "clang/Basic/AlignedAllocation.h"
28
#include "clang/Basic/PartialDiagnostic.h"
29
#include "clang/Basic/TargetInfo.h"
30
#include "clang/Lex/Preprocessor.h"
31
#include "clang/Sema/DeclSpec.h"
32
#include "clang/Sema/Initialization.h"
33
#include "clang/Sema/Lookup.h"
34
#include "clang/Sema/ParsedTemplate.h"
35
#include "clang/Sema/Scope.h"
36
#include "clang/Sema/ScopeInfo.h"
37
#include "clang/Sema/SemaLambda.h"
38
#include "clang/Sema/TemplateDeduction.h"
39
#include "llvm/ADT/APInt.h"
40
#include "llvm/ADT/STLExtras.h"
41
#include "llvm/Support/ErrorHandling.h"
42
using namespace clang;
43
using namespace sema;
44
45
/// Handle the result of the special case name lookup for inheriting
46
/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
47
/// constructor names in member using declarations, even if 'X' is not the
48
/// name of the corresponding type.
49
ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
50
                                              SourceLocation NameLoc,
51
417
                                              IdentifierInfo &Name) {
52
417
  NestedNameSpecifier *NNS = SS.getScopeRep();
53
417
54
  // Convert the nested-name-specifier into a type.
55
417
  QualType Type;
56
417
  switch (NNS->getKind()) {
57
415
  case NestedNameSpecifier::TypeSpec:
58
415
  case NestedNameSpecifier::TypeSpecWithTemplate:
59
415
    Type = QualType(NNS->getAsType(), 0);
60
415
    break;
61
415
62
2
  case NestedNameSpecifier::Identifier:
63
    // Strip off the last layer of the nested-name-specifier and build a
64
    // typename type for it.
65
2
    assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
66
2
    Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
67
2
                                        NNS->getAsIdentifier());
68
2
    break;
69
415
70
0
  case NestedNameSpecifier::Global:
71
0
  case NestedNameSpecifier::Super:
72
0
  case NestedNameSpecifier::Namespace:
73
0
  case NestedNameSpecifier::NamespaceAlias:
74
0
    llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
75
417
  }
76
417
77
  // This reference to the type is located entirely at the location of the
78
  // final identifier in the qualified-id.
79
417
  return CreateParsedType(Type,
80
417
                          Context.getTrivialTypeSourceInfo(Type, NameLoc));
81
417
}
82
83
ParsedType Sema::getConstructorName(IdentifierInfo &II,
84
                                    SourceLocation NameLoc,
85
                                    Scope *S, CXXScopeSpec &SS,
86
253k
                                    bool EnteringContext) {
87
253k
  CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
88
253k
  assert(CurClass && &II == CurClass->getIdentifier() &&
89
253k
         "not a constructor name");
90
253k
91
  // When naming a constructor as a member of a dependent context (eg, in a
92
  // friend declaration or an inherited constructor declaration), form an
93
  // unresolved "typename" type.
94
253k
  if (CurClass->isDependentContext() && 
!EnteringContext171k
&&
SS.getScopeRep()3
) {
95
1
    QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II);
96
1
    return ParsedType::make(T);
97
1
  }
98
253k
99
253k
  if (SS.isNotEmpty() && 
RequireCompleteDeclContext(SS, CurClass)34.1k
)
100
0
    return ParsedType();
101
253k
102
  // Find the injected-class-name declaration. Note that we make no attempt to
103
  // diagnose cases where the injected-class-name is shadowed: the only
104
  // declaration that can validly shadow the injected-class-name is a
105
  // non-static data member, and if the class contains both a non-static data
106
  // member and a constructor then it is ill-formed (we check that in
107
  // CheckCompletedCXXClass).
108
253k
  CXXRecordDecl *InjectedClassName = nullptr;
109
253k
  for (NamedDecl *ND : CurClass->lookup(&II)) {
110
253k
    auto *RD = dyn_cast<CXXRecordDecl>(ND);
111
253k
    if (RD && 
RD->isInjectedClassName()253k
) {
112
253k
      InjectedClassName = RD;
113
253k
      break;
114
253k
    }
115
253k
  }
116
253k
  if (!InjectedClassName) {
117
2
    if (!CurClass->isInvalidDecl()) {
118
      // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
119
      // properly. Work around it here for now.
120
1
      Diag(SS.getLastQualifierNameLoc(),
121
1
           diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
122
1
    }
123
2
    return ParsedType();
124
2
  }
125
253k
126
253k
  QualType T = Context.getTypeDeclType(InjectedClassName);
127
253k
  DiagnoseUseOfDecl(InjectedClassName, NameLoc);
128
253k
  MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
129
253k
130
253k
  return ParsedType::make(T);
131
253k
}
132
133
ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
134
                                   IdentifierInfo &II,
135
                                   SourceLocation NameLoc,
136
                                   Scope *S, CXXScopeSpec &SS,
137
                                   ParsedType ObjectTypePtr,
138
39.4k
                                   bool EnteringContext) {
139
  // Determine where to perform name lookup.
140
39.4k
141
  // FIXME: This area of the standard is very messy, and the current
142
  // wording is rather unclear about which scopes we search for the
143
  // destructor name; see core issues 399 and 555. Issue 399 in
144
  // particular shows where the current description of destructor name
145
  // lookup is completely out of line with existing practice, e.g.,
146
  // this appears to be ill-formed:
147
  //
148
  //   namespace N {
149
  //     template <typename T> struct S {
150
  //       ~S();
151
  //     };
152
  //   }
153
  //
154
  //   void f(N::S<int>* s) {
155
  //     s->N::S<int>::~S();
156
  //   }
157
  //
158
  // See also PR6358 and PR6359.
159
  //
160
  // For now, we accept all the cases in which the name given could plausibly
161
  // be interpreted as a correct destructor name, issuing off-by-default
162
  // extension diagnostics on the cases that don't strictly conform to the
163
  // C++20 rules. This basically means we always consider looking in the
164
  // nested-name-specifier prefix, the complete nested-name-specifier, and
165
  // the scope, and accept if we find the expected type in any of the three
166
  // places.
167
39.4k
168
39.4k
  if (SS.isInvalid())
169
7
    return nullptr;
170
39.4k
171
  // Whether we've failed with a diagnostic already.
172
39.4k
  bool Failed = false;
173
39.4k
174
39.4k
  llvm::SmallVector<NamedDecl*, 8> FoundDecls;
175
39.4k
  llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 8> FoundDeclSet;
176
39.4k
177
  // If we have an object type, it's because we are in a
178
  // pseudo-destructor-expression or a member access expression, and
179
  // we know what type we're looking for.
180
39.4k
  QualType SearchType =
181
39.2k
      ObjectTypePtr ? 
GetTypeFromParser(ObjectTypePtr)266
: QualType();
182
39.4k
183
39.5k
  auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType {
184
78.9k
    auto IsAcceptableResult = [&](NamedDecl *D) -> bool {
185
78.9k
      auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl());
186
78.9k
      if (!Type)
187
30
        return false;
188
78.9k
189
78.9k
      if (SearchType.isNull() || 
SearchType->isDependentType()584
)
190
78.3k
        return true;
191
584
192
584
      QualType T = Context.getTypeDeclType(Type);
193
584
      return Context.hasSameUnqualifiedType(T, SearchType);
194
584
    };
195
39.5k
196
39.5k
    unsigned NumAcceptableResults = 0;
197
39.5k
    for (NamedDecl *D : Found) {
198
39.5k
      if (IsAcceptableResult(D))
199
39.4k
        ++NumAcceptableResults;
200
39.5k
201
      // Don't list a class twice in the lookup failure diagnostic if it's
202
      // found by both its injected-class-name and by the name in the enclosing
203
      // scope.
204
39.5k
      if (auto *RD = dyn_cast<CXXRecordDecl>(D))
205
39.3k
        if (RD->isInjectedClassName())
206
38.9k
          D = cast<NamedDecl>(RD->getParent());
207
39.5k
208
39.5k
      if (FoundDeclSet.insert(D).second)
209
39.5k
        FoundDecls.push_back(D);
210
39.5k
    }
211
39.5k
212
    // As an extension, attempt to "fix" an ambiguity by erasing all non-type
213
    // results, and all non-matching results if we have a search type. It's not
214
    // clear what the right behavior is if destructor lookup hits an ambiguity,
215
    // but other compilers do generally accept at least some kinds of
216
    // ambiguity.
217
39.5k
    if (Found.isAmbiguous() && 
NumAcceptableResults == 16
) {
218
6
      Diag(NameLoc, diag::ext_dtor_name_ambiguous);
219
6
      LookupResult::Filter F = Found.makeFilter();
220
18
      while (F.hasNext()) {
221
12
        NamedDecl *D = F.next();
222
12
        if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
223
12
          Diag(D->getLocation(), diag::note_destructor_type_here)
224
12
              << Context.getTypeDeclType(TD);
225
0
        else
226
0
          Diag(D->getLocation(), diag::note_destructor_nontype_here);
227
12
228
12
        if (!IsAcceptableResult(D))
229
6
          F.erase();
230
12
      }
231
6
      F.done();
232
6
    }
233
39.5k
234
39.5k
    if (Found.isAmbiguous())
235
0
      Failed = true;
236
39.5k
237
39.5k
    if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
238
39.4k
      if (IsAcceptableResult(Type)) {
239
39.4k
        QualType T = Context.getTypeDeclType(Type);
240
39.4k
        MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
241
39.4k
        return CreateParsedType(T,
242
39.4k
                                Context.getTrivialTypeSourceInfo(T, NameLoc));
243
39.4k
      }
244
161
    }
245
161
246
161
    return nullptr;
247
161
  };
248
39.4k
249
39.4k
  bool IsDependent = false;
250
39.4k
251
90
  auto LookupInObjectType = [&]() -> ParsedType {
252
90
    if (Failed || SearchType.isNull())
253
29
      return nullptr;
254
61
255
61
    IsDependent |= SearchType->isDependentType();
256
61
257
61
    LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
258
61
    DeclContext *LookupCtx = computeDeclContext(SearchType);
259
61
    if (!LookupCtx)
260
1
      return nullptr;
261
60
    LookupQualifiedName(Found, LookupCtx);
262
60
    return CheckLookupResult(Found);
263
60
  };
264
39.4k
265
248
  auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType {
266
248
    if (Failed)
267
0
      return nullptr;
268
248
269
248
    IsDependent |= isDependentScopeSpecifier(LookupSS);
270
248
    DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext);
271
248
    if (!LookupCtx)
272
1
      return nullptr;
273
247
274
247
    LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
275
247
    if (RequireCompleteDeclContext(LookupSS, LookupCtx)) {
276
0
      Failed = true;
277
0
      return nullptr;
278
0
    }
279
247
    LookupQualifiedName(Found, LookupCtx);
280
247
    return CheckLookupResult(Found);
281
247
  };
282
39.4k
283
39.2k
  auto LookupInScope = [&]() -> ParsedType {
284
39.2k
    if (Failed || !S)
285
7
      return nullptr;
286
39.2k
287
39.2k
    LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
288
39.2k
    LookupName(Found, S);
289
39.2k
    return CheckLookupResult(Found);
290
39.2k
  };
291
39.4k
292
  // C++2a [basic.lookup.qual]p6:
293
  //   In a qualified-id of the form
294
  //
295
  //     nested-name-specifier[opt] type-name :: ~ type-name
296
  //
297
  //   the second type-name is looked up in the same scope as the first.
298
  //
299
  // We interpret this as meaning that if you do a dual-scope lookup for the
300
  // first name, you also do a dual-scope lookup for the second name, per
301
  // C++ [basic.lookup.classref]p4:
302
  //
303
  //   If the id-expression in a class member access is a qualified-id of the
304
  //   form
305
  //
306
  //     class-name-or-namespace-name :: ...
307
  //
308
  //   the class-name-or-namespace-name following the . or -> is first looked
309
  //   up in the class of the object expression and the name, if found, is used.
310
  //   Otherwise, it is looked up in the context of the entire
311
  //   postfix-expression.
312
  //
313
  // This looks in the same scopes as for an unqualified destructor name:
314
  //
315
  // C++ [basic.lookup.classref]p3:
316
  //   If the unqualified-id is ~ type-name, the type-name is looked up
317
  //   in the context of the entire postfix-expression. If the type T
318
  //   of the object expression is of a class type C, the type-name is
319
  //   also looked up in the scope of class C. At least one of the
320
  //   lookups shall find a name that refers to cv T.
321
  //
322
  // FIXME: The intent is unclear here. Should type-name::~type-name look in
323
  // the scope anyway if it finds a non-matching name declared in the class?
324
  // If both lookups succeed and find a dependent result, which result should
325
  // we retain? (Same question for p->~type-name().)
326
39.4k
327
39.4k
  if (NestedNameSpecifier *Prefix =
328
199
      SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) {
329
    // This is
330
    //
331
    //   nested-name-specifier type-name :: ~ type-name
332
    //
333
    // Look for the second type-name in the nested-name-specifier.
334
199
    CXXScopeSpec PrefixSS;
335
199
    PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
336
199
    if (ParsedType T = LookupInNestedNameSpec(PrefixSS))
337
165
      return T;
338
39.2k
  } else {
339
    // This is one of
340
    //
341
    //   type-name :: ~ type-name
342
    //   ~ type-name
343
    //
344
    // Look in the scope and (if any) the object type.
345
39.2k
    if (ParsedType T = LookupInScope())
346
39.1k
      return T;
347
90
    if (ParsedType T = LookupInObjectType())
348
34
      return T;
349
90
  }
350
90
351
90
  if (Failed)
352
0
    return nullptr;
353
90
354
90
  if (IsDependent) {
355
    // We didn't find our type, but that's OK: it's dependent anyway.
356
3
357
    // FIXME: What if we have no nested-name-specifier?
358
3
    QualType T = CheckTypenameType(ETK_None, SourceLocation(),
359
3
                                   SS.getWithLocInContext(Context),
360
3
                                   II, NameLoc);
361
3
    return ParsedType::make(T);
362
3
  }
363
87
364
  // The remaining cases are all non-standard extensions imitating the behavior
365
  // of various other compilers.
366
87
  unsigned NumNonExtensionDecls = FoundDecls.size();
367
87
368
87
  if (SS.isSet()) {
369
    // For compatibility with older broken C++ rules and existing code,
370
    //
371
    //   nested-name-specifier :: ~ type-name
372
    //
373
    // also looks for type-name within the nested-name-specifier.
374
49
    if (ParsedType T = LookupInNestedNameSpec(SS)) {
375
30
      Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope)
376
30
          << SS.getRange()
377
30
          << FixItHint::CreateInsertion(SS.getEndLoc(),
378
30
                                        ("::" + II.getName()).str());
379
30
      return T;
380
30
    }
381
19
382
    // For compatibility with other compilers and older versions of Clang,
383
    //
384
    //   nested-name-specifier type-name :: ~ type-name
385
    //
386
    // also looks for type-name in the scope. Unfortunately, we can't
387
    // reasonably apply this fallback for dependent nested-name-specifiers.
388
19
    if (SS.getScopeRep()->getPrefix()) {
389
10
      if (ParsedType T = LookupInScope()) {
390
10
        Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope)
391
10
            << FixItHint::CreateRemoval(SS.getRange());
392
10
        Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here)
393
10
            << GetTypeFromParser(T);
394
10
        return T;
395
10
      }
396
47
    }
397
19
  }
398
47
399
  // We didn't find anything matching; tell the user what we did find (if
400
  // anything).
401
47
402
  // Don't tell the user about declarations we shouldn't have found.
403
47
  FoundDecls.resize(NumNonExtensionDecls);
404
47
405
  // List types before non-types.
406
47
  std::stable_sort(FoundDecls.begin(), FoundDecls.end(),
407
0
                   [](NamedDecl *A, NamedDecl *B) {
408
0
                     return isa<TypeDecl>(A->getUnderlyingDecl()) >
409
0
                            isa<TypeDecl>(B->getUnderlyingDecl());
410
0
                   });
411
47
412
  // Suggest a fixit to properly name the destroyed type.
413
47
  auto MakeFixItHint = [&]{
414
47
    const CXXRecordDecl *Destroyed = nullptr;
415
    // FIXME: If we have a scope specifier, suggest its last component?
416
47
    if (!SearchType.isNull())
417
27
      Destroyed = SearchType->getAsCXXRecordDecl();
418
20
    else if (S)
419
20
      Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity());
420
47
    if (Destroyed)
421
39
      return FixItHint::CreateReplacement(SourceRange(NameLoc),
422
39
                                          Destroyed->getNameAsString());
423
8
    return FixItHint();
424
8
  };
425
47
426
47
  if (FoundDecls.empty()) {
427
    // FIXME: Attempt typo-correction?
428
26
    Diag(NameLoc, diag::err_undeclared_destructor_name)
429
26
      << &II << MakeFixItHint();
430
21
  } else if (!SearchType.isNull() && 
FoundDecls.size() == 119
) {
431
19
    if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) {
432
19
      assert(!SearchType.isNull() &&
433
19
             "should only reject a type result if we have a search type");
434
19
      QualType T = Context.getTypeDeclType(TD);
435
19
      Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
436
19
          << T << SearchType << MakeFixItHint();
437
0
    } else {
438
0
      Diag(NameLoc, diag::err_destructor_expr_nontype)
439
0
          << &II << MakeFixItHint();
440
0
    }
441
2
  } else {
442
2
    Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype
443
0
                                      : diag::err_destructor_expr_mismatch)
444
2
        << &II << SearchType << MakeFixItHint();
445
2
  }
446
47
447
21
  for (NamedDecl *FoundD : FoundDecls) {
448
21
    if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl()))
449
19
      Diag(FoundD->getLocation(), diag::note_destructor_type_here)
450
19
          << Context.getTypeDeclType(TD);
451
2
    else
452
2
      Diag(FoundD->getLocation(), diag::note_destructor_nontype_here)
453
2
          << FoundD;
454
21
  }
455
47
456
47
  return nullptr;
457
47
}
458
459
ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
460
22
                                              ParsedType ObjectType) {
461
22
  if (DS.getTypeSpecType() == DeclSpec::TST_error)
462
1
    return nullptr;
463
21
464
21
  if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
465
2
    Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
466
2
    return nullptr;
467
2
  }
468
19
469
19
  assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
470
19
         "unexpected type in getDestructorType");
471
19
  QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
472
19
473
  // If we know the type of the object, check that the correct destructor
474
  // type was named now; we can give better diagnostics this way.
475
19
  QualType SearchType = GetTypeFromParser(ObjectType);
476
19
  if (!SearchType.isNull() && 
!SearchType->isDependentType()18
&&
477
18
      !Context.hasSameUnqualifiedType(T, SearchType)) {
478
5
    Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
479
5
      << T << SearchType;
480
5
    return nullptr;
481
5
  }
482
14
483
14
  return ParsedType::make(T);
484
14
}
485
486
bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
487
699
                                  const UnqualifiedId &Name) {
488
699
  assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
489
699
490
699
  if (!SS.isValid())
491
684
    return false;
492
15
493
15
  switch (SS.getScopeRep()->getKind()) {
494
6
  case NestedNameSpecifier::Identifier:
495
6
  case NestedNameSpecifier::TypeSpec:
496
6
  case NestedNameSpecifier::TypeSpecWithTemplate:
497
    // Per C++11 [over.literal]p2, literal operators can only be declared at
498
    // namespace scope. Therefore, this unqualified-id cannot name anything.
499
    // Reject it early, because we have no AST representation for this in the
500
    // case where the scope is dependent.
501
6
    Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
502
6
        << SS.getScopeRep();
503
6
    return true;
504
6
505
9
  case NestedNameSpecifier::Global:
506
9
  case NestedNameSpecifier::Super:
507
9
  case NestedNameSpecifier::Namespace:
508
9
  case NestedNameSpecifier::NamespaceAlias:
509
9
    return false;
510
0
  }
511
0
512
0
  llvm_unreachable("unknown nested name specifier kind");
513
0
}
514
515
/// Build a C++ typeid expression with a type operand.
516
ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
517
                                SourceLocation TypeidLoc,
518
                                TypeSourceInfo *Operand,
519
4.94k
                                SourceLocation RParenLoc) {
520
  // C++ [expr.typeid]p4:
521
  //   The top-level cv-qualifiers of the lvalue expression or the type-id
522
  //   that is the operand of typeid are always ignored.
523
  //   If the type of the type-id is a class type or a reference to a class
524
  //   type, the class shall be completely-defined.
525
4.94k
  Qualifiers Quals;
526
4.94k
  QualType T
527
4.94k
    = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
528
4.94k
                                      Quals);
529
4.94k
  if (T->getAs<RecordType>() &&
530
257
      RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
531
5
    return ExprError();
532
4.93k
533
4.93k
  if (T->isVariablyModifiedType())
534
1
    return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
535
4.93k
536
4.93k
  if (CheckQualifiedFunctionForTypeId(T, TypeidLoc))
537
6
    return ExprError();
538
4.93k
539
4.93k
  return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
540
4.93k
                                     SourceRange(TypeidLoc, RParenLoc));
541
4.93k
}
542
543
/// Build a C++ typeid expression with an expression operand.
544
ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
545
                                SourceLocation TypeidLoc,
546
                                Expr *E,
547
285
                                SourceLocation RParenLoc) {
548
285
  bool WasEvaluated = false;
549
285
  if (E && !E->isTypeDependent()) {
550
271
    if (E->getType()->isPlaceholderType()) {
551
1
      ExprResult result = CheckPlaceholderExpr(E);
552
1
      if (result.isInvalid()) 
return ExprError()0
;
553
1
      E = result.get();
554
1
    }
555
271
556
271
    QualType T = E->getType();
557
271
    if (const RecordType *RecordT = T->getAs<RecordType>()) {
558
128
      CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
559
      // C++ [expr.typeid]p3:
560
      //   [...] If the type of the expression is a class type, the class
561
      //   shall be completely-defined.
562
128
      if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
563
1
        return ExprError();
564
127
565
      // C++ [expr.typeid]p3:
566
      //   When typeid is applied to an expression other than an glvalue of a
567
      //   polymorphic class type [...] [the] expression is an unevaluated
568
      //   operand. [...]
569
127
      if (RecordD->isPolymorphic() && 
E->isGLValue()108
) {
570
        // The subexpression is potentially evaluated; switch the context
571
        // and recheck the subexpression.
572
104
        ExprResult Result = TransformToPotentiallyEvaluated(E);
573
104
        if (Result.isInvalid()) 
return ExprError()10
;
574
94
        E = Result.get();
575
94
576
        // We require a vtable to query the type at run time.
577
94
        MarkVTableUsed(TypeidLoc, RecordD);
578
94
        WasEvaluated = true;
579
94
      }
580
127
    }
581
271
582
260
    ExprResult Result = CheckUnevaluatedOperand(E);
583
260
    if (Result.isInvalid())
584
0
      return ExprError();
585
260
    E = Result.get();
586
260
587
    // C++ [expr.typeid]p4:
588
    //   [...] If the type of the type-id is a reference to a possibly
589
    //   cv-qualified type, the result of the typeid expression refers to a
590
    //   std::type_info object representing the cv-unqualified referenced
591
    //   type.
592
260
    Qualifiers Quals;
593
260
    QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
594
260
    if (!Context.hasSameType(T, UnqualT)) {
595
20
      T = UnqualT;
596
20
      E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
597
20
    }
598
260
  }
599
285
600
274
  if (E->getType()->isVariablyModifiedType())
601
1
    return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
602
1
                     << E->getType());
603
273
  else if (!inTemplateInstantiation() &&
604
253
           E->HasSideEffects(Context, WasEvaluated)) {
605
    // The expression operand for typeid is in an unevaluated expression
606
    // context, so side effects could result in unintended consequences.
607
58
    Diag(E->getExprLoc(), WasEvaluated
608
37
                              ? diag::warn_side_effects_typeid
609
21
                              : diag::warn_side_effects_unevaluated_context);
610
58
  }
611
274
612
273
  return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
613
273
                                     SourceRange(TypeidLoc, RParenLoc));
614
274
}
615
616
/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
617
ExprResult
618
Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
619
5.10k
                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
620
  // typeid is not supported in OpenCL.
621
5.10k
  if (getLangOpts().OpenCLCPlusPlus) {
622
1
    return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
623
1
                     << "typeid");
624
1
  }
625
5.10k
626
  // Find the std::type_info type.
627
5.10k
  if (!getStdNamespace())
628
1
    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
629
5.10k
630
5.10k
  if (!CXXTypeInfoDecl) {
631
533
    IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
632
533
    LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
633
533
    LookupQualifiedName(R, getStdNamespace());
634
533
    CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
635
    // Microsoft's typeinfo doesn't have type_info in std but in the global
636
    // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
637
533
    if (!CXXTypeInfoDecl && 
LangOpts.MSVCCompat4
) {
638
1
      LookupQualifiedName(R, Context.getTranslationUnitDecl());
639
1
      CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
640
1
    }
641
533
    if (!CXXTypeInfoDecl)
642
3
      return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
643
5.10k
  }
644
5.10k
645
5.10k
  if (!getLangOpts().RTTI) {
646
1
    return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
647
1
  }
648
5.10k
649
5.10k
  QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
650
5.10k
651
5.10k
  if (isType) {
652
    // The operand is a type; handle it as such.
653
4.83k
    TypeSourceInfo *TInfo = nullptr;
654
4.83k
    QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
655
4.83k
                                   &TInfo);
656
4.83k
    if (T.isNull())
657
0
      return ExprError();
658
4.83k
659
4.83k
    if (!TInfo)
660
0
      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
661
4.83k
662
4.83k
    return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
663
4.83k
  }
664
265
665
  // The operand is an expression.
666
265
  ExprResult Result =
667
265
      BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc);
668
265
669
265
  if (!getLangOpts().RTTIData && 
!Result.isInvalid()15
)
670
15
    if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get()))
671
15
      if (CTE->isPotentiallyEvaluated() && 
!CTE->isMostDerived(Context)11
)
672
7
        Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled)
673
7
            << (getDiagnostics().getDiagnosticOptions().getFormat() ==
674
7
                DiagnosticOptions::MSVC);
675
265
  return Result;
676
265
}
677
678
/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
679
/// a single GUID.
680
static void
681
getUuidAttrOfType(Sema &SemaRef, QualType QT,
682
170
                  llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
683
  // Optionally remove one level of pointer, reference or array indirection.
684
170
  const Type *Ty = QT.getTypePtr();
685
170
  if (QT->isPointerType() || 
QT->isReferenceType()164
)
686
6
    Ty = QT->getPointeeType().getTypePtr();
687
164
  else if (QT->isArrayType())
688
10
    Ty = Ty->getBaseElementTypeUnsafe();
689
170
690
170
  const auto *TD = Ty->getAsTagDecl();
691
170
  if (!TD)
692
5
    return;
693
165
694
165
  if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
695
150
    UuidAttrs.insert(Uuid);
696
150
    return;
697
150
  }
698
15
699
  // __uuidof can grab UUIDs from template arguments.
700
15
  if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
701
6
    const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
702
9
    for (const TemplateArgument &TA : TAL.asArray()) {
703
9
      const UuidAttr *UuidForTA = nullptr;
704
9
      if (TA.getKind() == TemplateArgument::Type)
705
9
        getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
706
0
      else if (TA.getKind() == TemplateArgument::Declaration)
707
0
        getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
708
9
709
9
      if (UuidForTA)
710
0
        UuidAttrs.insert(UuidForTA);
711
9
    }
712
6
  }
713
15
}
714
715
/// Build a Microsoft __uuidof expression with a type operand.
716
ExprResult Sema::BuildCXXUuidof(QualType Type,
717
                                SourceLocation TypeidLoc,
718
                                TypeSourceInfo *Operand,
719
162
                                SourceLocation RParenLoc) {
720
162
  MSGuidDecl *Guid = nullptr;
721
162
  if (!Operand->getType()->isDependentType()) {
722
148
    llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
723
148
    getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
724
148
    if (UuidAttrs.empty())
725
9
      return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
726
139
    if (UuidAttrs.size() > 1)
727
1
      return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
728
138
    Guid = UuidAttrs.back()->getGuidDecl();
729
138
  }
730
162
731
152
  return new (Context)
732
152
      CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc));
733
162
}
734
735
/// Build a Microsoft __uuidof expression with an expression operand.
736
ExprResult Sema::BuildCXXUuidof(QualType Type, SourceLocation TypeidLoc,
737
27
                                Expr *E, SourceLocation RParenLoc) {
738
27
  MSGuidDecl *Guid = nullptr;
739
27
  if (!E->getType()->isDependentType()) {
740
26
    if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
741
      // A null pointer results in {00000000-0000-0000-0000-000000000000}.
742
13
      Guid = Context.getMSGuidDecl(MSGuidDecl::Parts{});
743
13
    } else {
744
13
      llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
745
13
      getUuidAttrOfType(*this, E->getType(), UuidAttrs);
746
13
      if (UuidAttrs.empty())
747
4
        return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
748
9
      if (UuidAttrs.size() > 1)
749
1
        return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
750
8
      Guid = UuidAttrs.back()->getGuidDecl();
751
8
    }
752
26
  }
753
27
754
22
  return new (Context)
755
22
      CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc));
756
27
}
757
758
/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
759
ExprResult
760
Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
761
171
                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
762
171
  QualType GuidType = Context.getMSGuidType();
763
171
  GuidType.addConst();
764
171
765
171
  if (isType) {
766
    // The operand is a type; handle it as such.
767
144
    TypeSourceInfo *TInfo = nullptr;
768
144
    QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
769
144
                                   &TInfo);
770
144
    if (T.isNull())
771
0
      return ExprError();
772
144
773
144
    if (!TInfo)
774
0
      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
775
144
776
144
    return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
777
144
  }
778
27
779
  // The operand is an expression.
780
27
  return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
781
27
}
782
783
/// ActOnCXXBoolLiteral - Parse {true,false} literals.
784
ExprResult
785
283k
Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
786
283k
  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
787
283k
         "Unknown C++ Boolean value!");
788
283k
  return new (Context)
789
283k
      CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
790
283k
}
791
792
/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
793
ExprResult
794
44.8k
Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
795
44.8k
  return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
796
44.8k
}
797
798
/// ActOnCXXThrow - Parse throw expressions.
799
ExprResult
800
13.3k
Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
801
13.3k
  bool IsThrownVarInScope = false;
802
13.3k
  if (Ex) {
803
    // C++0x [class.copymove]p31:
804
    //   When certain criteria are met, an implementation is allowed to omit the
805
    //   copy/move construction of a class object [...]
806
    //
807
    //     - in a throw-expression, when the operand is the name of a
808
    //       non-volatile automatic object (other than a function or catch-
809
    //       clause parameter) whose scope does not extend beyond the end of the
810
    //       innermost enclosing try-block (if there is one), the copy/move
811
    //       operation from the operand to the exception object (15.1) can be
812
    //       omitted by constructing the automatic object directly into the
813
    //       exception object
814
6.94k
    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
815
513
      if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
816
507
        if (Var->hasLocalStorage() && 
!Var->getType().isVolatileQualified()484
) {
817
521
          for( ; S; 
S = S->getParent()37
) {
818
521
            if (S->isDeclScope(Var)) {
819
72
              IsThrownVarInScope = true;
820
72
              break;
821
72
            }
822
449
823
449
            if (S->getFlags() &
824
449
                (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
825
449
                 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
826
449
                 Scope::TryScope))
827
412
              break;
828
449
          }
829
484
        }
830
507
      }
831
6.94k
  }
832
13.3k
833
13.3k
  return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
834
13.3k
}
835
836
ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
837
13.3k
                               bool IsThrownVarInScope) {
838
  // Don't report an error if 'throw' is used in system headers.
839
13.3k
  if (!getLangOpts().CXXExceptions &&
840
10
      !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) {
841
    // Delay error emission for the OpenMP device code.
842
10
    targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";
843
10
  }
844
13.3k
845
  // Exceptions aren't allowed in CUDA device code.
846
13.3k
  if (getLangOpts().CUDA)
847
14
    CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
848
14
        << "throw" << CurrentCUDATarget();
849
13.3k
850
13.3k
  if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
851
232
    Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
852
13.3k
853
13.3k
  if (Ex && 
!Ex->isTypeDependent()6.99k
) {
854
5.77k
    QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
855
5.77k
    if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
856
42
      return ExprError();
857
5.72k
858
    // Initialize the exception result.  This implicitly weeds out
859
    // abstract types or types with inaccessible copy constructors.
860
5.72k
861
    // C++0x [class.copymove]p31:
862
    //   When certain criteria are met, an implementation is allowed to omit the
863
    //   copy/move construction of a class object [...]
864
    //
865
    //     - in a throw-expression, when the operand is the name of a
866
    //       non-volatile automatic object (other than a function or
867
    //       catch-clause
868
    //       parameter) whose scope does not extend beyond the end of the
869
    //       innermost enclosing try-block (if there is one), the copy/move
870
    //       operation from the operand to the exception object (15.1) can be
871
    //       omitted by constructing the automatic object directly into the
872
    //       exception object
873
5.72k
    const VarDecl *NRVOVariable = nullptr;
874
5.72k
    if (IsThrownVarInScope)
875
73
      NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict);
876
5.72k
877
5.72k
    InitializedEntity Entity = InitializedEntity::InitializeException(
878
5.72k
        OpLoc, ExceptionObjectTy,
879
5.72k
        /*NRVO=*/NRVOVariable != nullptr);
880
5.72k
    ExprResult Res = PerformMoveOrCopyInitialization(
881
5.72k
        Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
882
5.72k
    if (Res.isInvalid())
883
5
      return ExprError();
884
5.72k
    Ex = Res.get();
885
5.72k
  }
886
13.3k
887
13.3k
  return new (Context)
888
13.3k
      CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
889
13.3k
}
890
891
static void
892
collectPublicBases(CXXRecordDecl *RD,
893
                   llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
894
                   llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
895
                   llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
896
47
                   bool ParentIsPublic) {
897
16
  for (const CXXBaseSpecifier &BS : RD->bases()) {
898
16
    CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
899
16
    bool NewSubobject;
900
    // Virtual bases constitute the same subobject.  Non-virtual bases are
901
    // always distinct subobjects.
902
16
    if (BS.isVirtual())
903
4
      NewSubobject = VBases.insert(BaseDecl).second;
904
12
    else
905
12
      NewSubobject = true;
906
16
907
16
    if (NewSubobject)
908
14
      ++SubobjectsSeen[BaseDecl];
909
16
910
    // Only add subobjects which have public access throughout the entire chain.
911
16
    bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
912
16
    if (PublicPath)
913
10
      PublicSubobjectsSeen.insert(BaseDecl);
914
16
915
    // Recurse on to each base subobject.
916
16
    collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
917
16
                       PublicPath);
918
16
  }
919
47
}
920
921
static void getUnambiguousPublicSubobjects(
922
31
    CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
923
31
  llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
924
31
  llvm::SmallSet<CXXRecordDecl *, 2> VBases;
925
31
  llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
926
31
  SubobjectsSeen[RD] = 1;
927
31
  PublicSubobjectsSeen.insert(RD);
928
31
  collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
929
31
                     /*ParentIsPublic=*/true);
930
31
931
39
  for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
932
    // Skip ambiguous objects.
933
39
    if (SubobjectsSeen[PublicSubobject] > 1)
934
0
      continue;
935
39
936
39
    Objects.push_back(PublicSubobject);
937
39
  }
938
31
}
939
940
/// CheckCXXThrowOperand - Validate the operand of a throw.
941
bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
942
5.77k
                                QualType ExceptionObjectTy, Expr *E) {
943
  //   If the type of the exception would be an incomplete type or a pointer
944
  //   to an incomplete type other than (cv) void the program is ill-formed.
945
5.77k
  QualType Ty = ExceptionObjectTy;
946
5.77k
  bool isPointer = false;
947
5.77k
  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
948
119
    Ty = Ptr->getPointeeType();
949
119
    isPointer = true;
950
119
  }
951
5.77k
  if (!isPointer || 
!Ty->isVoidType()119
) {
952
5.76k
    if (RequireCompleteType(ThrowLoc, Ty,
953
111
                            isPointer ? diag::err_throw_incomplete_ptr
954
5.65k
                                      : diag::err_throw_incomplete,
955
5.76k
                            E->getSourceRange()))
956
33
      return true;
957
5.73k
958
5.73k
    if (!isPointer && 
Ty->isSizelessType()5.63k
) {
959
4
      Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange();
960
4
      return true;
961
4
    }
962
5.73k
963
5.73k
    if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
964
5.73k
                               diag::err_throw_abstract_type, E))
965
3
      return true;
966
5.73k
  }
967
5.73k
968
  // If the exception has class type, we need additional handling.
969
5.73k
  CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
970
5.73k
  if (!RD)
971
1.08k
    return false;
972
4.65k
973
  // If we are throwing a polymorphic class type or pointer thereof,
974
  // exception handling will make use of the vtable.
975
4.65k
  MarkVTableUsed(ThrowLoc, RD);
976
4.65k
977
  // If a pointer is thrown, the referenced object will not be destroyed.
978
4.65k
  if (isPointer)
979
16
    return false;
980
4.63k
981
  // If the class has a destructor, we must be able to call it.
982
4.63k
  if (!RD->hasIrrelevantDestructor()) {
983
4.48k
    if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
984
4.48k
      MarkFunctionReferenced(E->getExprLoc(), Destructor);
985
4.48k
      CheckDestructorAccess(E->getExprLoc(), Destructor,
986
4.48k
                            PDiag(diag::err_access_dtor_exception) << Ty);
987
4.48k
      if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
988
1
        return true;
989
4.63k
    }
990
4.48k
  }
991
4.63k
992
  // The MSVC ABI creates a list of all types which can catch the exception
993
  // object.  This list also references the appropriate copy constructor to call
994
  // if the object is caught by value and has a non-trivial copy constructor.
995
4.63k
  if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
996
    // We are only interested in the public, unambiguous bases contained within
997
    // the exception object.  Bases which are ambiguous or otherwise
998
    // inaccessible are not catchable types.
999
31
    llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
1000
31
    getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
1001
31
1002
39
    for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
1003
      // Attempt to lookup the copy constructor.  Various pieces of machinery
1004
      // will spring into action, like template instantiation, which means this
1005
      // cannot be a simple walk of the class's decls.  Instead, we must perform
1006
      // lookup and overload resolution.
1007
39
      CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
1008
39
      if (!CD || CD->isDeleted())
1009
4
        continue;
1010
35
1011
      // Mark the constructor referenced as it is used by this throw expression.
1012
35
      MarkFunctionReferenced(E->getExprLoc(), CD);
1013
35
1014
      // Skip this copy constructor if it is trivial, we don't need to record it
1015
      // in the catchable type data.
1016
35
      if (CD->isTrivial())
1017
15
        continue;
1018
20
1019
      // The copy constructor is non-trivial, create a mapping from this class
1020
      // type to this constructor.
1021
      // N.B.  The selection of copy constructor is not sensitive to this
1022
      // particular throw-site.  Lookup will be performed at the catch-site to
1023
      // ensure that the copy constructor is, in fact, accessible (via
1024
      // friendship or any other means).
1025
20
      Context.addCopyConstructorForExceptionObject(Subobject, CD);
1026
20
1027
      // We don't keep the instantiated default argument expressions around so
1028
      // we must rebuild them here.
1029
26
      for (unsigned I = 1, E = CD->getNumParams(); I != E; 
++I6
) {
1030
7
        if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
1031
1
          return true;
1032
7
      }
1033
20
    }
1034
31
  }
1035
4.63k
1036
  // Under the Itanium C++ ABI, memory for the exception object is allocated by
1037
  // the runtime with no ability for the compiler to request additional
1038
  // alignment. Warn if the exception type requires alignment beyond the minimum
1039
  // guaranteed by the target C++ runtime.
1040
4.63k
  if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) {
1041
4.60k
    CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
1042
4.60k
    CharUnits ExnObjAlign = Context.getExnObjectAlignment();
1043
4.60k
    if (ExnObjAlign < TypeAlign) {
1044
26
      Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
1045
26
      Diag(ThrowLoc, diag::note_throw_underaligned_obj)
1046
26
          << Ty << (unsigned)TypeAlign.getQuantity()
1047
26
          << (unsigned)ExnObjAlign.getQuantity();
1048
26
    }
1049
4.60k
  }
1050
4.63k
1051
4.63k
  return false;
1052
4.63k
}
1053
1054
static QualType adjustCVQualifiersForCXXThisWithinLambda(
1055
    ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
1056
2.79k
    DeclContext *CurSemaContext, ASTContext &ASTCtx) {
1057
2.79k
1058
2.79k
  QualType ClassType = ThisTy->getPointeeType();
1059
2.79k
  LambdaScopeInfo *CurLSI = nullptr;
1060
2.79k
  DeclContext *CurDC = CurSemaContext;
1061
2.79k
1062
  // Iterate through the stack of lambdas starting from the innermost lambda to
1063
  // the outermost lambda, checking if '*this' is ever captured by copy - since
1064
  // that could change the cv-qualifiers of the '*this' object.
1065
  // The object referred to by '*this' starts out with the cv-qualifiers of its
1066
  // member function.  We then start with the innermost lambda and iterate
1067
  // outward checking to see if any lambda performs a by-copy capture of '*this'
1068
  // - and if so, any nested lambda must respect the 'constness' of that
1069
  // capturing lamdbda's call operator.
1070
  //
1071
2.79k
1072
  // Since the FunctionScopeInfo stack is representative of the lexical
1073
  // nesting of the lambda expressions during initial parsing (and is the best
1074
  // place for querying information about captures about lambdas that are
1075
  // partially processed) and perhaps during instantiation of function templates
1076
  // that contain lambda expressions that need to be transformed BUT not
1077
  // necessarily during instantiation of a nested generic lambda's function call
1078
  // operator (which might even be instantiated at the end of the TU) - at which
1079
  // time the DeclContext tree is mature enough to query capture information
1080
  // reliably - we use a two pronged approach to walk through all the lexically
1081
  // enclosing lambda expressions:
1082
  //
1083
  //  1) Climb down the FunctionScopeInfo stack as long as each item represents
1084
  //  a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
1085
  //  enclosed by the call-operator of the LSI below it on the stack (while
1086
  //  tracking the enclosing DC for step 2 if needed).  Note the topmost LSI on
1087
  //  the stack represents the innermost lambda.
1088
  //
1089
  //  2) If we run out of enclosing LSI's, check if the enclosing DeclContext
1090
  //  represents a lambda's call operator.  If it does, we must be instantiating
1091
  //  a generic lambda's call operator (represented by the Current LSI, and
1092
  //  should be the only scenario where an inconsistency between the LSI and the
1093
  //  DeclContext should occur), so climb out the DeclContexts if they
1094
  //  represent lambdas, while querying the corresponding closure types
1095
  //  regarding capture information.
1096
2.79k
1097
  // 1) Climb down the function scope info stack.
1098
2.79k
  for (int I = FunctionScopes.size();
1099
6.15k
       I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
1100
3.99k
       (!CurLSI || 
!CurLSI->Lambda1.19k
|| CurLSI->Lambda->getDeclContext() ==
1101
1.18k
                       cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
1102
3.91k
       
CurDC = getLambdaAwareParentOfDeclContext(CurDC)3.35k
) {
1103
3.91k
    CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
1104
3.91k
1105
3.91k
    if (!CurLSI->isCXXThisCaptured())
1106
1.55k
        continue;
1107
2.36k
1108
2.36k
    auto C = CurLSI->getCXXThisCapture();
1109
2.36k
1110
2.36k
    if (C.isCopyCapture()) {
1111
560
      ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1112
560
      if (CurLSI->CallOperator->isConst())
1113
240
        ClassType.addConst();
1114
560
      return ASTCtx.getPointerType(ClassType);
1115
560
    }
1116
2.36k
  }
1117
2.79k
1118
  // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
1119
  // happen during instantiation of its nested generic lambda call operator)
1120
2.23k
  if (isLambdaCallOperator(CurDC)) {
1121
128
    assert(CurLSI && "While computing 'this' capture-type for a generic "
1122
128
                     "lambda, we must have a corresponding LambdaScopeInfo");
1123
128
    assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
1124
128
           "While computing 'this' capture-type for a generic lambda, when we "
1125
128
           "run out of enclosing LSI's, yet the enclosing DC is a "
1126
128
           "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1127
128
           "lambda call oeprator");
1128
128
    assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
1129
128
1130
128
    auto IsThisCaptured =
1131
206
        [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1132
206
      IsConst = false;
1133
206
      IsByCopy = false;
1134
206
      for (auto &&C : Closure->captures()) {
1135
206
        if (C.capturesThis()) {
1136
206
          if (C.getCaptureKind() == LCK_StarThis)
1137
36
            IsByCopy = true;
1138
206
          if (Closure->getLambdaCallOperator()->isConst())
1139
170
            IsConst = true;
1140
206
          return true;
1141
206
        }
1142
206
      }
1143
0
      return false;
1144
206
    };
1145
128
1146
128
    bool IsByCopyCapture = false;
1147
128
    bool IsConstCapture = false;
1148
128
    CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1149
298
    while (Closure &&
1150
206
           IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1151
206
      if (IsByCopyCapture) {
1152
36
        ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1153
36
        if (IsConstCapture)
1154
0
          ClassType.addConst();
1155
36
        return ASTCtx.getPointerType(ClassType);
1156
36
      }
1157
170
      Closure = isLambdaCallOperator(Closure->getParent())
1158
78
                    ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1159
92
                    : nullptr;
1160
170
    }
1161
128
  }
1162
2.19k
  return ASTCtx.getPointerType(ClassType);
1163
2.23k
}
1164
1165
2.03M
QualType Sema::getCurrentThisType() {
1166
2.03M
  DeclContext *DC = getFunctionLevelDeclContext();
1167
2.03M
  QualType ThisTy = CXXThisTypeOverride;
1168
2.03M
1169
2.03M
  if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1170
2.02M
    if (method && method->isInstance())
1171
2.02M
      ThisTy = method->getThisType();
1172
2.02M
  }
1173
2.03M
1174
2.03M
  if (ThisTy.isNull() && 
isLambdaCallOperator(CurContext)9.32k
&&
1175
50
      inTemplateInstantiation()) {
1176
30
1177
30
    assert(isa<CXXRecordDecl>(DC) &&
1178
30
           "Trying to get 'this' type from static method?");
1179
30
1180
    // This is a lambda call operator that is being instantiated as a default
1181
    // initializer. DC must point to the enclosing class type, so we can recover
1182
    // the 'this' type from it.
1183
30
1184
30
    QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1185
    // There are no cv-qualifiers for 'this' within default initializers,
1186
    // per [expr.prim.general]p4.
1187
30
    ThisTy = Context.getPointerType(ClassTy);
1188
30
  }
1189
2.03M
1190
  // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1191
  // might need to be adjusted if the lambda or any of its enclosing lambda's
1192
  // captures '*this' by copy.
1193
2.03M
  if (!ThisTy.isNull() && 
isLambdaCallOperator(CurContext)2.02M
)
1194
2.79k
    return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1195
2.79k
                                                    CurContext, Context);
1196
2.03M
  return ThisTy;
1197
2.03M
}
1198
1199
Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
1200
                                         Decl *ContextDecl,
1201
                                         Qualifiers CXXThisTypeQuals,
1202
                                         bool Enabled)
1203
  : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1204
4.11M
{
1205
4.11M
  if (!Enabled || 
!ContextDecl2.66M
)
1206
1.61M
    return;
1207
2.50M
1208
2.50M
  CXXRecordDecl *Record = nullptr;
1209
2.50M
  if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1210
53.9k
    Record = Template->getTemplatedDecl();
1211
2.44M
  else
1212
2.44M
    Record = cast<CXXRecordDecl>(ContextDecl);
1213
2.50M
1214
2.50M
  QualType T = S.Context.getRecordType(Record);
1215
2.50M
  T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1216
2.50M
1217
2.50M
  S.CXXThisTypeOverride = S.Context.getPointerType(T);
1218
2.50M
1219
2.50M
  this->Enabled = true;
1220
2.50M
}
1221
1222
1223
4.11M
Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1224
4.11M
  if (Enabled) {
1225
2.50M
    S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1226
2.50M
  }
1227
4.11M
}
1228
1229
bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1230
    bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1231
1.01M
    const bool ByCopy) {
1232
  // We don't need to capture this in an unevaluated context.
1233
1.01M
  if (isUnevaluatedContext() && 
!Explicit3.56k
)
1234
3.56k
    return true;
1235
1.01M
1236
1.01M
  assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
1237
1.01M
1238
1.01M
  const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1239
18
                                         ? *FunctionScopeIndexToStopAt
1240
1.01M
                                         : FunctionScopes.size() - 1;
1241
1.01M
1242
  // Check that we can capture the *enclosing object* (referred to by '*this')
1243
  // by the capturing-entity/closure (lambda/block/etc) at
1244
  // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1245
1.01M
1246
  // Note: The *enclosing object* can only be captured by-value by a
1247
  // closure that is a lambda, using the explicit notation:
1248
  //    [*this] { ... }.
1249
  // Every other capture of the *enclosing object* results in its by-reference
1250
  // capture.
1251
1.01M
1252
  // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1253
  // stack), we can capture the *enclosing object* only if:
1254
  // - 'L' has an explicit byref or byval capture of the *enclosing object*
1255
  // -  or, 'L' has an implicit capture.
1256
  // AND
1257
  //   -- there is no enclosing closure
1258
  //   -- or, there is some enclosing closure 'E' that has already captured the
1259
  //      *enclosing object*, and every intervening closure (if any) between 'E'
1260
  //      and 'L' can implicitly capture the *enclosing object*.
1261
  //   -- or, every enclosing closure can implicitly capture the
1262
  //      *enclosing object*
1263
1.01M
1264
1.01M
1265
1.01M
  unsigned NumCapturingClosures = 0;
1266
1.02M
  for (int idx = MaxFunctionScopesIndex; idx >= 0; 
idx--11.2k
) {
1267
1.02M
    if (CapturingScopeInfo *CSI =
1268
22.7k
            dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1269
22.7k
      if (CSI->CXXThisCaptureIndex != 0) {
1270
        // 'this' is already being captured; there isn't anything more to do.
1271
11.4k
        CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1272
11.4k
        break;
1273
11.4k
      }
1274
11.3k
      LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1275
11.3k
      if (LSI && 
isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)828
) {
1276
        // This context can't implicitly capture 'this'; fail out.
1277
20
        if (BuildAndDiagnose)
1278
16
          Diag(Loc, diag::err_this_capture)
1279
16
              << (Explicit && 
idx == MaxFunctionScopesIndex0
);
1280
20
        return true;
1281
20
      }
1282
11.3k
      if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1283
11.0k
          CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1284
10.8k
          CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1285
10.8k
          CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1286
11.2k
          
(384
Explicit384
&&
idx == MaxFunctionScopesIndex354
)) {
1287
        // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1288
        // iteration through can be an explicit capture, all enclosing closures,
1289
        // if any, must perform implicit captures.
1290
11.2k
1291
        // This closure can capture 'this'; continue looking upwards.
1292
11.2k
        NumCapturingClosures++;
1293
11.2k
        continue;
1294
11.2k
      }
1295
      // This context can't implicitly capture 'this'; fail out.
1296
32
      if (BuildAndDiagnose)
1297
26
        Diag(Loc, diag::err_this_capture)
1298
26
            << (Explicit && 
idx == MaxFunctionScopesIndex2
);
1299
32
      return true;
1300
32
    }
1301
1.00M
    break;
1302
1.00M
  }
1303
1.01M
  if (!BuildAndDiagnose) 
return false47
;
1304
1.01M
1305
  // If we got here, then the closure at MaxFunctionScopesIndex on the
1306
  // FunctionScopes stack, can capture the *enclosing object*, so capture it
1307
  // (including implicit by-reference captures in any enclosing closures).
1308
1.01M
1309
  // In the loop below, respect the ByCopy flag only for the closure requesting
1310
  // the capture (i.e. first iteration through the loop below).  Ignore it for
1311
  // all enclosing closure's up to NumCapturingClosures (since they must be
1312
  // implicitly capturing the *enclosing  object* by reference (see loop
1313
  // above)).
1314
1.01M
  assert((!ByCopy ||
1315
1.01M
          dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1316
1.01M
         "Only a lambda can capture the enclosing object (referred to by "
1317
1.01M
         "*this) by copy");
1318
1.01M
  QualType ThisTy = getCurrentThisType();
1319
1.02M
  for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1320
11.2k
       --idx, --NumCapturingClosures) {
1321
11.2k
    CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1322
11.2k
1323
    // The type of the corresponding data member (not a 'this' pointer if 'by
1324
    // copy').
1325
11.2k
    QualType CaptureType = ThisTy;
1326
11.2k
    if (ByCopy) {
1327
      // If we are capturing the object referred to by '*this' by copy, ignore
1328
      // any cv qualifiers inherited from the type of the member function for
1329
      // the type of the closure-type's corresponding data member and any use
1330
      // of 'this'.
1331
128
      CaptureType = ThisTy->getPointeeType();
1332
128
      CaptureType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1333
128
    }
1334
11.2k
1335
11.2k
    bool isNested = NumCapturingClosures > 1;
1336
11.2k
    CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);
1337
11.2k
  }
1338
1.01M
  return false;
1339
1.01M
}
1340
1341
205k
ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
1342
  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1343
  /// is a non-lvalue expression whose value is the address of the object for
1344
  /// which the function is called.
1345
205k
1346
205k
  QualType ThisTy = getCurrentThisType();
1347
205k
  if (ThisTy.isNull())
1348
49
    return Diag(Loc, diag::err_invalid_this_use);
1349
205k
  return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
1350
205k
}
1351
1352
Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type,
1353
1.01M
                             bool IsImplicit) {
1354
1.01M
  auto *This = new (Context) CXXThisExpr(Loc, Type, IsImplicit);
1355
1.01M
  MarkThisReferenced(This);
1356
1.01M
  return This;
1357
1.01M
}
1358
1359
1.01M
void Sema::MarkThisReferenced(CXXThisExpr *This) {
1360
1.01M
  CheckCXXThisCapture(This->getExprLoc());
1361
1.01M
}
1362
1363
772k
bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1364
  // If we're outside the body of a member function, then we'll have a specified
1365
  // type for 'this'.
1366
772k
  if (CXXThisTypeOverride.isNull())
1367
771k
    return false;
1368
558
1369
  // Determine whether we're looking into a class that's currently being
1370
  // defined.
1371
558
  CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1372
558
  return Class && Class->isBeingDefined();
1373
558
}
1374
1375
/// Parse construction of a specified type.
1376
/// Can be interpreted either as function-style casting ("int(x)")
1377
/// or class type construction ("ClassType(x,y,z)")
1378
/// or creation of a value-initialized type ("int()").
1379
ExprResult
1380
Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
1381
                                SourceLocation LParenOrBraceLoc,
1382
                                MultiExprArg exprs,
1383
                                SourceLocation RParenOrBraceLoc,
1384
299k
                                bool ListInitialization) {
1385
299k
  if (!TypeRep)
1386
5
    return ExprError();
1387
299k
1388
299k
  TypeSourceInfo *TInfo;
1389
299k
  QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1390
299k
  if (!TInfo)
1391
0
    TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
1392
299k
1393
299k
  auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1394
299k
                                          RParenOrBraceLoc, ListInitialization);
1395
  // Avoid creating a non-type-dependent expression that contains typos.
1396
  // Non-type-dependent expressions are liable to be discarded without
1397
  // checking for embedded typos.
1398
299k
  if (!Result.isInvalid() && 
Result.get()->isInstantiationDependent()299k
&&
1399
227k
      !Result.get()->isTypeDependent())
1400
4.10k
    Result = CorrectDelayedTyposInExpr(Result.get());
1401
295k
  else if (Result.isInvalid())
1402
194
    Result = CreateRecoveryExpr(TInfo->getTypeLoc().getBeginLoc(),
1403
194
                                RParenOrBraceLoc, exprs, Ty);
1404
299k
  return Result;
1405
299k
}
1406
1407
ExprResult
1408
Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1409
                                SourceLocation LParenOrBraceLoc,
1410
                                MultiExprArg Exprs,
1411
                                SourceLocation RParenOrBraceLoc,
1412
363k
                                bool ListInitialization) {
1413
363k
  QualType Ty = TInfo->getType();
1414
363k
  SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1415
363k
1416
363k
  if (Ty->isDependentType() || 
CallExpr::hasAnyTypeDependentArguments(Exprs)136k
) {
1417
    // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1418
    // directly. We work around this by dropping the locations of the braces.
1419
230k
    SourceRange Locs = ListInitialization
1420
7.48k
                           ? SourceRange()
1421
223k
                           : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1422
230k
    return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(),
1423
230k
                                              Exprs, Locs.getEnd());
1424
230k
  }
1425
133k
1426
133k
  assert((!ListInitialization ||
1427
133k
          (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1428
133k
         "List initialization must have initializer list as expression.");
1429
133k
  SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1430
133k
1431
133k
  InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1432
133k
  InitializationKind Kind =
1433
133k
      Exprs.size()
1434
72.8k
          ? ListInitialization
1435
8.02k
                ? InitializationKind::CreateDirectList(
1436
8.02k
                      TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1437
64.8k
                : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1438
64.8k
                                                   RParenOrBraceLoc)
1439
60.1k
          : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1440
60.1k
                                            RParenOrBraceLoc);
1441
133k
1442
  // C++1z [expr.type.conv]p1:
1443
  //   If the type is a placeholder for a deduced class type, [...perform class
1444
  //   template argument deduction...]
1445
133k
  DeducedType *Deduced = Ty->getContainedDeducedType();
1446
133k
  if (Deduced && 
isa<DeducedTemplateSpecializationType>(Deduced)66
) {
1447
66
    Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1448
66
                                                     Kind, Exprs);
1449
66
    if (Ty.isNull())
1450
5
      return ExprError();
1451
61
    Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1452
61
  }
1453
133k
1454
  // C++ [expr.type.conv]p1:
1455
  // If the expression list is a parenthesized single expression, the type
1456
  // conversion expression is equivalent (in definedness, and if defined in
1457
  // meaning) to the corresponding cast expression.
1458
133k
  if (Exprs.size() == 1 && 
!ListInitialization68.7k
&&
1459
60.7k
      !isa<InitListExpr>(Exprs[0])) {
1460
60.7k
    Expr *Arg = Exprs[0];
1461
60.7k
    return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1462
60.7k
                                      RParenOrBraceLoc);
1463
60.7k
  }
1464
72.2k
1465
  //   For an expression of the form T(), T shall not be an array type.
1466
72.2k
  QualType ElemTy = Ty;
1467
72.2k
  if (Ty->isArrayType()) {
1468
69
    if (!ListInitialization)
1469
5
      return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1470
5
                         << FullRange);
1471
64
    ElemTy = Context.getBaseElementType(Ty);
1472
64
  }
1473
72.2k
1474
  // There doesn't seem to be an explicit rule against this but sanity demands
1475
  // we only construct objects with object types.
1476
72.2k
  if (Ty->isFunctionType())
1477
16
    return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1478
16
                       << Ty << FullRange);
1479
72.2k
1480
  // C++17 [expr.type.conv]p2:
1481
  //   If the type is cv void and the initializer is (), the expression is a
1482
  //   prvalue of the specified type that performs no initialization.
1483
72.2k
  if (!Ty->isVoidType() &&
1484
72.2k
      RequireCompleteType(TyBeginLoc, ElemTy,
1485
72.2k
                          diag::err_invalid_incomplete_type_use, FullRange))
1486
40
    return ExprError();
1487
72.2k
1488
  //   Otherwise, the expression is a prvalue of the specified type whose
1489
  //   result object is direct-initialized (11.6) with the initializer.
1490
72.2k
  InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1491
72.2k
  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1492
72.2k
1493
72.2k
  if (Result.isInvalid())
1494
166
    return Result;
1495
72.0k
1496
72.0k
  Expr *Inner = Result.get();
1497
72.0k
  if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1498
6.49k
    Inner = BTE->getSubExpr();
1499
72.0k
  if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1500
16.6k
      !isa<CXXScalarValueInitExpr>(Inner)) {
1501
    // If we created a CXXTemporaryObjectExpr, that node also represents the
1502
    // functional cast. Otherwise, create an explicit cast to represent
1503
    // the syntactic form of a functional-style cast that was used here.
1504
    //
1505
    // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1506
    // would give a more consistent AST representation than using a
1507
    // CXXTemporaryObjectExpr. It's also weird that the functional cast
1508
    // is sometimes handled by initialization and sometimes not.
1509
7.43k
    QualType ResultType = Result.get()->getType();
1510
7.43k
    SourceRange Locs = ListInitialization
1511
7.38k
                           ? SourceRange()
1512
52
                           : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1513
7.43k
    Result = CXXFunctionalCastExpr::Create(
1514
7.43k
        Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1515
7.43k
        Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(),
1516
7.43k
        Locs.getBegin(), Locs.getEnd());
1517
7.43k
  }
1518
72.0k
1519
72.0k
  return Result;
1520
72.0k
}
1521
1522
941
bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) {
1523
  // [CUDA] Ignore this function, if we can't call it.
1524
941
  const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
1525
941
  if (getLangOpts().CUDA &&
1526
192
      IdentifyCUDAPreference(Caller, Method) <= CFP_WrongSide)
1527
95
    return false;
1528
846
1529
846
  SmallVector<const FunctionDecl*, 4> PreventedBy;
1530
846
  bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1531
846
1532
846
  if (Result || 
!getLangOpts().CUDA144
||
PreventedBy.empty()18
)
1533
828
    return Result;
1534
18
1535
  // In case of CUDA, return true if none of the 1-argument deallocator
1536
  // functions are actually callable.
1537
22
  
return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) 18
{
1538
22
    assert(FD->getNumParams() == 1 &&
1539
22
           "Only single-operand functions should be in PreventedBy");
1540
22
    return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice;
1541
22
  });
1542
18
}
1543
1544
/// Determine whether the given function is a non-placement
1545
/// deallocation function.
1546
18.5k
static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1547
18.5k
  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1548
840
    return S.isUsualDeallocationFunction(Method);
1549
17.6k
1550
17.6k
  if (FD->getOverloadedOperator() != OO_Delete &&
1551
4.34k
      FD->getOverloadedOperator() != OO_Array_Delete)
1552
0
    return false;
1553
17.6k
1554
17.6k
  unsigned UsualParams = 1;
1555
17.6k
1556
17.6k
  if (S.getLangOpts().SizedDeallocation && 
UsualParams < FD->getNumParams()182
&&
1557
122
      S.Context.hasSameUnqualifiedType(
1558
122
          FD->getParamDecl(UsualParams)->getType(),
1559
122
          S.Context.getSizeType()))
1560
75
    ++UsualParams;
1561
17.6k
1562
17.6k
  if (S.getLangOpts().AlignedAllocation && 
UsualParams < FD->getNumParams()1.44k
&&
1563
1.03k
      S.Context.hasSameUnqualifiedType(
1564
1.03k
          FD->getParamDecl(UsualParams)->getType(),
1565
1.03k
          S.Context.getTypeDeclType(S.getStdAlignValT())))
1566
701
    ++UsualParams;
1567
17.6k
1568
17.6k
  return UsualParams == FD->getNumParams();
1569
17.6k
}
1570
1571
namespace {
1572
  struct UsualDeallocFnInfo {
1573
10.4k
    UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1574
    UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1575
        : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1576
          Destroying(false), HasSizeT(false), HasAlignValT(false),
1577
17.7k
          CUDAPref(Sema::CFP_Native) {
1578
      // A function template declaration is never a usual deallocation function.
1579
17.7k
      if (!FD)
1580
3
        return;
1581
17.7k
      unsigned NumBaseParams = 1;
1582
17.7k
      if (FD->isDestroyingOperatorDelete()) {
1583
136
        Destroying = true;
1584
136
        ++NumBaseParams;
1585
136
      }
1586
17.7k
1587
17.7k
      if (NumBaseParams < FD->getNumParams() &&
1588
11.9k
          S.Context.hasSameUnqualifiedType(
1589
11.9k
              FD->getParamDecl(NumBaseParams)->getType(),
1590
1.17k
              S.Context.getSizeType())) {
1591
1.17k
        ++NumBaseParams;
1592
1.17k
        HasSizeT = true;
1593
1.17k
      }
1594
17.7k
1595
17.7k
      if (NumBaseParams < FD->getNumParams() &&
1596
11.3k
          FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1597
6.06k
        ++NumBaseParams;
1598
6.06k
        HasAlignValT = true;
1599
6.06k
      }
1600
17.7k
1601
      // In CUDA, determine how much we'd like / dislike to call this.
1602
17.7k
      if (S.getLangOpts().CUDA)
1603
238
        if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1604
238
          CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
1605
17.7k
    }
1606
1607
25.5k
    explicit operator bool() const { return FD; }
1608
1609
    bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1610
645
                      bool WantAlign) const {
1611
      // C++ P0722:
1612
      //   A destroying operator delete is preferred over a non-destroying
1613
      //   operator delete.
1614
645
      if (Destroying != Other.Destroying)
1615
32
        return Destroying;
1616
613
1617
      // C++17 [expr.delete]p10:
1618
      //   If the type has new-extended alignment, a function with a parameter
1619
      //   of type std::align_val_t is preferred; otherwise a function without
1620
      //   such a parameter is preferred
1621
613
      if (HasAlignValT != Other.HasAlignValT)
1622
493
        return HasAlignValT == WantAlign;
1623
120
1624
120
      if (HasSizeT != Other.HasSizeT)
1625
106
        return HasSizeT == WantSize;
1626
14
1627
      // Use CUDA call preference as a tiebreaker.
1628
14
      return CUDAPref > Other.CUDAPref;
1629
14
    }
1630
1631
    DeclAccessPair Found;
1632
    FunctionDecl *FD;
1633
    bool Destroying, HasSizeT, HasAlignValT;
1634
    Sema::CUDAFunctionPreference CUDAPref;
1635
  };
1636
}
1637
1638
/// Determine whether a type has new-extended alignment. This may be called when
1639
/// the type is incomplete (for a delete-expression with an incomplete pointee
1640
/// type), in which case it will conservatively return false if the alignment is
1641
/// not known.
1642
10.2k
static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1643
10.2k
  return S.getLangOpts().AlignedAllocation &&
1644
875
         S.getASTContext().getTypeAlignIfKnown(AllocType) >
1645
875
             S.getASTContext().getTargetInfo().getNewAlign();
1646
10.2k
}
1647
1648
/// Select the correct "usual" deallocation function to use from a selection of
1649
/// deallocation functions (either global or class-scope).
1650
static UsualDeallocFnInfo resolveDeallocationOverload(
1651
    Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1652
10.4k
    llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1653
10.4k
  UsualDeallocFnInfo Best;
1654
10.4k
1655
28.0k
  for (auto I = R.begin(), E = R.end(); I != E; 
++I17.6k
) {
1656
17.6k
    UsualDeallocFnInfo Info(S, I.getPair());
1657
17.6k
    if (!Info || 
!isNonPlacementDeallocationFunction(S, Info.FD)17.6k
||
1658
6.42k
        Info.CUDAPref == Sema::CFP_Never)
1659
11.2k
      continue;
1660
6.40k
1661
6.40k
    if (!Best) {
1662
5.80k
      Best = Info;
1663
5.80k
      if (BestFns)
1664
1.80k
        BestFns->push_back(Info);
1665
5.80k
      continue;
1666
5.80k
    }
1667
602
1668
602
    if (Best.isBetterThan(Info, WantSize, WantAlign))
1669
447
      continue;
1670
155
1671
    //   If more than one preferred function is found, all non-preferred
1672
    //   functions are eliminated from further consideration.
1673
155
    if (BestFns && 
Info.isBetterThan(Best, WantSize, WantAlign)43
)
1674
39
      BestFns->clear();
1675
155
1676
155
    Best = Info;
1677
155
    if (BestFns)
1678
43
      BestFns->push_back(Info);
1679
155
  }
1680
10.4k
1681
10.4k
  return Best;
1682
10.4k
}
1683
1684
/// Determine whether a given type is a class for which 'delete[]' would call
1685
/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1686
/// we need to store the array size (even if the type is
1687
/// trivially-destructible).
1688
static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1689
1.05k
                                         QualType allocType) {
1690
1.05k
  const RecordType *record =
1691
1.05k
    allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1692
1.05k
  if (!record) 
return false681
;
1693
372
1694
  // Try to find an operator delete[] in class scope.
1695
372
1696
372
  DeclarationName deleteName =
1697
372
    S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1698
372
  LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1699
372
  S.LookupQualifiedName(ops, record->getDecl());
1700
372
1701
  // We're just doing this for information.
1702
372
  ops.suppressDiagnostics();
1703
372
1704
  // Very likely: there's no operator delete[].
1705
372
  if (ops.empty()) 
return false328
;
1706
44
1707
  // If it's ambiguous, it should be illegal to call operator delete[]
1708
  // on this thing, so it doesn't matter if we allocate extra space or not.
1709
44
  if (ops.isAmbiguous()) 
return false0
;
1710
44
1711
  // C++17 [expr.delete]p10:
1712
  //   If the deallocation functions have class scope, the one without a
1713
  //   parameter of type std::size_t is selected.
1714
44
  auto Best = resolveDeallocationOverload(
1715
44
      S, ops, /*WantSize*/false,
1716
44
      /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1717
44
  return Best && Best.HasSizeT;
1718
44
}
1719
1720
/// Parsed a C++ 'new' expression (C++ 5.3.4).
1721
///
1722
/// E.g.:
1723
/// @code new (memory) int[size][4] @endcode
1724
/// or
1725
/// @code ::new Foo(23, "hello") @endcode
1726
///
1727
/// \param StartLoc The first location of the expression.
1728
/// \param UseGlobal True if 'new' was prefixed with '::'.
1729
/// \param PlacementLParen Opening paren of the placement arguments.
1730
/// \param PlacementArgs Placement new arguments.
1731
/// \param PlacementRParen Closing paren of the placement arguments.
1732
/// \param TypeIdParens If the type is in parens, the source range.
1733
/// \param D The type to be allocated, as well as array dimensions.
1734
/// \param Initializer The initializing expression or initializer-list, or null
1735
///   if there is none.
1736
ExprResult
1737
Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1738
                  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1739
                  SourceLocation PlacementRParen, SourceRange TypeIdParens,
1740
23.5k
                  Declarator &D, Expr *Initializer) {
1741
23.5k
  Optional<Expr *> ArraySize;
1742
  // If the specified type is an array, unwrap it and save the expression.
1743
23.5k
  if (D.getNumTypeObjects() > 0 &&
1744
1.21k
      D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1745
1.17k
    DeclaratorChunk &Chunk = D.getTypeObject(0);
1746
1.17k
    if (D.getDeclSpec().hasAutoTypeSpec())
1747
0
      return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1748
0
        << D.getSourceRange());
1749
1.17k
    if (Chunk.Arr.hasStatic)
1750
0
      return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1751
0
        << D.getSourceRange());
1752
1.17k
    if (!Chunk.Arr.NumElts && 
!Initializer25
)
1753
7
      return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1754
7
        << D.getSourceRange());
1755
1.17k
1756
1.17k
    ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1757
1.17k
    D.DropFirstTypeObject();
1758
1.17k
  }
1759
23.5k
1760
  // Every dimension shall be of constant size.
1761
23.5k
  if (ArraySize) {
1762
1.21k
    for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; 
++I47
) {
1763
128
      if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1764
71
        break;
1765
57
1766
57
      DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1767
57
      if (Expr *NumElts = (Expr *)Array.NumElts) {
1768
57
        if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1769
57
          if (getLangOpts().CPlusPlus14) {
1770
            // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1771
            //   shall be a converted constant expression (5.19) of type std::size_t
1772
            //   and shall evaluate to a strictly positive value.
1773
18
            llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));
1774
18
            Array.NumElts
1775
18
             = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1776
18
                                                CCEK_ArrayBound)
1777
18
                 .get();
1778
39
          } else {
1779
39
            Array.NumElts
1780
39
              = VerifyIntegerConstantExpression(NumElts, nullptr,
1781
39
                                                diag::err_new_array_nonconst)
1782
39
                  .get();
1783
39
          }
1784
57
          if (!Array.NumElts)
1785
10
            return ExprError();
1786
57
        }
1787
57
      }
1788
57
    }
1789
1.17k
  }
1790
23.5k
1791
23.5k
  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1792
23.5k
  QualType AllocType = TInfo->getType();
1793
23.5k
  if (D.isInvalidType())
1794
11
    return ExprError();
1795
23.5k
1796
23.5k
  SourceRange DirectInitRange;
1797
23.5k
  if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1798
20.6k
    DirectInitRange = List->getSourceRange();
1799
23.5k
1800
23.5k
  return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1801
23.5k
                     PlacementLParen, PlacementArgs, PlacementRParen,
1802
23.5k
                     TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
1803
23.5k
                     Initializer);
1804
23.5k
}
1805
1806
static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1807
1.20k
                                       Expr *Init) {
1808
1.20k
  if (!Init)
1809
1.07k
    return true;
1810
128
  if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1811
50
    return PLE->getNumExprs() == 0;
1812
78
  if (isa<ImplicitValueInitExpr>(Init))
1813
0
    return true;
1814
78
  else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1815
0
    return !CCE->isListInitialization() &&
1816
0
           CCE->getConstructor()->isDefaultConstructor();
1817
78
  else if (Style == CXXNewExpr::ListInit) {
1818
78
    assert(isa<InitListExpr>(Init) &&
1819
78
           "Shouldn't create list CXXConstructExprs for arrays.");
1820
78
    return true;
1821
78
  }
1822
0
  return false;
1823
0
}
1824
1825
bool
1826
1.90M
Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const {
1827
1.90M
  if (!getLangOpts().AlignedAllocationUnavailable)
1828
1.90M
    return false;
1829
479
  if (FD.isDefined())
1830
180
    return false;
1831
299
  Optional<unsigned> AlignmentParam;
1832
299
  if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) &&
1833
259
      AlignmentParam.hasValue())
1834
161
    return true;
1835
138
  return false;
1836
138
}
1837
1838
// Emit a diagnostic if an aligned allocation/deallocation function that is not
1839
// implemented in the standard library is selected.
1840
void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1841
1.90M
                                                SourceLocation Loc) {
1842
1.90M
  if (isUnavailableAlignedAllocationFunction(FD)) {
1843
161
    const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
1844
161
    StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1845
161
        getASTContext().getTargetInfo().getPlatformName());
1846
161
    VersionTuple OSVersion = alignedAllocMinVersion(T.getOS());
1847
161
1848
161
    OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator();
1849
161
    bool IsDelete = Kind == OO_Delete || 
Kind == OO_Array_Delete105
;
1850
161
    Diag(Loc, diag::err_aligned_allocation_unavailable)
1851
161
        << IsDelete << FD.getType().getAsString() << OSName
1852
161
        << OSVersion.getAsString() << OSVersion.empty();
1853
161
    Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
1854
161
  }
1855
1.90M
}
1856
1857
ExprResult
1858
Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1859
                  SourceLocation PlacementLParen,
1860
                  MultiExprArg PlacementArgs,
1861
                  SourceLocation PlacementRParen,
1862
                  SourceRange TypeIdParens,
1863
                  QualType AllocType,
1864
                  TypeSourceInfo *AllocTypeInfo,
1865
                  Optional<Expr *> ArraySize,
1866
                  SourceRange DirectInitRange,
1867
24.9k
                  Expr *Initializer) {
1868
24.9k
  SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1869
24.9k
  SourceLocation StartLoc = Range.getBegin();
1870
24.9k
1871
24.9k
  CXXNewExpr::InitializationStyle initStyle;
1872
24.9k
  if (DirectInitRange.isValid()) {
1873
21.7k
    assert(Initializer && "Have parens but no initializer.");
1874
21.7k
    initStyle = CXXNewExpr::CallInit;
1875
3.24k
  } else if (Initializer && 
isa<InitListExpr>(Initializer)170
)
1876
170
    initStyle = CXXNewExpr::ListInit;
1877
3.07k
  else {
1878
3.07k
    assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1879
3.07k
            isa<CXXConstructExpr>(Initializer)) &&
1880
3.07k
           "Initializer expression that cannot have been implicitly created.");
1881
3.07k
    initStyle = CXXNewExpr::NoInit;
1882
3.07k
  }
1883
24.9k
1884
24.9k
  Expr **Inits = &Initializer;
1885
21.8k
  unsigned NumInits = Initializer ? 1 : 
03.07k
;
1886
24.9k
  if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1887
21.7k
    assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1888
21.7k
    Inits = List->getExprs();
1889
21.7k
    NumInits = List->getNumExprs();
1890
21.7k
  }
1891
24.9k
1892
  // C++11 [expr.new]p15:
1893
  //   A new-expression that creates an object of type T initializes that
1894
  //   object as follows:
1895
24.9k
  InitializationKind Kind
1896
      //     - If the new-initializer is omitted, the object is default-
1897
      //       initialized (8.5); if no initialization is performed,
1898
      //       the object has indeterminate value
1899
24.9k
      = initStyle == CXXNewExpr::NoInit
1900
3.07k
            ? InitializationKind::CreateDefault(TypeRange.getBegin())
1901
            //     - Otherwise, the new-initializer is interpreted according to
1902
            //     the
1903
            //       initialization rules of 8.5 for direct-initialization.
1904
21.8k
            : initStyle == CXXNewExpr::ListInit
1905
170
                  ? InitializationKind::CreateDirectList(
1906
170
                        TypeRange.getBegin(), Initializer->getBeginLoc(),
1907
170
                        Initializer->getEndLoc())
1908
21.7k
                  : InitializationKind::CreateDirect(TypeRange.getBegin(),
1909
21.7k
                                                     DirectInitRange.getBegin(),
1910
21.7k
                                                     DirectInitRange.getEnd());
1911
24.9k
1912
  // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1913
24.9k
  auto *Deduced = AllocType->getContainedDeducedType();
1914
24.9k
  if (Deduced && 
isa<DeducedTemplateSpecializationType>(Deduced)66
) {
1915
14
    if (ArraySize)
1916
0
      return ExprError(
1917
0
          Diag(ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
1918
0
               diag::err_deduced_class_template_compound_type)
1919
0
          << /*array*/ 2
1920
0
          << (ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
1921
14
1922
14
    InitializedEntity Entity
1923
14
      = InitializedEntity::InitializeNew(StartLoc, AllocType);
1924
14
    AllocType = DeduceTemplateSpecializationFromInitializer(
1925
14
        AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1926
14
    if (AllocType.isNull())
1927
0
      return ExprError();
1928
24.9k
  } else if (Deduced) {
1929
52
    bool Braced = (initStyle == CXXNewExpr::ListInit);
1930
52
    if (NumInits == 1) {
1931
49
      if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1932
20
        Inits = p->getInits();
1933
20
        NumInits = p->getNumInits();
1934
20
        Braced = true;
1935
20
      }
1936
49
    }
1937
52
1938
52
    if (initStyle == CXXNewExpr::NoInit || 
NumInits == 051
)
1939
6
      return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1940
6
                       << AllocType << TypeRange);
1941
46
    if (NumInits > 1) {
1942
10
      Expr *FirstBad = Inits[1];
1943
10
      return ExprError(Diag(FirstBad->getBeginLoc(),
1944
10
                            diag::err_auto_new_ctor_multiple_expressions)
1945
10
                       << AllocType << TypeRange);
1946
10
    }
1947
36
    if (Braced && 
!getLangOpts().CPlusPlus177
)
1948
5
      Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
1949
5
          << AllocType << TypeRange;
1950
36
    Expr *Deduce = Inits[0];
1951
36
    QualType DeducedType;
1952
36
    if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
1953
1
      return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1954
1
                       << AllocType << Deduce->getType()
1955
1
                       << TypeRange << Deduce->getSourceRange());
1956
35
    if (DeducedType.isNull())
1957
1
      return ExprError();
1958
34
    AllocType = DeducedType;
1959
34
  }
1960
24.9k
1961
  // Per C++0x [expr.new]p5, the type being constructed may be a
1962
  // typedef of an array type.
1963
24.9k
  if (!ArraySize) {
1964
23.6k
    if (const ConstantArrayType *Array
1965
6
                              = Context.getAsConstantArrayType(AllocType)) {
1966
6
      ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1967
6
                                         Context.getSizeType(),
1968
6
                                         TypeRange.getEnd());
1969
6
      AllocType = Array->getElementType();
1970
6
    }
1971
23.6k
  }
1972
24.9k
1973
24.9k
  if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1974
57
    return ExprError();
1975
24.8k
1976
  // In ARC, infer 'retaining' for the allocated
1977
24.8k
  if (getLangOpts().ObjCAutoRefCount &&
1978
31
      AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1979
14
      AllocType->isObjCLifetimeType()) {
1980
0
    AllocType = Context.getLifetimeQualifiedType(AllocType,
1981
0
                                    AllocType->getObjCARCImplicitLifetime());
1982
0
  }
1983
24.8k
1984
24.8k
  QualType ResultType = Context.getPointerType(AllocType);
1985
24.8k
1986
24.8k
  if (ArraySize && 
*ArraySize1.23k
&&
1987
1.20k
      (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
1988
4
    ExprResult result = CheckPlaceholderExpr(*ArraySize);
1989
4
    if (result.isInvalid()) 
return ExprError()0
;
1990
4
    ArraySize = result.get();
1991
4
  }
1992
  // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1993
  //   integral or enumeration type with a non-negative value."
1994
  // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1995
  //   enumeration type, or a class type for which a single non-explicit
1996
  //   conversion function to integral or unscoped enumeration type exists.
1997
  // C++1y [expr.new]p6: The expression [...] is implicitly converted to
1998
  //   std::size_t.
1999
24.8k
  llvm::Optional<uint64_t> KnownArraySize;
2000
24.8k
  if (ArraySize && 
*ArraySize1.23k
&&
!(*ArraySize)->isTypeDependent()1.20k
) {
2001
1.20k
    ExprResult ConvertedSize;
2002
1.20k
    if (getLangOpts().CPlusPlus14) {
2003
408
      assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
2004
408
2005
408
      ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(),
2006
408
                                                AA_Converting);
2007
408
2008
408
      if (!ConvertedSize.isInvalid() &&
2009
403
          (*ArraySize)->getType()->getAs<RecordType>())
2010
        // Diagnose the compatibility of this conversion.
2011
12
        Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
2012
12
          << (*ArraySize)->getType() << 0 << "'size_t'";
2013
793
    } else {
2014
793
      class SizeConvertDiagnoser : public ICEConvertDiagnoser {
2015
793
      protected:
2016
793
        Expr *ArraySize;
2017
793
2018
793
      public:
2019
793
        SizeConvertDiagnoser(Expr *ArraySize)
2020
793
            : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
2021
793
              ArraySize(ArraySize) {}
2022
793
2023
793
        SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
2024
5
                                             QualType T) override {
2025
5
          return S.Diag(Loc, diag::err_array_size_not_integral)
2026
5
                   << S.getLangOpts().CPlusPlus11 << T;
2027
5
        }
2028
793
2029
793
        SemaDiagnosticBuilder diagnoseIncomplete(
2030
0
            Sema &S, SourceLocation Loc, QualType T) override {
2031
0
          return S.Diag(Loc, diag::err_array_size_incomplete_type)
2032
0
                   << T << ArraySize->getSourceRange();
2033
0
        }
2034
793
2035
793
        SemaDiagnosticBuilder diagnoseExplicitConv(
2036
1
            Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
2037
1
          return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
2038
1
        }
2039
793
2040
793
        SemaDiagnosticBuilder noteExplicitConv(
2041
1
            Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2042
1
          return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2043
1
                   << ConvTy->isEnumeralType() << ConvTy;
2044
1
        }
2045
793
2046
793
        SemaDiagnosticBuilder diagnoseAmbiguous(
2047
9
            Sema &S, SourceLocation Loc, QualType T) override {
2048
9
          return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
2049
9
        }
2050
793
2051
793
        SemaDiagnosticBuilder noteAmbiguous(
2052
18
            Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2053
18
          return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2054
18
                   << ConvTy->isEnumeralType() << ConvTy;
2055
18
        }
2056
793
2057
793
        SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2058
793
                                                 QualType T,
2059
15
                                                 QualType ConvTy) override {
2060
15
          return S.Diag(Loc,
2061
15
                        S.getLangOpts().CPlusPlus11
2062
8
                          ? diag::warn_cxx98_compat_array_size_conversion
2063
7
                          : diag::ext_array_size_conversion)
2064
15
                   << T << ConvTy->isEnumeralType() << ConvTy;
2065
15
        }
2066
793
      } SizeDiagnoser(*ArraySize);
2067
793
2068
793
      ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
2069
793
                                                          SizeDiagnoser);
2070
793
    }
2071
1.20k
    if (ConvertedSize.isInvalid())
2072
5
      return ExprError();
2073
1.19k
2074
1.19k
    ArraySize = ConvertedSize.get();
2075
1.19k
    QualType SizeType = (*ArraySize)->getType();
2076
1.19k
2077
1.19k
    if (!SizeType->isIntegralOrUnscopedEnumerationType())
2078
14
      return ExprError();
2079
1.18k
2080
    // C++98 [expr.new]p7:
2081
    //   The expression in a direct-new-declarator shall have integral type
2082
    //   with a non-negative value.
2083
    //
2084
    // Let's see if this is a constant < 0. If so, we reject it out of hand,
2085
    // per CWG1464. Otherwise, if it's not a constant, we must have an
2086
    // unparenthesized array type.
2087
1.18k
    if (!(*ArraySize)->isValueDependent()) {
2088
      // We've already performed any required implicit conversion to integer or
2089
      // unscoped enumeration type.
2090
      // FIXME: Per CWG1464, we are required to check the value prior to
2091
      // converting to size_t. This will never find a negative array size in
2092
      // C++14 onwards, because Value is always unsigned here!
2093
896
      if (Optional<llvm::APSInt> Value =
2094
623
              (*ArraySize)->getIntegerConstantExpr(Context)) {
2095
623
        if (Value->isSigned() && 
Value->isNegative()365
) {
2096
4
          return ExprError(Diag((*ArraySize)->getBeginLoc(),
2097
4
                                diag::err_typecheck_negative_array_size)
2098
4
                           << (*ArraySize)->getSourceRange());
2099
4
        }
2100
619
2101
619
        if (!AllocType->isDependentType()) {
2102
603
          unsigned ActiveSizeBits = ConstantArrayType::getNumAddressingBits(
2103
603
              Context, AllocType, *Value);
2104
603
          if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2105
6
            return ExprError(
2106
6
                Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2107
6
                << Value->toString(10) << (*ArraySize)->getSourceRange());
2108
613
        }
2109
613
2110
613
        KnownArraySize = Value->getZExtValue();
2111
273
      } else if (TypeIdParens.isValid()) {
2112
        // Can't have dynamic array size when the type-id is in parentheses.
2113
6
        Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2114
6
            << (*ArraySize)->getSourceRange()
2115
6
            << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2116
6
            << FixItHint::CreateRemoval(TypeIdParens.getEnd());
2117
6
2118
6
        TypeIdParens = SourceRange();
2119
6
      }
2120
896
    }
2121
1.18k
2122
    // Note that we do *not* convert the argument in any way.  It can
2123
    // be signed, larger than size_t, whatever.
2124
1.18k
  }
2125
24.8k
2126
24.8k
  FunctionDecl *OperatorNew = nullptr;
2127
24.8k
  FunctionDecl *OperatorDelete = nullptr;
2128
24.8k
  unsigned Alignment =
2129
20.1k
      AllocType->isDependentType() ? 0 : 
Context.getTypeAlign(AllocType)4.71k
;
2130
24.8k
  unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2131
24.8k
  bool PassAlignment = getLangOpts().AlignedAllocation &&
2132
1.15k
                       Alignment > NewAlignment;
2133
24.8k
2134
16.4k
  AllocationFunctionScope Scope = UseGlobal ? AFS_Global : 
AFS_Both8.40k
;
2135
24.8k
  if (!AllocType->isDependentType() &&
2136
4.71k
      !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
2137
4.71k
      FindAllocationFunctions(
2138
4.71k
          StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope,
2139
4.71k
          AllocType, ArraySize.hasValue(), PassAlignment, PlacementArgs,
2140
4.71k
          OperatorNew, OperatorDelete))
2141
40
    return ExprError();
2142
24.8k
2143
  // If this is an array allocation, compute whether the usual array
2144
  // deallocation function for the type has a size_t parameter.
2145
24.8k
  bool UsualArrayDeleteWantsSize = false;
2146
24.8k
  if (ArraySize && 
!AllocType->isDependentType()1.20k
)
2147
1.02k
    UsualArrayDeleteWantsSize =
2148
1.02k
        doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
2149
24.8k
2150
24.8k
  SmallVector<Expr *, 8> AllPlaceArgs;
2151
24.8k
  if (OperatorNew) {
2152
4.67k
    auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2153
24
    VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2154
4.64k
                                                    : VariadicDoesNotApply;
2155
4.67k
2156
    // We've already converted the placement args, just fill in any default
2157
    // arguments. Skip the first parameter because we don't have a corresponding
2158
    // argument. Skip the second parameter too if we're passing in the
2159
    // alignment; we've already filled it in.
2160
4.55k
    unsigned NumImplicitArgs = PassAlignment ? 
2119
: 1;
2161
4.67k
    if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2162
4.67k
                               NumImplicitArgs, PlacementArgs, AllPlaceArgs,
2163
4.67k
                               CallType))
2164
1
      return ExprError();
2165
4.67k
2166
4.67k
    if (!AllPlaceArgs.empty())
2167
1.36k
      PlacementArgs = AllPlaceArgs;
2168
4.67k
2169
    // We would like to perform some checking on the given `operator new` call,
2170
    // but the PlacementArgs does not contain the implicit arguments,
2171
    // namely allocation size and maybe allocation alignment,
2172
    // so we need to conjure them.
2173
4.67k
2174
4.67k
    QualType SizeTy = Context.getSizeType();
2175
4.67k
    unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2176
4.67k
2177
4.67k
    llvm::APInt SingleEltSize(
2178
4.67k
        SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity());
2179
4.67k
2180
    // How many bytes do we want to allocate here?
2181
4.67k
    llvm::Optional<llvm::APInt> AllocationSize;
2182
4.67k
    if (!ArraySize.hasValue() && 
!AllocType->isDependentType()3.64k
) {
2183
      // For non-array operator new, we only want to allocate one element.
2184
3.64k
      AllocationSize = SingleEltSize;
2185
1.02k
    } else if (KnownArraySize.hasValue() && 
!AllocType->isDependentType()595
) {
2186
      // For array operator new, only deal with static array size case.
2187
595
      bool Overflow;
2188
595
      AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize)
2189
595
                           .umul_ov(SingleEltSize, Overflow);
2190
595
      (void)Overflow;
2191
595
      assert(
2192
595
          !Overflow &&
2193
595
          "Expected that all the overflows would have been handled already.");
2194
595
    }
2195
4.67k
2196
4.67k
    IntegerLiteral AllocationSizeLiteral(
2197
4.67k
        Context,
2198
4.67k
        AllocationSize.getValueOr(llvm::APInt::getNullValue(SizeTyWidth)),
2199
4.67k
        SizeTy, SourceLocation());
2200
    // Otherwise, if we failed to constant-fold the allocation size, we'll
2201
    // just give up and pass-in something opaque, that isn't a null pointer.
2202
4.67k
    OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_RValue,
2203
4.67k
                                         OK_Ordinary, /*SourceExpr=*/nullptr);
2204
4.67k
2205
    // Let's synthesize the alignment argument in case we will need it.
2206
    // Since we *really* want to allocate these on stack, this is slightly ugly
2207
    // because there might not be a `std::align_val_t` type.
2208
4.67k
    EnumDecl *StdAlignValT = getStdAlignValT();
2209
4.67k
    QualType AlignValT =
2210
2.73k
        StdAlignValT ? Context.getTypeDeclType(StdAlignValT) : 
SizeTy1.93k
;
2211
4.67k
    IntegerLiteral AlignmentLiteral(
2212
4.67k
        Context,
2213
4.67k
        llvm::APInt(Context.getTypeSize(SizeTy),
2214
4.67k
                    Alignment / Context.getCharWidth()),
2215
4.67k
        SizeTy, SourceLocation());
2216
4.67k
    ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT,
2217
4.67k
                                      CK_IntegralCast, &AlignmentLiteral,
2218
4.67k
                                      VK_RValue, FPOptionsOverride());
2219
4.67k
2220
    // Adjust placement args by prepending conjured size and alignment exprs.
2221
4.67k
    llvm::SmallVector<Expr *, 8> CallArgs;
2222
4.67k
    CallArgs.reserve(NumImplicitArgs + PlacementArgs.size());
2223
4.67k
    CallArgs.emplace_back(AllocationSize.hasValue()
2224
4.23k
                              ? static_cast<Expr *>(&AllocationSizeLiteral)
2225
433
                              : &OpaqueAllocationSize);
2226
4.67k
    if (PassAlignment)
2227
119
      CallArgs.emplace_back(&DesiredAlignment);
2228
4.67k
    CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end());
2229
4.67k
2230
4.67k
    DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs);
2231
4.67k
2232
4.67k
    checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs,
2233
4.67k
              /*IsMemberFunction=*/false, StartLoc, Range, CallType);
2234
4.67k
2235
    // Warn if the type is over-aligned and is being allocated by (unaligned)
2236
    // global operator new.
2237
4.67k
    if (PlacementArgs.empty() && 
!PassAlignment3.30k
&&
2238
3.23k
        (OperatorNew->isImplicit() ||
2239
1.37k
         (OperatorNew->getBeginLoc().isValid() &&
2240
3.01k
          
getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())1.36k
))) {
2241
3.01k
      if (Alignment > NewAlignment)
2242
33
        Diag(StartLoc, diag::warn_overaligned_type)
2243
33
            << AllocType
2244
33
            << unsigned(Alignment / Context.getCharWidth())
2245
33
            << unsigned(NewAlignment / Context.getCharWidth());
2246
3.01k
    }
2247
4.67k
  }
2248
24.8k
2249
  // Array 'new' can't have any initializers except empty parentheses.
2250
  // Initializer lists are also allowed, in C++11. Rely on the parser for the
2251
  // dialect distinction.
2252
24.8k
  if (ArraySize && 
!isLegalArrayNewInitializer(initStyle, Initializer)1.20k
) {
2253
15
    SourceRange InitRange(Inits[0]->getBeginLoc(),
2254
15
                          Inits[NumInits - 1]->getEndLoc());
2255
15
    Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2256
15
    return ExprError();
2257
15
  }
2258
24.8k
2259
  // If we can perform the initialization, and we've not already done so,
2260
  // do it now.
2261
24.8k
  if (!AllocType->isDependentType() &&
2262
4.66k
      !Expr::hasAnyTypeDependentArguments(
2263
4.64k
          llvm::makeArrayRef(Inits, NumInits))) {
2264
    // The type we initialize is the complete type, including the array bound.
2265
4.64k
    QualType InitType;
2266
4.64k
    if (KnownArraySize)
2267
583
      InitType = Context.getConstantArrayType(
2268
583
          AllocType,
2269
583
          llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2270
583
                      *KnownArraySize),
2271
583
          *ArraySize, ArrayType::Normal, 0);
2272
4.05k
    else if (ArraySize)
2273
428
      InitType =
2274
428
          Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2275
3.63k
    else
2276
3.63k
      InitType = AllocType;
2277
4.64k
2278
4.64k
    InitializedEntity Entity
2279
4.64k
      = InitializedEntity::InitializeNew(StartLoc, InitType);
2280
4.64k
    InitializationSequence InitSeq(*this, Entity, Kind,
2281
4.64k
                                   MultiExprArg(Inits, NumInits));
2282
4.64k
    ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
2283
4.64k
                                          MultiExprArg(Inits, NumInits));
2284
4.64k
    if (FullInit.isInvalid())
2285
58
      return ExprError();
2286
4.58k
2287
    // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2288
    // we don't want the initialized object to be destructed.
2289
    // FIXME: We should not create these in the first place.
2290
4.58k
    if (CXXBindTemporaryExpr *Binder =
2291
0
            dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2292
0
      FullInit = Binder->getSubExpr();
2293
4.58k
2294
4.58k
    Initializer = FullInit.get();
2295
4.58k
2296
    // FIXME: If we have a KnownArraySize, check that the array bound of the
2297
    // initializer is no greater than that constant value.
2298
4.58k
2299
4.58k
    if (ArraySize && 
!*ArraySize998
) {
2300
20
      auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
2301
20
      if (CAT) {
2302
        // FIXME: Track that the array size was inferred rather than explicitly
2303
        // specified.
2304
17
        ArraySize = IntegerLiteral::Create(
2305
17
            Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
2306
3
      } else {
2307
3
        Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
2308
3
            << Initializer->getSourceRange();
2309
3
      }
2310
20
    }
2311
4.58k
  }
2312
24.8k
2313
  // Mark the new and delete operators as referenced.
2314
24.7k
  if (OperatorNew) {
2315
4.60k
    if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2316
0
      return ExprError();
2317
4.60k
    MarkFunctionReferenced(StartLoc, OperatorNew);
2318
4.60k
  }
2319
24.7k
  if (OperatorDelete) {
2320
2.25k
    if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2321
37
      return ExprError();
2322
2.21k
    MarkFunctionReferenced(StartLoc, OperatorDelete);
2323
2.21k
  }
2324
24.7k
2325
24.7k
  return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2326
24.7k
                            PassAlignment, UsualArrayDeleteWantsSize,
2327
24.7k
                            PlacementArgs, TypeIdParens, ArraySize, initStyle,
2328
24.7k
                            Initializer, ResultType, AllocTypeInfo, Range,
2329
24.7k
                            DirectInitRange);
2330
24.7k
}
2331
2332
/// Checks that a type is suitable as the allocated type
2333
/// in a new-expression.
2334
bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
2335
24.9k
                              SourceRange R) {
2336
  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2337
  //   abstract class type or array thereof.
2338
24.9k
  if (AllocType->isFunctionType())
2339
0
    return Diag(Loc, diag::err_bad_new_type)
2340
0
      << AllocType << 0 << R;
2341
24.9k
  else if (AllocType->isReferenceType())
2342
3
    return Diag(Loc, diag::err_bad_new_type)
2343
3
      << AllocType << 1 << R;
2344
24.9k
  else if (!AllocType->isDependentType() &&
2345
4.80k
           RequireCompleteSizedType(
2346
4.80k
               Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R))
2347
36
    return true;
2348
24.9k
  else if (RequireNonAbstractType(Loc, AllocType,
2349
24.9k
                                  diag::err_allocation_of_abstract_type))
2350
8
    return true;
2351
24.8k
  else if (AllocType->isVariablyModifiedType())
2352
2
    return Diag(Loc, diag::err_variably_modified_new_type)
2353
2
             << AllocType;
2354
24.8k
  else if (AllocType.getAddressSpace() != LangAS::Default &&
2355
8
           !getLangOpts().OpenCLCPlusPlus)
2356
8
    return Diag(Loc, diag::err_address_space_qualified_new)
2357
8
      << AllocType.getUnqualifiedType()
2358
8
      << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
2359
24.8k
  else if (getLangOpts().ObjCAutoRefCount) {
2360
31
    if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2361
0
      QualType BaseAllocType = Context.getBaseElementType(AT);
2362
0
      if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2363
0
          BaseAllocType->isObjCLifetimeType())
2364
0
        return Diag(Loc, diag::err_arc_new_array_without_ownership)
2365
0
          << BaseAllocType;
2366
24.8k
    }
2367
31
  }
2368
24.8k
2369
24.8k
  return false;
2370
24.8k
}
2371
2372
static bool resolveAllocationOverload(
2373
    Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2374
    bool &PassAlignment, FunctionDecl *&Operator,
2375
4.98k
    OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2376
4.98k
  OverloadCandidateSet Candidates(R.getNameLoc(),
2377
4.98k
                                  OverloadCandidateSet::CSK_Normal);
2378
4.98k
  for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2379
20.6k
       Alloc != AllocEnd; 
++Alloc15.6k
) {
2380
    // Even member operator new/delete are implicitly treated as
2381
    // static, so don't use AddMemberCandidate.
2382
15.6k
    NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2383
15.6k
2384
15.6k
    if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2385
59
      S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2386
59
                                     /*ExplicitTemplateArgs=*/nullptr, Args,
2387
59
                                     Candidates,
2388
59
                                     /*SuppressUserConversions=*/false);
2389
59
      continue;
2390
59
    }
2391
15.6k
2392
15.6k
    FunctionDecl *Fn = cast<FunctionDecl>(D);
2393
15.6k
    S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2394
15.6k
                           /*SuppressUserConversions=*/false);
2395
15.6k
  }
2396
4.98k
2397
  // Do the resolution.
2398
4.98k
  OverloadCandidateSet::iterator Best;
2399
4.98k
  switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2400
4.86k
  case OR_Success: {
2401
    // Got one!
2402
4.86k
    FunctionDecl *FnDecl = Best->Function;
2403
4.86k
    if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2404
4.86k
                                Best->FoundDecl) == Sema::AR_inaccessible)
2405
6
      return true;
2406
4.85k
2407
4.85k
    Operator = FnDecl;
2408
4.85k
    return false;
2409
4.85k
  }
2410
4.85k
2411
109
  case OR_No_Viable_Function:
2412
    // C++17 [expr.new]p13:
2413
    //   If no matching function is found and the allocated object type has
2414
    //   new-extended alignment, the alignment argument is removed from the
2415
    //   argument list, and overload resolution is performed again.
2416
109
    if (PassAlignment) {
2417
86
      PassAlignment = false;
2418
86
      AlignArg = Args[1];
2419
86
      Args.erase(Args.begin() + 1);
2420
86
      return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2421
86
                                       Operator, &Candidates, AlignArg,
2422
86
                                       Diagnose);
2423
86
    }
2424
23
2425
    // MSVC will fall back on trying to find a matching global operator new
2426
    // if operator new[] cannot be found.  Also, MSVC will leak by not
2427
    // generating a call to operator delete or operator delete[], but we
2428
    // will not replicate that bug.
2429
    // FIXME: Find out how this interacts with the std::align_val_t fallback
2430
    // once MSVC implements it.
2431
23
    if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2432
5
        S.Context.getLangOpts().MSVCCompat) {
2433
4
      R.clear();
2434
4
      R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2435
4
      S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2436
      // FIXME: This will give bad diagnostics pointing at the wrong functions.
2437
4
      return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2438
4
                                       Operator, /*Candidates=*/nullptr,
2439
4
                                       /*AlignArg=*/nullptr, Diagnose);
2440
4
    }
2441
19
2442
19
    if (Diagnose) {
2443
17
      PartialDiagnosticAt PD(R.getNameLoc(), S.PDiag(diag::err_ovl_no_viable_function_in_call)
2444
17
          << R.getLookupName() << Range);
2445
17
2446
      // If we have aligned candidates, only note the align_val_t candidates
2447
      // from AlignedCandidates and the non-align_val_t candidates from
2448
      // Candidates.
2449
17
      if (AlignedCandidates) {
2450
0
        auto IsAligned = [](OverloadCandidate &C) {
2451
0
          return C.Function->getNumParams() > 1 &&
2452
0
                 C.Function->getParamDecl(1)->getType()->isAlignValT();
2453
0
        };
2454
0
        auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2455
0
2456
        // This was an overaligned allocation, so list the aligned candidates
2457
        // first.
2458
0
        Args.insert(Args.begin() + 1, AlignArg);
2459
0
        AlignedCandidates->NoteCandidates(PD, S, OCD_AllCandidates, Args, "",
2460
0
                                          R.getNameLoc(), IsAligned);
2461
0
        Args.erase(Args.begin() + 1);
2462
0
        Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2463
0
                                  IsUnaligned);
2464
17
      } else {
2465
17
        Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args);
2466
17
      }
2467
17
    }
2468
19
    return true;
2469
19
2470
3
  case OR_Ambiguous:
2471
3
    if (Diagnose) {
2472
3
      Candidates.NoteCandidates(
2473
3
          PartialDiagnosticAt(R.getNameLoc(),
2474
3
                              S.PDiag(diag::err_ovl_ambiguous_call)
2475
3
                                  << R.getLookupName() << Range),
2476
3
          S, OCD_AmbiguousCandidates, Args);
2477
3
    }
2478
3
    return true;
2479
19
2480
12
  case OR_Deleted: {
2481
12
    if (Diagnose) {
2482
12
      Candidates.NoteCandidates(
2483
12
          PartialDiagnosticAt(R.getNameLoc(),
2484
12
                              S.PDiag(diag::err_ovl_deleted_call)
2485
12
                                  << R.getLookupName() << Range),
2486
12
          S, OCD_AllCandidates, Args);
2487
12
    }
2488
12
    return true;
2489
0
  }
2490
0
  }
2491
0
  llvm_unreachable("Unreachable, bad result from BestViableFunction");
2492
0
}
2493
2494
bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2495
                                   AllocationFunctionScope NewScope,
2496
                                   AllocationFunctionScope DeleteScope,
2497
                                   QualType AllocType, bool IsArray,
2498
                                   bool &PassAlignment, MultiExprArg PlaceArgs,
2499
                                   FunctionDecl *&OperatorNew,
2500
                                   FunctionDecl *&OperatorDelete,
2501
5.16k
                                   bool Diagnose) {
2502
  // --- Choosing an allocation function ---
2503
  // C++ 5.3.4p8 - 14 & 18
2504
  // 1) If looking in AFS_Global scope for allocation functions, only look in
2505
  //    the global scope. Else, if AFS_Class, only look in the scope of the
2506
  //    allocated class. If AFS_Both, look in both.
2507
  // 2) If an array size is given, look for operator new[], else look for
2508
  //   operator new.
2509
  // 3) The first argument is always size_t. Append the arguments from the
2510
  //   placement form.
2511
5.16k
2512
5.16k
  SmallVector<Expr*, 8> AllocArgs;
2513
4.95k
  AllocArgs.reserve((PassAlignment ? 
2211
: 1) + PlaceArgs.size());
2514
5.16k
2515
  // We don't care about the actual value of these arguments.
2516
  // FIXME: Should the Sema create the expression and embed it in the syntax
2517
  // tree? Or should the consumer just recalculate the value?
2518
  // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2519
5.16k
  IntegerLiteral Size(Context, llvm::APInt::getNullValue(
2520
5.16k
                      Context.getTargetInfo().getPointerWidth(0)),
2521
5.16k
                      Context.getSizeType(),
2522
5.16k
                      SourceLocation());
2523
5.16k
  AllocArgs.push_back(&Size);
2524
5.16k
2525
5.16k
  QualType AlignValT = Context.VoidTy;
2526
5.16k
  if (PassAlignment) {
2527
211
    DeclareGlobalNewDelete();
2528
211
    AlignValT = Context.getTypeDeclType(getStdAlignValT());
2529
211
  }
2530
5.16k
  CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2531
5.16k
  if (PassAlignment)
2532
211
    AllocArgs.push_back(&Align);
2533
5.16k
2534
5.16k
  AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2535
5.16k
2536
  // C++ [expr.new]p8:
2537
  //   If the allocated type is a non-array type, the allocation
2538
  //   function's name is operator new and the deallocation function's
2539
  //   name is operator delete. If the allocated type is an array
2540
  //   type, the allocation function's name is operator new[] and the
2541
  //   deallocation function's name is operator delete[].
2542
5.16k
  DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
2543
4.13k
      IsArray ? 
OO_Array_New1.03k
: OO_New);
2544
5.16k
2545
5.16k
  QualType AllocElemType = Context.getBaseElementType(AllocType);
2546
5.16k
2547
  // Find the allocation function.
2548
5.16k
  {
2549
5.16k
    LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2550
5.16k
2551
    // C++1z [expr.new]p9:
2552
    //   If the new-expression begins with a unary :: operator, the allocation
2553
    //   function's name is looked up in the global scope. Otherwise, if the
2554
    //   allocated type is a class type T or array thereof, the allocation
2555
    //   function's name is looked up in the scope of T.
2556
5.16k
    if (AllocElemType->isRecordType() && 
NewScope != AFS_Global3.57k
)
2557
2.79k
      LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2558
5.16k
2559
    // We can see ambiguity here if the allocation function is found in
2560
    // multiple base classes.
2561
5.16k
    if (R.isAmbiguous())
2562
0
      return true;
2563
5.16k
2564
    //   If this lookup fails to find the name, or if the allocated type is not
2565
    //   a class type, the allocation function's name is looked up in the
2566
    //   global scope.
2567
5.16k
    if (R.empty()) {
2568
4.91k
      if (NewScope == AFS_Class)
2569
264
        return true;
2570
4.65k
2571
4.65k
      LookupQualifiedName(R, Context.getTranslationUnitDecl());
2572
4.65k
    }
2573
5.16k
2574
4.89k
    if (getLangOpts().OpenCLCPlusPlus && 
R.empty()7
) {
2575
2
      if (PlaceArgs.empty()) {
2576
1
        Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2577
1
      } else {
2578
1
        Diag(StartLoc, diag::err_openclcxx_placement_new);
2579
1
      }
2580
2
      return true;
2581
2
    }
2582
4.89k
2583
4.89k
    assert(!R.empty() && "implicitly declared allocation functions not found");
2584
4.89k
    assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2585
4.89k
2586
    // We do our own custom access checks below.
2587
4.89k
    R.suppressDiagnostics();
2588
4.89k
2589
4.89k
    if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2590
4.89k
                                  OperatorNew, /*Candidates=*/nullptr,
2591
4.89k
                                  /*AlignArg=*/nullptr, Diagnose))
2592
40
      return true;
2593
4.85k
  }
2594
4.85k
2595
  // We don't need an operator delete if we're running under -fno-exceptions.
2596
4.85k
  if (!getLangOpts().Exceptions) {
2597
2.40k
    OperatorDelete = nullptr;
2598
2.40k
    return false;
2599
2.40k
  }
2600
2.44k
2601
  // Note, the name of OperatorNew might have been changed from array to
2602
  // non-array by resolveAllocationOverload.
2603
2.44k
  DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2604
2.44k
      OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2605
442
          ? OO_Array_Delete
2606
2.00k
          : OO_Delete);
2607
2.44k
2608
  // C++ [expr.new]p19:
2609
  //
2610
  //   If the new-expression begins with a unary :: operator, the
2611
  //   deallocation function's name is looked up in the global
2612
  //   scope. Otherwise, if the allocated type is a class type T or an
2613
  //   array thereof, the deallocation function's name is looked up in
2614
  //   the scope of T. If this lookup fails to find the name, or if
2615
  //   the allocated type is not a class type or array thereof, the
2616
  //   deallocation function's name is looked up in the global scope.
2617
2.44k
  LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2618
2.44k
  if (AllocElemType->isRecordType() && 
DeleteScope != AFS_Global1.91k
) {
2619
1.38k
    auto *RD =
2620
1.38k
        cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl());
2621
1.38k
    LookupQualifiedName(FoundDelete, RD);
2622
1.38k
  }
2623
2.44k
  if (FoundDelete.isAmbiguous())
2624
0
    return true; // FIXME: clean up expressions?
2625
2.44k
2626
2.44k
  bool FoundGlobalDelete = FoundDelete.empty();
2627
2.44k
  if (FoundDelete.empty()) {
2628
2.32k
    if (DeleteScope == AFS_Class)
2629
0
      return true;
2630
2.32k
2631
2.32k
    DeclareGlobalNewDelete();
2632
2.32k
    LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2633
2.32k
  }
2634
2.44k
2635
2.44k
  FoundDelete.suppressDiagnostics();
2636
2.44k
2637
2.44k
  SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
2638
2.44k
2639
  // Whether we're looking for a placement operator delete is dictated
2640
  // by whether we selected a placement operator new, not by whether
2641
  // we had explicit placement arguments.  This matters for things like
2642
  //   struct A { void *operator new(size_t, int = 0); ... };
2643
  //   A *a = new A()
2644
  //
2645
  // We don't have any definition for what a "placement allocation function"
2646
  // is, but we assume it's any allocation function whose
2647
  // parameter-declaration-clause is anything other than (size_t).
2648
  //
2649
  // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2650
  // This affects whether an exception from the constructor of an overaligned
2651
  // type uses the sized or non-sized form of aligned operator delete.
2652
2.44k
  bool isPlacementNew = !PlaceArgs.empty() || 
OperatorNew->param_size() != 11.53k
||
2653
1.46k
                        OperatorNew->isVariadic();
2654
2.44k
2655
2.44k
  if (isPlacementNew) {
2656
    // C++ [expr.new]p20:
2657
    //   A declaration of a placement deallocation function matches the
2658
    //   declaration of a placement allocation function if it has the
2659
    //   same number of parameters and, after parameter transformations
2660
    //   (8.3.5), all parameter types except the first are
2661
    //   identical. [...]
2662
    //
2663
    // To perform this comparison, we compute the function type that
2664
    // the deallocation function should have, and use that type both
2665
    // for template argument deduction and for comparison purposes.
2666
988
    QualType ExpectedFunctionType;
2667
988
    {
2668
988
      auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2669
988
2670
988
      SmallVector<QualType, 4> ArgTypes;
2671
988
      ArgTypes.push_back(Context.VoidPtrTy);
2672
2.03k
      for (unsigned I = 1, N = Proto->getNumParams(); I < N; 
++I1.04k
)
2673
1.04k
        ArgTypes.push_back(Proto->getParamType(I));
2674
988
2675
988
      FunctionProtoType::ExtProtoInfo EPI;
2676
      // FIXME: This is not part of the standard's rule.
2677
988
      EPI.Variadic = Proto->isVariadic();
2678
988
2679
988
      ExpectedFunctionType
2680
988
        = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2681
988
    }
2682
988
2683
988
    for (LookupResult::iterator D = FoundDelete.begin(),
2684
988
                             DEnd = FoundDelete.end();
2685
5.49k
         D != DEnd; 
++D4.50k
) {
2686
4.50k
      FunctionDecl *Fn = nullptr;
2687
4.50k
      if (FunctionTemplateDecl *FnTmpl =
2688
36
              dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2689
        // Perform template argument deduction to try to match the
2690
        // expected function type.
2691
36
        TemplateDeductionInfo Info(StartLoc);
2692
36
        if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2693
36
                                    Info))
2694
17
          continue;
2695
4.46k
      } else
2696
4.46k
        Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2697
4.50k
2698
4.48k
      if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2699
4.48k
                                                  ExpectedFunctionType,
2700
4.48k
                                                  /*AdjustExcpetionSpec*/true),
2701
4.48k
                              ExpectedFunctionType))
2702
917
        Matches.push_back(std::make_pair(D.getPair(), Fn));
2703
4.48k
    }
2704
988
2705
988
    if (getLangOpts().CUDA)
2706
0
      EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2707
1.46k
  } else {
2708
    // C++1y [expr.new]p22:
2709
    //   For a non-placement allocation function, the normal deallocation
2710
    //   function lookup is used
2711
    //
2712
    // Per [expr.delete]p10, this lookup prefers a member operator delete
2713
    // without a size_t argument, but prefers a non-member operator delete
2714
    // with a size_t where possible (which it always is in this case).
2715
1.46k
    llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2716
1.46k
    UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2717
1.46k
        *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2718
1.46k
        /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2719
1.46k
        &BestDeallocFns);
2720
1.46k
    if (Selected)
2721
1.46k
      Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2722
1
    else {
2723
      // If we failed to select an operator, all remaining functions are viable
2724
      // but ambiguous.
2725
1
      for (auto Fn : BestDeallocFns)
2726
0
        Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2727
1
    }
2728
1.46k
  }
2729
2.44k
2730
  // C++ [expr.new]p20:
2731
  //   [...] If the lookup finds a single matching deallocation
2732
  //   function, that function will be called; otherwise, no
2733
  //   deallocation function will be called.
2734
2.44k
  if (Matches.size() == 1) {
2735
2.37k
    OperatorDelete = Matches[0].second;
2736
2.37k
2737
    // C++1z [expr.new]p23:
2738
    //   If the lookup finds a usual deallocation function (3.7.4.2)
2739
    //   with a parameter of type std::size_t and that function, considered
2740
    //   as a placement deallocation function, would have been
2741
    //   selected as a match for the allocation function, the program
2742
    //   is ill-formed.
2743
2.37k
    if (getLangOpts().CPlusPlus11 && 
isPlacementNew2.29k
&&
2744
908
        isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2745
132
      UsualDeallocFnInfo Info(*this,
2746
132
                              DeclAccessPair::make(OperatorDelete, AS_public));
2747
      // Core issue, per mail to core reflector, 2016-10-09:
2748
      //   If this is a member operator delete, and there is a corresponding
2749
      //   non-sized member operator delete, this isn't /really/ a sized
2750
      //   deallocation function, it just happens to have a size_t parameter.
2751
132
      bool IsSizedDelete = Info.HasSizeT;
2752
132
      if (IsSizedDelete && 
!FoundGlobalDelete12
) {
2753
11
        auto NonSizedDelete =
2754
11
            resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2755
11
                                        /*WantAlign*/Info.HasAlignValT);
2756
11
        if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2757
3
            NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2758
3
          IsSizedDelete = false;
2759
11
      }
2760
132
2761
132
      if (IsSizedDelete) {
2762
9
        SourceRange R = PlaceArgs.empty()
2763
0
                            ? SourceRange()
2764
9
                            : SourceRange(PlaceArgs.front()->getBeginLoc(),
2765
9
                                          PlaceArgs.back()->getEndLoc());
2766
9
        Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2767
9
        if (!OperatorDelete->isImplicit())
2768
9
          Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2769
9
              << DeleteName;
2770
9
      }
2771
132
    }
2772
2.37k
2773
2.37k
    CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2774
2.37k
                          Matches[0].first);
2775
72
  } else if (!Matches.empty()) {
2776
    // We found multiple suitable operators. Per [expr.new]p20, that means we
2777
    // call no 'operator delete' function, but we should at least warn the user.
2778
    // FIXME: Suppress this warning if the construction cannot throw.
2779
0
    Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2780
0
      << DeleteName << AllocElemType;
2781
0
2782
0
    for (auto &Match : Matches)
2783
0
      Diag(Match.second->getLocation(),
2784
0
           diag::note_member_declared_here) << DeleteName;
2785
0
  }
2786
2.44k
2787
2.44k
  return false;
2788
2.44k
}
2789
2790
/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2791
/// delete. These are:
2792
/// @code
2793
///   // C++03:
2794
///   void* operator new(std::size_t) throw(std::bad_alloc);
2795
///   void* operator new[](std::size_t) throw(std::bad_alloc);
2796
///   void operator delete(void *) throw();
2797
///   void operator delete[](void *) throw();
2798
///   // C++11:
2799
///   void* operator new(std::size_t);
2800
///   void* operator new[](std::size_t);
2801
///   void operator delete(void *) noexcept;
2802
///   void operator delete[](void *) noexcept;
2803
///   // C++1y:
2804
///   void* operator new(std::size_t);
2805
///   void* operator new[](std::size_t);
2806
///   void operator delete(void *) noexcept;
2807
///   void operator delete[](void *) noexcept;
2808
///   void operator delete(void *, std::size_t) noexcept;
2809
///   void operator delete[](void *, std::size_t) noexcept;
2810
/// @endcode
2811
/// Note that the placement and nothrow forms of new are *not* implicitly
2812
/// declared. Their use requires including \<new\>.
2813
38.9k
void Sema::DeclareGlobalNewDelete() {
2814
38.9k
  if (GlobalNewDeleteDeclared)
2815
36.7k
    return;
2816
2.20k
2817
  // The implicitly declared new and delete operators
2818
  // are not supported in OpenCL.
2819
2.20k
  if (getLangOpts().OpenCLCPlusPlus)
2820
15
    return;
2821
2.18k
2822
  // C++ [basic.std.dynamic]p2:
2823
  //   [...] The following allocation and deallocation functions (18.4) are
2824
  //   implicitly declared in global scope in each translation unit of a
2825
  //   program
2826
  //
2827
  //     C++03:
2828
  //     void* operator new(std::size_t) throw(std::bad_alloc);
2829
  //     void* operator new[](std::size_t) throw(std::bad_alloc);
2830
  //     void  operator delete(void*) throw();
2831
  //     void  operator delete[](void*) throw();
2832
  //     C++11:
2833
  //     void* operator new(std::size_t);
2834
  //     void* operator new[](std::size_t);
2835
  //     void  operator delete(void*) noexcept;
2836
  //     void  operator delete[](void*) noexcept;
2837
  //     C++1y:
2838
  //     void* operator new(std::size_t);
2839
  //     void* operator new[](std::size_t);
2840
  //     void  operator delete(void*) noexcept;
2841
  //     void  operator delete[](void*) noexcept;
2842
  //     void  operator delete(void*, std::size_t) noexcept;
2843
  //     void  operator delete[](void*, std::size_t) noexcept;
2844
  //
2845
  //   These implicit declarations introduce only the function names operator
2846
  //   new, operator new[], operator delete, operator delete[].
2847
  //
2848
  // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2849
  // "std" or "bad_alloc" as necessary to form the exception specification.
2850
  // However, we do not make these implicit declarations visible to name
2851
  // lookup.
2852
2.18k
  if (!StdBadAlloc && 
!getLangOpts().CPlusPlus111.55k
) {
2853
    // The "std::bad_alloc" class has not yet been declared, so build it
2854
    // implicitly.
2855
179
    StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2856
179
                                        getOrCreateStdNamespace(),
2857
179
                                        SourceLocation(), SourceLocation(),
2858
179
                                      &PP.getIdentifierTable().get("bad_alloc"),
2859
179
                                        nullptr);
2860
179
    getStdBadAlloc()->setImplicit(true);
2861
179
  }
2862
2.18k
  if (!StdAlignValT && 
getLangOpts().AlignedAllocation1.62k
) {
2863
    // The "std::align_val_t" enum class has not yet been declared, so build it
2864
    // implicitly.
2865
177
    auto *AlignValT = EnumDecl::Create(
2866
177
        Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2867
177
        &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2868
177
    AlignValT->setIntegerType(Context.getSizeType());
2869
177
    AlignValT->setPromotionType(Context.getSizeType());
2870
177
    AlignValT->setImplicit(true);
2871
177
    StdAlignValT = AlignValT;
2872
177
  }
2873
2.18k
2874
2.18k
  GlobalNewDeleteDeclared = true;
2875
2.18k
2876
2.18k
  QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2877
2.18k
  QualType SizeT = Context.getSizeType();
2878
2.18k
2879
2.18k
  auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2880
8.74k
                                              QualType Return, QualType Param) {
2881
8.74k
    llvm::SmallVector<QualType, 3> Params;
2882
8.74k
    Params.push_back(Param);
2883
8.74k
2884
    // Create up to four variants of the function (sized/aligned).
2885
8.74k
    bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2886
116
                           (Kind == OO_Delete || 
Kind == OO_Array_Delete87
);
2887
8.74k
    bool HasAlignedVariant = getLangOpts().AlignedAllocation;
2888
8.74k
2889
8.68k
    int NumSizeVariants = (HasSizedVariant ? 
258
: 1);
2890
7.84k
    int NumAlignVariants = (HasAlignedVariant ? 
2900
: 1);
2891
17.5k
    for (int Sized = 0; Sized < NumSizeVariants; 
++Sized8.80k
) {
2892
8.80k
      if (Sized)
2893
58
        Params.push_back(SizeT);
2894
8.80k
2895
18.5k
      for (int Aligned = 0; Aligned < NumAlignVariants; 
++Aligned9.73k
) {
2896
9.73k
        if (Aligned)
2897
934
          Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2898
9.73k
2899
9.73k
        DeclareGlobalAllocationFunction(
2900
9.73k
            Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2901
9.73k
2902
9.73k
        if (Aligned)
2903
934
          Params.pop_back();
2904
9.73k
      }
2905
8.80k
    }
2906
8.74k
  };
2907
2.18k
2908
2.18k
  DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2909
2.18k
  DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2910
2.18k
  DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2911
2.18k
  DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
2912
2.18k
}
2913
2914
/// DeclareGlobalAllocationFunction - Declares a single implicit global
2915
/// allocation function if it doesn't already exist.
2916
void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
2917
                                           QualType Return,
2918
9.73k
                                           ArrayRef<QualType> Params) {
2919
9.73k
  DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2920
9.73k
2921
  // Check if this function is already declared.
2922
9.73k
  DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2923
9.73k
  for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2924
10.9k
       Alloc != AllocEnd; 
++Alloc1.20k
) {
2925
    // Only look at non-template functions, as it is the predefined,
2926
    // non-templated allocation function we are trying to declare here.
2927
1.72k
    if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
2928
1.72k
      if (Func->getNumParams() == Params.size()) {
2929
556
        llvm::SmallVector<QualType, 3> FuncParams;
2930
556
        for (auto *P : Func->parameters())
2931
618
          FuncParams.push_back(
2932
618
              Context.getCanonicalType(P->getType().getUnqualifiedType()));
2933
556
        if (llvm::makeArrayRef(FuncParams) == Params) {
2934
          // Make the function visible to name lookup, even if we found it in
2935
          // an unimported module. It either is an implicitly-declared global
2936
          // allocation function, or is suppressing that function.
2937
522
          Func->setVisibleDespiteOwningModule();
2938
522
          return;
2939
522
        }
2940
556
      }
2941
1.72k
    }
2942
1.72k
  }
2943
9.73k
2944
9.21k
  FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
2945
9.21k
      /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
2946
9.21k
2947
9.21k
  QualType BadAllocType;
2948
9.21k
  bool HasBadAllocExceptionSpec
2949
9.21k
    = (Name.getCXXOverloadedOperator() == OO_New ||
2950
6.93k
       Name.getCXXOverloadedOperator() == OO_Array_New);
2951
9.21k
  if (HasBadAllocExceptionSpec) {
2952
4.56k
    if (!getLangOpts().CPlusPlus11) {
2953
368
      BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
2954
368
      assert(StdBadAlloc && "Must have std::bad_alloc declared");
2955
368
      EPI.ExceptionSpec.Type = EST_Dynamic;
2956
368
      EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
2957
368
    }
2958
4.65k
  } else {
2959
4.65k
    EPI.ExceptionSpec =
2960
4.28k
        getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : 
EST_DynamicNone368
;
2961
4.65k
  }
2962
9.21k
2963
9.63k
  auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2964
9.63k
    QualType FnType = Context.getFunctionType(Return, Params, EPI);
2965
9.63k
    FunctionDecl *Alloc = FunctionDecl::Create(
2966
9.63k
        Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2967
9.63k
        FnType, /*TInfo=*/nullptr, SC_None, false, true);
2968
9.63k
    Alloc->setImplicit();
2969
    // Global allocation functions should always be visible.
2970
9.63k
    Alloc->setVisibleDespiteOwningModule();
2971
9.63k
2972
9.63k
    Alloc->addAttr(VisibilityAttr::CreateImplicit(
2973
9.63k
        Context, LangOpts.GlobalAllocationFunctionVisibilityHidden
2974
0
                     ? VisibilityAttr::Hidden
2975
9.63k
                     : VisibilityAttr::Default));
2976
9.63k
2977
9.63k
    llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2978
10.6k
    for (QualType T : Params) {
2979
10.6k
      ParamDecls.push_back(ParmVarDecl::Create(
2980
10.6k
          Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2981
10.6k
          /*TInfo=*/nullptr, SC_None, nullptr));
2982
10.6k
      ParamDecls.back()->setImplicit();
2983
10.6k
    }
2984
9.63k
    Alloc->setParams(ParamDecls);
2985
9.63k
    if (ExtraAttr)
2986
848
      Alloc->addAttr(ExtraAttr);
2987
9.63k
    AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(Alloc);
2988
9.63k
    Context.getTranslationUnitDecl()->addDecl(Alloc);
2989
9.63k
    IdResolver.tryAddTopLevelDecl(Alloc, Name);
2990
9.63k
  };
2991
9.21k
2992
9.21k
  if (!LangOpts.CUDA)
2993
8.79k
    CreateAllocationFunctionDecl(nullptr);
2994
424
  else {
2995
    // Host and device get their own declaration so each can be
2996
    // defined or re-declared independently.
2997
424
    CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2998
424
    CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
2999
424
  }
3000
9.21k
}
3001
3002
FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
3003
                                                  bool CanProvideSize,
3004
                                                  bool Overaligned,
3005
3.94k
                                                  DeclarationName Name) {
3006
3.94k
  DeclareGlobalNewDelete();
3007
3.94k
3008
3.94k
  LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
3009
3.94k
  LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
3010
3.94k
3011
  // FIXME: It's possible for this to result in ambiguity, through a
3012
  // user-declared variadic operator delete or the enable_if attribute. We
3013
  // should probably not consider those cases to be usual deallocation
3014
  // functions. But for now we just make an arbitrary choice in that case.
3015
3.94k
  auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
3016
3.94k
                                            Overaligned);
3017
3.94k
  assert(Result.FD && "operator delete missing from global scope?");
3018
3.94k
  return Result.FD;
3019
3.94k
}
3020
3021
FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
3022
1.88k
                                                          CXXRecordDecl *RD) {
3023
1.88k
  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
3024
1.88k
3025
1.88k
  FunctionDecl *OperatorDelete = nullptr;
3026
1.88k
  if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
3027
49
    return nullptr;
3028
1.83k
  if (OperatorDelete)
3029
57
    return OperatorDelete;
3030
1.77k
3031
  // If there's no class-specific operator delete, look up the global
3032
  // non-array delete.
3033
1.77k
  return FindUsualDeallocationFunction(
3034
1.77k
      Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
3035
1.77k
      Name);
3036
1.77k
}
3037
3038
bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
3039
                                    DeclarationName Name,
3040
4.98k
                                    FunctionDecl *&Operator, bool Diagnose) {
3041
4.98k
  LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
3042
  // Try to find operator delete/operator delete[] in class scope.
3043
4.98k
  LookupQualifiedName(Found, RD);
3044
4.98k
3045
4.98k
  if (Found.isAmbiguous())
3046
9
    return true;
3047
4.97k
3048
4.97k
  Found.suppressDiagnostics();
3049
4.97k
3050
4.97k
  bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
3051
4.97k
3052
  // C++17 [expr.delete]p10:
3053
  //   If the deallocation functions have class scope, the one without a
3054
  //   parameter of type std::size_t is selected.
3055
4.97k
  llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
3056
4.97k
  resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
3057
4.97k
                              /*WantAlign*/ Overaligned, &Matches);
3058
4.97k
3059
  // If we could find an overload, use it.
3060
4.97k
  if (Matches.size() == 1) {
3061
341
    Operator = cast<CXXMethodDecl>(Matches[0].FD);
3062
341
3063
    // FIXME: DiagnoseUseOfDecl?
3064
341
    if (Operator->isDeleted()) {
3065
69
      if (Diagnose) {
3066
66
        Diag(StartLoc, diag::err_deleted_function_use);
3067
66
        NoteDeletedFunction(Operator);
3068
66
      }
3069
69
      return true;
3070
69
    }
3071
272
3072
272
    if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
3073
272
                              Matches[0].Found, Diagnose) == AR_inaccessible)
3074
7
      return true;
3075
265
3076
265
    return false;
3077
265
  }
3078
4.63k
3079
  // We found multiple suitable operators; complain about the ambiguity.
3080
  // FIXME: The standard doesn't say to do this; it appears that the intent
3081
  // is that this should never happen.
3082
4.63k
  if (!Matches.empty()) {
3083
4
    if (Diagnose) {
3084
4
      Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
3085
4
        << Name << RD;
3086
4
      for (auto &Match : Matches)
3087
8
        Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
3088
4
    }
3089
4
    return true;
3090
4
  }
3091
4.62k
3092
  // We did find operator delete/operator delete[] declarations, but
3093
  // none of them were suitable.
3094
4.62k
  if (!Found.empty()) {
3095
77
    if (Diagnose) {
3096
25
      Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
3097
25
        << Name << RD;
3098
25
3099
25
      for (NamedDecl *D : Found)
3100
28
        Diag(D->getUnderlyingDecl()->getLocation(),
3101
28
             diag::note_member_declared_here) << Name;
3102
25
    }
3103
77
    return true;
3104
77
  }
3105
4.55k
3106
4.55k
  Operator = nullptr;
3107
4.55k
  return false;
3108
4.55k
}
3109
3110
namespace {
3111
/// Checks whether delete-expression, and new-expression used for
3112
///  initializing deletee have the same array form.
3113
class MismatchingNewDeleteDetector {
3114
public:
3115
  enum MismatchResult {
3116
    /// Indicates that there is no mismatch or a mismatch cannot be proven.
3117
    NoMismatch,
3118
    /// Indicates that variable is initialized with mismatching form of \a new.
3119
    VarInitMismatches,
3120
    /// Indicates that member is initialized with mismatching form of \a new.
3121
    MemberInitMismatches,
3122
    /// Indicates that 1 or more constructors' definitions could not been
3123
    /// analyzed, and they will be checked again at the end of translation unit.
3124
    AnalyzeLater
3125
  };
3126
3127
  /// \param EndOfTU True, if this is the final analysis at the end of
3128
  /// translation unit. False, if this is the initial analysis at the point
3129
  /// delete-expression was encountered.
3130
  explicit MismatchingNewDeleteDetector(bool EndOfTU)
3131
      : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
3132
4.70k
        HasUndefinedConstructors(false) {}
3133
3134
  /// Checks whether pointee of a delete-expression is initialized with
3135
  /// matching form of new-expression.
3136
  ///
3137
  /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
3138
  /// point where delete-expression is encountered, then a warning will be
3139
  /// issued immediately. If return value is \c AnalyzeLater at the point where
3140
  /// delete-expression is seen, then member will be analyzed at the end of
3141
  /// translation unit. \c AnalyzeLater is returned iff at least one constructor
3142
  /// couldn't be analyzed. If at least one constructor initializes the member
3143
  /// with matching type of new, the return value is \c NoMismatch.
3144
  MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
3145
  /// Analyzes a class member.
3146
  /// \param Field Class member to analyze.
3147
  /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3148
  /// for deleting the \p Field.
3149
  MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
3150
  FieldDecl *Field;
3151
  /// List of mismatching new-expressions used for initialization of the pointee
3152
  llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
3153
  /// Indicates whether delete-expression was in array form.
3154
  bool IsArrayForm;
3155
3156
private:
3157
  const bool EndOfTU;
3158
  /// Indicates that there is at least one constructor without body.
3159
  bool HasUndefinedConstructors;
3160
  /// Returns \c CXXNewExpr from given initialization expression.
3161
  /// \param E Expression used for initializing pointee in delete-expression.
3162
  /// E can be a single-element \c InitListExpr consisting of new-expression.
3163
  const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
3164
  /// Returns whether member is initialized with mismatching form of
3165
  /// \c new either by the member initializer or in-class initialization.
3166
  ///
3167
  /// If bodies of all constructors are not visible at the end of translation
3168
  /// unit or at least one constructor initializes member with the matching
3169
  /// form of \c new, mismatch cannot be proven, and this function will return
3170
  /// \c NoMismatch.
3171
  MismatchResult analyzeMemberExpr(const MemberExpr *ME);
3172
  /// Returns whether variable is initialized with mismatching form of
3173
  /// \c new.
3174
  ///
3175
  /// If variable is initialized with matching form of \c new or variable is not
3176
  /// initialized with a \c new expression, this function will return true.
3177
  /// If variable is initialized with mismatching form of \c new, returns false.
3178
  /// \param D Variable to analyze.
3179
  bool hasMatchingVarInit(const DeclRefExpr *D);
3180
  /// Checks whether the constructor initializes pointee with mismatching
3181
  /// form of \c new.
3182
  ///
3183
  /// Returns true, if member is initialized with matching form of \c new in
3184
  /// member initializer list. Returns false, if member is initialized with the
3185
  /// matching form of \c new in this constructor's initializer or given
3186
  /// constructor isn't defined at the point where delete-expression is seen, or
3187
  /// member isn't initialized by the constructor.
3188
  bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3189
  /// Checks whether member is initialized with matching form of
3190
  /// \c new in member initializer list.
3191
  bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3192
  /// Checks whether member is initialized with mismatching form of \c new by
3193
  /// in-class initializer.
3194
  MismatchResult analyzeInClassInitializer();
3195
};
3196
}
3197
3198
MismatchingNewDeleteDetector::MismatchResult
3199
4.13k
MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3200
4.13k
  NewExprs.clear();
3201
4.13k
  assert(DE && "Expected delete-expression");
3202
4.13k
  IsArrayForm = DE->isArrayForm();
3203
4.13k
  const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3204
4.13k
  if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3205
1.56k
    return analyzeMemberExpr(ME);
3206
2.56k
  } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3207
2.10k
    if (!hasMatchingVarInit(D))
3208
16
      return VarInitMismatches;
3209
2.55k
  }
3210
2.55k
  return NoMismatch;
3211
2.55k
}
3212
3213
const CXXNewExpr *
3214
3.06k
MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3215
3.06k
  assert(E != nullptr && "Expected a valid initializer expression");
3216
3.06k
  E = E->IgnoreParenImpCasts();
3217
3.06k
  if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3218
18
    if (ILE->getNumInits() == 1)
3219
18
      E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3220
18
  }
3221
3.06k
3222
3.06k
  return dyn_cast_or_null<const CXXNewExpr>(E);
3223
3.06k
}
3224
3225
bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3226
11.2k
    const CXXCtorInitializer *CI) {
3227
11.2k
  const CXXNewExpr *NE = nullptr;
3228
11.2k
  if (Field == CI->getMember() &&
3229
2.51k
      (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3230
58
    if (NE->isArray() == IsArrayForm)
3231
26
      return true;
3232
32
    else
3233
32
      NewExprs.push_back(NE);
3234
58
  }
3235
11.1k
  return false;
3236
11.2k
}
3237
3238
bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3239
4.74k
    const CXXConstructorDecl *CD) {
3240
4.74k
  if (CD->isImplicit())
3241
101
    return false;
3242
4.63k
  const FunctionDecl *Definition = CD;
3243
4.63k
  if (!CD->isThisDeclarationADefinition() && 
!CD->isDefined(Definition)2.08k
) {
3244
1.14k
    HasUndefinedConstructors = true;
3245
1.14k
    return EndOfTU;
3246
1.14k
  }
3247
11.2k
  
for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits())3.49k
{
3248
11.2k
    if (hasMatchingNewInCtorInit(CI))
3249
26
      return true;
3250
11.2k
  }
3251
3.46k
  return false;
3252
3.49k
}
3253
3254
MismatchingNewDeleteDetector::MismatchResult
3255
23
MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3256
23
  assert(Field != nullptr && "This should be called only for members");
3257
23
  const Expr *InitExpr = Field->getInClassInitializer();
3258
23
  if (!InitExpr)
3259
8
    return EndOfTU ? 
NoMismatch4
:
AnalyzeLater4
;
3260
15
  if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3261
9
    if (NE->isArray() != IsArrayForm) {
3262
8
      NewExprs.push_back(NE);
3263
8
      return MemberInitMismatches;
3264
8
    }
3265
7
  }
3266
7
  return NoMismatch;
3267
7
}
3268
3269
MismatchingNewDeleteDetector::MismatchResult
3270
MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3271
2.13k
                                           bool DeleteWasArrayForm) {
3272
2.13k
  assert(Field != nullptr && "Analysis requires a valid class member.");
3273
2.13k
  this->Field = Field;
3274
2.13k
  IsArrayForm = DeleteWasArrayForm;
3275
2.13k
  const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3276
4.74k
  for (const auto *CD : RD->ctors()) {
3277
4.74k
    if (hasMatchingNewInCtor(CD))
3278
576
      return NoMismatch;
3279
4.74k
  }
3280
1.55k
  if (HasUndefinedConstructors)
3281
569
    return EndOfTU ? 
NoMismatch0
: AnalyzeLater;
3282
988
  if (!NewExprs.empty())
3283
12
    return MemberInitMismatches;
3284
976
  return Field->hasInClassInitializer() ? 
analyzeInClassInitializer()23
3285
953
                                        : NoMismatch;
3286
976
}
3287
3288
MismatchingNewDeleteDetector::MismatchResult
3289
1.56k
MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3290
1.56k
  assert(ME != nullptr && "Expected a member expression");
3291
1.56k
  if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3292
1.56k
    return analyzeField(F, IsArrayForm);
3293
2
  return NoMismatch;
3294
2
}
3295
3296
2.10k
bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3297
2.10k
  const CXXNewExpr *NE = nullptr;
3298
2.10k
  if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3299
2.10k
    if (VD->hasInit() && 
(NE = getNewExprFromInitListOrExpr(VD->getInit()))531
&&
3300
367
        NE->isArray() != IsArrayForm) {
3301
16
      NewExprs.push_back(NE);
3302
16
    }
3303
2.10k
  }
3304
2.10k
  return NewExprs.empty();
3305
2.10k
}
3306
3307
static void
3308
DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3309
36
                            const MismatchingNewDeleteDetector &Detector) {
3310
36
  SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3311
36
  FixItHint H;
3312
36
  if (!Detector.IsArrayForm)
3313
27
    H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3314
9
  else {
3315
9
    SourceLocation RSquare = Lexer::findLocationAfterToken(
3316
9
        DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3317
9
        SemaRef.getLangOpts(), true);
3318
9
    if (RSquare.isValid())
3319
7
      H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3320
9
  }
3321
36
  SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3322
36
      << Detector.IsArrayForm << H;
3323
36
3324
36
  for (const auto *NE : Detector.NewExprs)
3325
48
    SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3326
48
        << Detector.IsArrayForm;
3327
36
}
3328
3329
4.41k
void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3330
4.41k
  if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3331
288
    return;
3332
4.13k
  MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3333
4.13k
  switch (Detector.analyzeDeleteExpr(DE)) {
3334
24
  case MismatchingNewDeleteDetector::VarInitMismatches:
3335
24
  case MismatchingNewDeleteDetector::MemberInitMismatches: {
3336
24
    DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
3337
24
    break;
3338
24
  }
3339
573
  case MismatchingNewDeleteDetector::AnalyzeLater: {
3340
573
    DeleteExprs[Detector.Field].push_back(
3341
573
        std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
3342
573
    break;
3343
24
  }
3344
3.53k
  case MismatchingNewDeleteDetector::NoMismatch:
3345
3.53k
    break;
3346
4.13k
  }
3347
4.13k
}
3348
3349
void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3350
573
                                     bool DeleteWasArrayForm) {
3351
573
  MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3352
573
  switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3353
0
  case MismatchingNewDeleteDetector::VarInitMismatches:
3354
0
    llvm_unreachable("This analysis should have been done for class members.");
3355
0
  case MismatchingNewDeleteDetector::AnalyzeLater:
3356
0
    llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3357
0
                     "translation unit.");
3358
12
  case MismatchingNewDeleteDetector::MemberInitMismatches:
3359
12
    DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3360
12
    break;
3361
561
  case MismatchingNewDeleteDetector::NoMismatch:
3362
561
    break;
3363
573
  }
3364
573
}
3365
3366
/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3367
/// @code ::delete ptr; @endcode
3368
/// or
3369
/// @code delete [] ptr; @endcode
3370
ExprResult
3371
Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3372
4.53k
                     bool ArrayForm, Expr *ExE) {
3373
  // C++ [expr.delete]p1:
3374
  //   The operand shall have a pointer type, or a class type having a single
3375
  //   non-explicit conversion function to a pointer type. The result has type
3376
  //   void.
3377
  //
3378
  // DR599 amends "pointer type" to "pointer to object type" in both cases.
3379
4.53k
3380
4.53k
  ExprResult Ex = ExE;
3381
4.53k
  FunctionDecl *OperatorDelete = nullptr;
3382
4.53k
  bool ArrayFormAsWritten = ArrayForm;
3383
4.53k
  bool UsualArrayDeleteWantsSize = false;
3384
4.53k
3385
4.53k
  if (!Ex.get()->isTypeDependent()) {
3386
    // Perform lvalue-to-rvalue cast, if needed.
3387
2.30k
    Ex = DefaultLvalueConversion(Ex.get());
3388
2.30k
    if (Ex.isInvalid())
3389
3
      return ExprError();
3390
2.30k
3391
2.30k
    QualType Type = Ex.get()->getType();
3392
2.30k
3393
2.30k
    class DeleteConverter : public ContextualImplicitConverter {
3394
2.30k
    public:
3395
2.30k
      DeleteConverter() : ContextualImplicitConverter(false, true) {}
3396
2.30k
3397
4.72k
      bool match(QualType ConvType) override {
3398
        // FIXME: If we have an operator T* and an operator void*, we must pick
3399
        // the operator T*.
3400
4.72k
        if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3401
4.61k
          if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3402
4.59k
            return true;
3403
131
        return false;
3404
131
      }
3405
2.30k
3406
2.30k
      SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3407
22
                                            QualType T) override {
3408
22
        return S.Diag(Loc, diag::err_delete_operand) << T;
3409
22
      }
3410
2.30k
3411
2.30k
      SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3412
3
                                               QualType T) override {
3413
3
        return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3414
3
      }
3415
2.30k
3416
2.30k
      SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3417
2.30k
                                                 QualType T,
3418
2
                                                 QualType ConvTy) override {
3419
2
        return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3420
2
      }
3421
2.30k
3422
2.30k
      SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3423
2
                                             QualType ConvTy) override {
3424
2
        return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3425
2
          << ConvTy;
3426
2
      }
3427
2.30k
3428
2.30k
      SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3429
11
                                              QualType T) override {
3430
11
        return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3431
11
      }
3432
2.30k
3433
2.30k
      SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3434
22
                                          QualType ConvTy) override {
3435
22
        return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3436
22
          << ConvTy;
3437
22
      }
3438
2.30k
3439
2.30k
      SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3440
2.30k
                                               QualType T,
3441
0
                                               QualType ConvTy) override {
3442
0
        llvm_unreachable("conversion functions are permitted");
3443
0
      }
3444
2.30k
    } Converter;
3445
2.30k
3446
2.30k
    Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3447
2.30k
    if (Ex.isInvalid())
3448
0
      return ExprError();
3449
2.30k
    Type = Ex.get()->getType();
3450
2.30k
    if (!Converter.match(Type))
3451
      // FIXME: PerformContextualImplicitConversion should return ExprError
3452
      //        itself in this case.
3453
36
      return ExprError();
3454
2.26k
3455
2.26k
    QualType Pointee = Type->castAs<PointerType>()->getPointeeType();
3456
2.26k
    QualType PointeeElem = Context.getBaseElementType(Pointee);
3457
2.26k
3458
2.26k
    if (Pointee.getAddressSpace() != LangAS::Default &&
3459
6
        !getLangOpts().OpenCLCPlusPlus)
3460
2
      return Diag(Ex.get()->getBeginLoc(),
3461
2
                  diag::err_address_space_qualified_delete)
3462
2
             << Pointee.getUnqualifiedType()
3463
2
             << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
3464
2.26k
3465
2.26k
    CXXRecordDecl *PointeeRD = nullptr;
3466
2.26k
    if (Pointee->isVoidType() && 
!isSFINAEContext()23
) {
3467
      // The C++ standard bans deleting a pointer to a non-object type, which
3468
      // effectively bans deletion of "void*". However, most compilers support
3469
      // this, so we treat it as a warning unless we're in a SFINAE context.
3470
23
      Diag(StartLoc, diag::ext_delete_void_ptr_operand)
3471
23
        << Type << Ex.get()->getSourceRange();
3472
2.24k
    } else if (Pointee->isFunctionType() || Pointee->isVoidType() ||
3473
2.24k
               Pointee->isSizelessType()) {
3474
8
      return ExprError(Diag(StartLoc, diag::err_delete_operand)
3475
8
        << Type << Ex.get()->getSourceRange());
3476
2.23k
    } else if (!Pointee->isDependentType()) {
3477
      // FIXME: This can result in errors if the definition was imported from a
3478
      // module but is hidden.
3479
2.23k
      if (!RequireCompleteType(StartLoc, Pointee,
3480
2.21k
                               diag::warn_delete_incomplete, Ex.get())) {
3481
2.21k
        if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3482
1.17k
          PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3483
2.21k
      }
3484
2.23k
    }
3485
2.26k
3486
2.25k
    if (Pointee->isArrayType() && 
!ArrayForm17
) {
3487
4
      Diag(StartLoc, diag::warn_delete_array_type)
3488
4
          << Type << Ex.get()->getSourceRange()
3489
4
          << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
3490
4
      ArrayForm = true;
3491
4
    }
3492
2.25k
3493
2.25k
    DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3494
1.49k
                                      ArrayForm ? 
OO_Array_Delete760
: OO_Delete);
3495
2.25k
3496
2.25k
    if (PointeeRD) {
3497
1.17k
      if (!UseGlobal &&
3498
1.12k
          FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3499
1.12k
                                   OperatorDelete))
3500
59
        return ExprError();
3501
1.11k
3502
      // If we're allocating an array of records, check whether the
3503
      // usual operator delete[] has a size_t parameter.
3504
1.11k
      if (ArrayForm) {
3505
        // If the user specifically asked to use the global allocator,
3506
        // we'll need to do the lookup into the class.
3507
171
        if (UseGlobal)
3508
24
          UsualArrayDeleteWantsSize =
3509
24
            doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3510
147
3511
        // Otherwise, the usual operator delete[] should be the
3512
        // function we just found.
3513
147
        else if (OperatorDelete && 
isa<CXXMethodDecl>(OperatorDelete)38
)
3514
38
          UsualArrayDeleteWantsSize =
3515
38
            UsualDeallocFnInfo(*this,
3516
38
                               DeclAccessPair::make(OperatorDelete, AS_public))
3517
38
              .HasSizeT;
3518
171
      }
3519
1.11k
3520
1.11k
      if (!PointeeRD->hasIrrelevantDestructor())
3521
656
        if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3522
656
          MarkFunctionReferenced(StartLoc,
3523
656
                                    const_cast<CXXDestructorDecl*>(Dtor));
3524
656
          if (DiagnoseUseOfDecl(Dtor, StartLoc))
3525
6
            return ExprError();
3526
1.10k
        }
3527
1.10k
3528
1.10k
      CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3529
1.10k
                           /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3530
1.10k
                           /*WarnOnNonAbstractTypes=*/!ArrayForm,
3531
1.10k
                           SourceLocation());
3532
1.10k
    }
3533
2.25k
3534
2.19k
    if (!OperatorDelete) {
3535
1.99k
      if (getLangOpts().OpenCLCPlusPlus) {
3536
3
        Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3537
3
        return ExprError();
3538
3
      }
3539
1.99k
3540
1.99k
      bool IsComplete = isCompleteType(StartLoc, Pointee);
3541
1.99k
      bool CanProvideSize =
3542
1.99k
          IsComplete && 
(1.95k
!ArrayForm1.95k
||
UsualArrayDeleteWantsSize718
||
3543
713
                         Pointee.isDestructedType());
3544
1.99k
      bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3545
1.99k
3546
      // Look for a global declaration.
3547
1.99k
      OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3548
1.99k
                                                     Overaligned, DeleteName);
3549
1.99k
    }
3550
2.19k
3551
2.18k
    MarkFunctionReferenced(StartLoc, OperatorDelete);
3552
2.18k
3553
    // Check access and ambiguity of destructor if we're going to call it.
3554
    // Note that this is required even for a virtual delete.
3555
2.18k
    bool IsVirtualDelete = false;
3556
2.18k
    if (PointeeRD) {
3557
1.10k
      if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3558
1.10k
        CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3559
1.10k
                              PDiag(diag::err_access_dtor) << PointeeElem);
3560
1.10k
        IsVirtualDelete = Dtor->isVirtual();
3561
1.10k
      }
3562
1.10k
    }
3563
2.18k
3564
2.18k
    DiagnoseUseOfDecl(OperatorDelete, StartLoc);
3565
2.18k
3566
    // Convert the operand to the type of the first parameter of operator
3567
    // delete. This is only necessary if we selected a destroying operator
3568
    // delete that we are going to call (non-virtually); converting to void*
3569
    // is trivial and left to AST consumers to handle.
3570
2.18k
    QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3571
2.18k
    if (!IsVirtualDelete && 
!ParamType->getPointeeType()->isVoidType()2.06k
) {
3572
27
      Qualifiers Qs = Pointee.getQualifiers();
3573
27
      if (Qs.hasCVRQualifiers()) {
3574
        // Qualifiers are irrelevant to this conversion; we're only looking
3575
        // for access and ambiguity.
3576
2
        Qs.removeCVRQualifiers();
3577
2
        QualType Unqual = Context.getPointerType(
3578
2
            Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3579
2
        Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3580
2
      }
3581
27
      Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3582
27
      if (Ex.isInvalid())
3583
4
        return ExprError();
3584
4.41k
    }
3585
2.18k
  }
3586
4.41k
3587
4.41k
  CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
3588
4.41k
      Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3589
4.41k
      UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3590
4.41k
  AnalyzeDeleteExprMismatch(Result);
3591
4.41k
  return Result;
3592
4.41k
}
3593
3594
static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
3595
                                            bool IsDelete,
3596
955
                                            FunctionDecl *&Operator) {
3597
955
3598
955
  DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
3599
485
      IsDelete ? 
OO_Delete470
: OO_New);
3600
955
3601
955
  LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
3602
955
  S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
3603
955
  assert(!R.empty() && "implicitly declared allocation functions not found");
3604
955
  assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3605
955
3606
  // We do our own custom access checks below.
3607
955
  R.suppressDiagnostics();
3608
955
3609
955
  SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end());
3610
955
  OverloadCandidateSet Candidates(R.getNameLoc(),
3611
955
                                  OverloadCandidateSet::CSK_Normal);
3612
955
  for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3613
5.80k
       FnOvl != FnOvlEnd; 
++FnOvl4.85k
) {
3614
    // Even member operator new/delete are implicitly treated as
3615
    // static, so don't use AddMemberCandidate.
3616
4.85k
    NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3617
4.85k
3618
4.85k
    if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3619
4
      S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3620
4
                                     /*ExplicitTemplateArgs=*/nullptr, Args,
3621
4
                                     Candidates,
3622
4
                                     /*SuppressUserConversions=*/false);
3623
4
      continue;
3624
4
    }
3625
4.84k
3626
4.84k
    FunctionDecl *Fn = cast<FunctionDecl>(D);
3627
4.84k
    S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3628
4.84k
                           /*SuppressUserConversions=*/false);
3629
4.84k
  }
3630
955
3631
955
  SourceRange Range = TheCall->getSourceRange();
3632
955
3633
  // Do the resolution.
3634
955
  OverloadCandidateSet::iterator Best;
3635
955
  switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3636
921
  case OR_Success: {
3637
    // Got one!
3638
921
    FunctionDecl *FnDecl = Best->Function;
3639
921
    assert(R.getNamingClass() == nullptr &&
3640
921
           "class members should not be considered");
3641
921
3642
921
    if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3643
20
      S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3644
12
          << (IsDelete ? 1 : 
08
) << Range;
3645
20
      S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3646
20
          << R.getLookupName() << FnDecl->getSourceRange();
3647
20
      return true;
3648
20
    }
3649
901
3650
901
    Operator = FnDecl;
3651
901
    return false;
3652
901
  }
3653
901
3654
30
  case OR_No_Viable_Function:
3655
30
    Candidates.NoteCandidates(
3656
30
        PartialDiagnosticAt(R.getNameLoc(),
3657
30
                            S.PDiag(diag::err_ovl_no_viable_function_in_call)
3658
30
                                << R.getLookupName() << Range),
3659
30
        S, OCD_AllCandidates, Args);
3660
30
    return true;
3661
901
3662
4
  case OR_Ambiguous:
3663
4
    Candidates.NoteCandidates(
3664
4
        PartialDiagnosticAt(R.getNameLoc(),
3665
4
                            S.PDiag(diag::err_ovl_ambiguous_call)
3666
4
                                << R.getLookupName() << Range),
3667
4
        S, OCD_AmbiguousCandidates, Args);
3668
4
    return true;
3669
901
3670
0
  case OR_Deleted: {
3671
0
    Candidates.NoteCandidates(
3672
0
        PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call)
3673
0
                                                << R.getLookupName() << Range),
3674
0
        S, OCD_AllCandidates, Args);
3675
0
    return true;
3676
0
  }
3677
0
  }
3678
0
  llvm_unreachable("Unreachable, bad result from BestViableFunction");
3679
0
}
3680
3681
ExprResult
3682
Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3683
957
                                             bool IsDelete) {
3684
957
  CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3685
957
  if (!getLangOpts().CPlusPlus) {
3686
2
    Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3687
1
        << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3688
2
        << "C++";
3689
2
    return ExprError();
3690
2
  }
3691
  // CodeGen assumes it can find the global new and delete to call,
3692
  // so ensure that they are declared.
3693
955
  DeclareGlobalNewDelete();
3694
955
3695
955
  FunctionDecl *OperatorNewOrDelete = nullptr;
3696
955
  if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3697
955
                                      OperatorNewOrDelete))
3698
54
    return ExprError();
3699
901
  assert(OperatorNewOrDelete && "should be found");
3700
901
3701
901
  DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3702
901
  MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3703
901
3704
901
  TheCall->setType(OperatorNewOrDelete->getReturnType());
3705
1.84k
  for (unsigned i = 0; i != TheCall->getNumArgs(); 
++i947
) {
3706
947
    QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3707
947
    InitializedEntity Entity =
3708
947
        InitializedEntity::InitializeParameter(Context, ParamTy, false);
3709
947
    ExprResult Arg = PerformCopyInitialization(
3710
947
        Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
3711
947
    if (Arg.isInvalid())
3712
0
      return ExprError();
3713
947
    TheCall->setArg(i, Arg.get());
3714
947
  }
3715
901
  auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3716
901
  assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3717
901
         "Callee expected to be implicit cast to a builtin function pointer");
3718
901
  Callee->setType(OperatorNewOrDelete->getType());
3719
901
3720
901
  return TheCallResult;
3721
901
}
3722
3723
void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3724
                                bool IsDelete, bool CallCanBeVirtual,
3725
                                bool WarnOnNonAbstractTypes,
3726
2.15k
                                SourceLocation DtorLoc) {
3727
2.15k
  if (!dtor || 
dtor->isVirtual()1.91k
||
!CallCanBeVirtual1.74k
||
isUnevaluatedContext()1.55k
)
3728
647
    return;
3729
1.50k
3730
  // C++ [expr.delete]p3:
3731
  //   In the first alternative (delete object), if the static type of the
3732
  //   object to be deleted is different from its dynamic type, the static
3733
  //   type shall be a base class of the dynamic type of the object to be
3734
  //   deleted and the static type shall have a virtual destructor or the
3735
  //   behavior is undefined.
3736
  //
3737
1.50k
  const CXXRecordDecl *PointeeRD = dtor->getParent();
3738
  // Note: a final class cannot be derived from, no issue there
3739
1.50k
  if (!PointeeRD->isPolymorphic() || 
PointeeRD->hasAttr<FinalAttr>()73
)
3740
1.44k
    return;
3741
64
3742
  // If the superclass is in a system header, there's nothing that can be done.
3743
  // The `delete` (where we emit the warning) can be in a system header,
3744
  // what matters for this warning is where the deleted type is defined.
3745
64
  if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3746
2
    return;
3747
62
3748
62
  QualType ClassType = dtor->getThisType()->getPointeeType();
3749
62
  if (PointeeRD->isAbstract()) {
3750
    // If the class is abstract, we warn by default, because we're
3751
    // sure the code has undefined behavior.
3752
8
    Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 
10
)
3753
8
                                                           << ClassType;
3754
54
  } else if (WarnOnNonAbstractTypes) {
3755
    // Otherwise, if this is not an array delete, it's a bit suspect,
3756
    // but not necessarily wrong.
3757
42
    Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 
18
)
3758
50
                                                  << ClassType;
3759
50
  }
3760
62
  if (!IsDelete) {
3761
8
    std::string TypeStr;
3762
8
    ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3763
8
    Diag(DtorLoc, diag::note_delete_non_virtual)
3764
8
        << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3765
8
  }
3766
62
}
3767
3768
Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3769
                                                   SourceLocation StmtLoc,
3770
1.01k
                                                   ConditionKind CK) {
3771
1.01k
  ExprResult E =
3772
1.01k
      CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3773
1.01k
  if (E.isInvalid())
3774
77
    return ConditionError();
3775
935
  return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3776
935
                         CK == ConditionKind::ConstexprIf);
3777
935
}
3778
3779
/// Check the use of the given variable as a C++ condition in an if,
3780
/// while, do-while, or switch statement.
3781
ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
3782
                                        SourceLocation StmtLoc,
3783
1.01k
                                        ConditionKind CK) {
3784
1.01k
  if (ConditionVar->isInvalidDecl())
3785
56
    return ExprError();
3786
956
3787
956
  QualType T = ConditionVar->getType();
3788
956
3789
  // C++ [stmt.select]p2:
3790
  //   The declarator shall not specify a function or an array.
3791
956
  if (T->isFunctionType())
3792
0
    return ExprError(Diag(ConditionVar->getLocation(),
3793
0
                          diag::err_invalid_use_of_function_type)
3794
0
                       << ConditionVar->getSourceRange());
3795
956
  else if (T->isArrayType())
3796
2
    return ExprError(Diag(ConditionVar->getLocation(),
3797
2
                          diag::err_invalid_use_of_array_type)
3798
2
                     << ConditionVar->getSourceRange());
3799
954
3800
954
  ExprResult Condition = BuildDeclRefExpr(
3801
954
      ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
3802
954
      ConditionVar->getLocation());
3803
954
3804
954
  switch (CK) {
3805
893
  case ConditionKind::Boolean:
3806
893
    return CheckBooleanCondition(StmtLoc, Condition.get());
3807
0
3808
0
  case ConditionKind::ConstexprIf:
3809
0
    return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3810
0
3811
61
  case ConditionKind::Switch:
3812
61
    return CheckSwitchCondition(StmtLoc, Condition.get());
3813
0
  }
3814
0
3815
0
  llvm_unreachable("unexpected condition kind");
3816
0
}
3817
3818
/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
3819
597k
ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
3820
  // C++ 6.4p4:
3821
  // The value of a condition that is an initialized declaration in a statement
3822
  // other than a switch statement is the value of the declared variable
3823
  // implicitly converted to type bool. If that conversion is ill-formed, the
3824
  // program is ill-formed.
3825
  // The value of a condition that is an expression is the value of the
3826
  // expression, implicitly converted to bool.
3827
  //
3828
  // FIXME: Return this value to the caller so they don't need to recompute it.
3829
597k
  llvm::APSInt Value(/*BitWidth*/1);
3830
597k
  return (IsConstexpr && 
!CondExpr->isValueDependent()129
)
3831
110
             ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3832
110
                                                CCEK_ConstexprIf)
3833
597k
             : PerformContextuallyConvertToBool(CondExpr);
3834
597k
}
3835
3836
/// Helper function to determine whether this is the (deprecated) C++
3837
/// conversion from a string literal to a pointer to non-const char or
3838
/// non-const wchar_t (for narrow and wide string literals,
3839
/// respectively).
3840
bool
3841
147k
Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3842
  // Look inside the implicit cast, if it exists.
3843
147k
  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3844
5
    From = Cast->getSubExpr();
3845
147k
3846
  // A string literal (2.13.4) that is not a wide string literal can
3847
  // be converted to an rvalue of type "pointer to char"; a wide
3848
  // string literal can be converted to an rvalue of type "pointer
3849
  // to wchar_t" (C++ 4.2p2).
3850
147k
  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
3851
127k
    if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
3852
123k
      if (const BuiltinType *ToPointeeType
3853
123k
          = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
3854
        // This conversion is considered only when there is an
3855
        // explicit appropriate pointer target type (C++ 4.2p2).
3856
123k
        if (!ToPtrType->getPointeeType().hasQualifiers()) {
3857
870
          switch (StrLit->getKind()) {
3858
6
            case StringLiteral::UTF8:
3859
6
            case StringLiteral::UTF16:
3860
6
            case StringLiteral::UTF32:
3861
              // We don't allow UTF literals to be implicitly converted
3862
6
              break;
3863
838
            case StringLiteral::Ascii:
3864
838
              return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3865
838
                      ToPointeeType->getKind() == BuiltinType::Char_S);
3866
26
            case StringLiteral::Wide:
3867
26
              return Context.typesAreCompatible(Context.getWideCharType(),
3868
26
                                                QualType(ToPointeeType, 0));
3869
147k
          }
3870
147k
        }
3871
123k
      }
3872
147k
3873
147k
  return false;
3874
147k
}
3875
3876
static ExprResult BuildCXXCastArgument(Sema &S,
3877
                                       SourceLocation CastLoc,
3878
                                       QualType Ty,
3879
                                       CastKind Kind,
3880
                                       CXXMethodDecl *Method,
3881
                                       DeclAccessPair FoundDecl,
3882
                                       bool HadMultipleCandidates,
3883
5.65k
                                       Expr *From) {
3884
5.65k
  switch (Kind) {
3885
0
  default: llvm_unreachable("Unhandled cast kind!");
3886
717
  case CK_ConstructorConversion: {
3887
717
    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
3888
717
    SmallVector<Expr*, 8> ConstructorArgs;
3889
717
3890
717
    if (S.RequireNonAbstractType(CastLoc, Ty,
3891
717
                                 diag::err_allocation_of_abstract_type))
3892
4
      return ExprError();
3893
713
3894
713
    if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
3895
0
      return ExprError();
3896
713
3897
713
    S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3898
713
                             InitializedEntity::InitializeTemporary(Ty));
3899
713
    if (S.DiagnoseUseOfDecl(Method, CastLoc))
3900
2
      return ExprError();
3901
711
3902
711
    ExprResult Result = S.BuildCXXConstructExpr(
3903
711
        CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
3904
711
        ConstructorArgs, HadMultipleCandidates,
3905
711
        /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3906
711
        CXXConstructExpr::CK_Complete, SourceRange());
3907
711
    if (Result.isInvalid())
3908
0
      return ExprError();
3909
711
3910
711
    return S.MaybeBindToTemporary(Result.getAs<Expr>());
3911
711
  }
3912
711
3913
4.94k
  case CK_UserDefinedConversion: {
3914
4.94k
    assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
3915
4.94k
3916
4.94k
    S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
3917
4.94k
    if (S.DiagnoseUseOfDecl(Method, CastLoc))
3918
0
      return ExprError();
3919
4.94k
3920
    // Create an implicit call expr that calls it.
3921
4.94k
    CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3922
4.94k
    ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
3923
4.94k
                                                 HadMultipleCandidates);
3924
4.94k
    if (Result.isInvalid())
3925
1
      return ExprError();
3926
    // Record usage of conversion in an implicit cast.
3927
4.93k
    Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3928
4.93k
                                      CK_UserDefinedConversion, Result.get(),
3929
4.93k
                                      nullptr, Result.get()->getValueKind(),
3930
4.93k
                                      S.CurFPFeatureOverrides());
3931
4.93k
3932
4.93k
    return S.MaybeBindToTemporary(Result.get());
3933
4.93k
  }
3934
5.65k
  }
3935
5.65k
}
3936
3937
/// PerformImplicitConversion - Perform an implicit conversion of the
3938
/// expression From to the type ToType using the pre-computed implicit
3939
/// conversion sequence ICS. Returns the converted
3940
/// expression. Action is the kind of conversion we're performing,
3941
/// used in the error message.
3942
ExprResult
3943
Sema::PerformImplicitConversion(Expr *From, QualType ToType,
3944
                                const ImplicitConversionSequence &ICS,
3945
                                AssignmentAction Action,
3946
9.95M
                                CheckedConversionKind CCK) {
3947
  // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
3948
9.95M
  if (CCK == CCK_ForBuiltinOverloadedOp && 
!From->getType()->isRecordType()83.2k
)
3949
79.1k
    return From;
3950
9.87M
3951
9.87M
  switch (ICS.getKind()) {
3952
9.86M
  case ImplicitConversionSequence::StandardConversion: {
3953
9.86M
    ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3954
9.86M
                                               Action, CCK);
3955
9.86M
    if (Res.isInvalid())
3956
112
      return ExprError();
3957
9.86M
    From = Res.get();
3958
9.86M
    break;
3959
9.86M
  }
3960
9.86M
3961
5.65k
  case ImplicitConversionSequence::UserDefinedConversion: {
3962
5.65k
3963
5.65k
      FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
3964
5.65k
      CastKind CastKind;
3965
5.65k
      QualType BeforeToType;
3966
5.65k
      assert(FD && "no conversion function for user-defined conversion seq");
3967
5.65k
      if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
3968
4.94k
        CastKind = CK_UserDefinedConversion;
3969
4.94k
3970
        // If the user-defined conversion is specified by a conversion function,
3971
        // the initial standard conversion sequence converts the source type to
3972
        // the implicit object parameter of the conversion function.
3973
4.94k
        BeforeToType = Context.getTagDeclType(Conv->getParent());
3974
717
      } else {
3975
717
        const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
3976
717
        CastKind = CK_ConstructorConversion;
3977
        // Do no conversion if dealing with ... for the first conversion.
3978
717
        if (!ICS.UserDefined.EllipsisConversion) {
3979
          // If the user-defined conversion is specified by a constructor, the
3980
          // initial standard conversion sequence converts the source type to
3981
          // the type required by the argument of the constructor
3982
714
          BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3983
714
        }
3984
717
      }
3985
      // Watch out for ellipsis conversion.
3986
5.65k
      if (!ICS.UserDefined.EllipsisConversion) {
3987
5.65k
        ExprResult Res =
3988
5.65k
          PerformImplicitConversion(From, BeforeToType,
3989
5.65k
                                    ICS.UserDefined.Before, AA_Converting,
3990
5.65k
                                    CCK);
3991
5.65k
        if (Res.isInvalid())
3992
0
          return ExprError();
3993
5.65k
        From = Res.get();
3994
5.65k
      }
3995
5.65k
3996
5.65k
      ExprResult CastArg = BuildCXXCastArgument(
3997
5.65k
          *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
3998
5.65k
          cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
3999
5.65k
          ICS.UserDefined.HadMultipleCandidates, From);
4000
5.65k
4001
5.65k
      if (CastArg.isInvalid())
4002
7
        return ExprError();
4003
5.65k
4004
5.65k
      From = CastArg.get();
4005
5.65k
4006
      // C++ [over.match.oper]p7:
4007
      //   [...] the second standard conversion sequence of a user-defined
4008
      //   conversion sequence is not applied.
4009
5.65k
      if (CCK == CCK_ForBuiltinOverloadedOp)
4010
4.14k
        return From;
4011
1.50k
4012
1.50k
      return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
4013
1.50k
                                       AA_Converting, CCK);
4014
1.50k
  }
4015
1.50k
4016
10
  case ImplicitConversionSequence::AmbiguousConversion:
4017
10
    ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
4018
10
                          PDiag(diag::err_typecheck_ambiguous_condition)
4019
10
                            << From->getSourceRange());
4020
10
    return ExprError();
4021
1.50k
4022
0
  case ImplicitConversionSequence::EllipsisConversion:
4023
0
    llvm_unreachable("Cannot perform an ellipsis conversion");
4024
1.50k
4025
444
  case ImplicitConversionSequence::BadConversion:
4026
444
    Sema::AssignConvertType ConvTy =
4027
444
        CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType());
4028
444
    bool Diagnosed = DiagnoseAssignmentResult(
4029
439
        ConvTy == Compatible ? 
Incompatible5
: ConvTy, From->getExprLoc(),
4030
444
        ToType, From->getType(), From, Action);
4031
444
    assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
4032
444
    return ExprError();
4033
9.86M
  }
4034
9.86M
4035
  // Everything went well.
4036
9.86M
  return From;
4037
9.86M
}
4038
4039
/// PerformImplicitConversion - Perform an implicit conversion of the
4040
/// expression From to the type ToType by following the standard
4041
/// conversion sequence SCS. Returns the converted
4042
/// expression. Flavor is the context in which we're performing this
4043
/// conversion, for use in error messages.
4044
ExprResult
4045
Sema::PerformImplicitConversion(Expr *From, QualType ToType,
4046
                                const StandardConversionSequence& SCS,
4047
                                AssignmentAction Action,
4048
9.87M
                                CheckedConversionKind CCK) {
4049
9.87M
  bool CStyle = (CCK == CCK_CStyleCast || 
CCK == CCK_FunctionalCast9.44M
);
4050
9.87M
4051
  // Overall FIXME: we are recomputing too many types here and doing far too
4052
  // much extra work. What this means is that we need to keep track of more
4053
  // information that is computed when we try the implicit conversion initially,
4054
  // so that we don't need to recompute anything here.
4055
9.87M
  QualType FromType = From->getType();
4056
9.87M
4057
9.87M
  if (SCS.CopyConstructor) {
4058
    // FIXME: When can ToType be a reference type?
4059
0
    assert(!ToType->isReferenceType());
4060
0
    if (SCS.Second == ICK_Derived_To_Base) {
4061
0
      SmallVector<Expr*, 8> ConstructorArgs;
4062
0
      if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
4063
0
                                  From, /*FIXME:ConstructLoc*/SourceLocation(),
4064
0
                                  ConstructorArgs))
4065
0
        return ExprError();
4066
0
      return BuildCXXConstructExpr(
4067
0
          /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4068
0
          SCS.FoundCopyConstructor, SCS.CopyConstructor,
4069
0
          ConstructorArgs, /*HadMultipleCandidates*/ false,
4070
0
          /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4071
0
          CXXConstructExpr::CK_Complete, SourceRange());
4072
0
    }
4073
0
    return BuildCXXConstructExpr(
4074
0
        /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4075
0
        SCS.FoundCopyConstructor, SCS.CopyConstructor,
4076
0
        From, /*HadMultipleCandidates*/ false,
4077
0
        /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4078
0
        CXXConstructExpr::CK_Complete, SourceRange());
4079
0
  }
4080
9.87M
4081
  // Resolve overloaded function references.
4082
9.87M
  if (Context.hasSameType(FromType, Context.OverloadTy)) {
4083
1.10k
    DeclAccessPair Found;
4084
1.10k
    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
4085
1.10k
                                                          true, Found);
4086
1.10k
    if (!Fn)
4087
0
      return ExprError();
4088
1.10k
4089
1.10k
    if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
4090
20
      return ExprError();
4091
1.08k
4092
1.08k
    From = FixOverloadedFunctionReference(From, Found, Fn);
4093
1.08k
    FromType = From->getType();
4094
1.08k
  }
4095
9.87M
4096
  // If we're converting to an atomic type, first convert to the corresponding
4097
  // non-atomic type.
4098
9.87M
  QualType ToAtomicType;
4099
9.87M
  if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
4100
497
    ToAtomicType = ToType;
4101
497
    ToType = ToAtomic->getValueType();
4102
497
  }
4103
9.87M
4104
9.87M
  QualType InitialFromType = FromType;
4105
  // Perform the first implicit conversion.
4106
9.87M
  switch (SCS.First) {
4107
8.27M
  case ICK_Identity:
4108
8.27M
    if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
4109
1
      FromType = FromAtomic->getValueType().getUnqualifiedType();
4110
1
      From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
4111
1
                                      From, /*BasePath=*/nullptr, VK_RValue,
4112
1
                                      FPOptionsOverride());
4113
1
    }
4114
8.27M
    break;
4115
0
4116
1.52M
  case ICK_Lvalue_To_Rvalue: {
4117
1.52M
    assert(From->getObjectKind() != OK_ObjCProperty);
4118
1.52M
    ExprResult FromRes = DefaultLvalueConversion(From);
4119
1.52M
    assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
4120
1.52M
    From = FromRes.get();
4121
1.52M
    FromType = From->getType();
4122
1.52M
    break;
4123
0
  }
4124
0
4125
79.2k
  case ICK_Array_To_Pointer:
4126
79.2k
    FromType = Context.getArrayDecayedType(FromType);
4127
79.2k
    From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
4128
79.2k
                             VK_RValue, /*BasePath=*/nullptr, CCK).get();
4129
79.2k
    break;
4130
0
4131
4.17k
  case ICK_Function_To_Pointer:
4132
4.17k
    FromType = Context.getPointerType(FromType);
4133
4.17k
    From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
4134
4.17k
                             VK_RValue, /*BasePath=*/nullptr, CCK).get();
4135
4.17k
    break;
4136
0
4137
0
  default:
4138
0
    llvm_unreachable("Improper first standard conversion");
4139
9.87M
  }
4140
9.87M
4141
  // Perform the second implicit conversion
4142
9.87M
  switch (SCS.Second) {
4143
8.71M
  case ICK_Identity:
4144
    // C++ [except.spec]p5:
4145
    //   [For] assignment to and initialization of pointers to functions,
4146
    //   pointers to member functions, and references to functions: the
4147
    //   target entity shall allow at least the exceptions allowed by the
4148
    //   source value in the assignment or initialization.
4149
8.71M
    switch (Action) {
4150
3.68M
    case AA_Assigning:
4151
3.68M
    case AA_Initializing:
4152
      // Note, function argument passing and returning are initialization.
4153
3.68M
    case AA_Passing:
4154
3.68M
    case AA_Returning:
4155
3.68M
    case AA_Sending:
4156
3.68M
    case AA_Passing_CFAudited:
4157
3.68M
      if (CheckExceptionSpecCompatibility(From, ToType))
4158
55
        return ExprError();
4159
3.68M
      break;
4160
3.68M
4161
5.02M
    case AA_Casting:
4162
5.02M
    case AA_Converting:
4163
      // Casts and implicit conversions are not initialization, so are not
4164
      // checked for exception specification mismatches.
4165
5.02M
      break;
4166
8.71M
    }
4167
    // Nothing else to do.
4168
8.71M
    break;
4169
8.71M
4170
712k
  case ICK_Integral_Promotion:
4171
712k
  case ICK_Integral_Conversion:
4172
712k
    if (ToType->isBooleanType()) {
4173
4
      assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4174
4
             SCS.Second == ICK_Integral_Promotion &&
4175
4
             "only enums with fixed underlying type can promote to bool");
4176
4
      From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
4177
4
                               VK_RValue, /*BasePath=*/nullptr, CCK).get();
4178
712k
    } else {
4179
712k
      From = ImpCastExprToType(From, ToType, CK_IntegralCast,
4180
712k
                               VK_RValue, /*BasePath=*/nullptr, CCK).get();
4181
712k
    }
4182
712k
    break;
4183
712k
4184
4.22k
  case ICK_Floating_Promotion:
4185
4.22k
  case ICK_Floating_Conversion:
4186
4.22k
    From = ImpCastExprToType(From, ToType, CK_FloatingCast,
4187
4.22k
                             VK_RValue, /*BasePath=*/nullptr, CCK).get();
4188
4.22k
    break;
4189
4.22k
4190
55
  case ICK_Complex_Promotion:
4191
55
  case ICK_Complex_Conversion: {
4192
55
    QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();
4193
55
    QualType ToEl = ToType->castAs<ComplexType>()->getElementType();
4194
55
    CastKind CK;
4195
55
    if (FromEl->isRealFloatingType()) {
4196
41
      if (ToEl->isRealFloatingType())
4197
33
        CK = CK_FloatingComplexCast;
4198
8
      else
4199
8
        CK = CK_FloatingComplexToIntegralComplex;
4200
14
    } else if (ToEl->isRealFloatingType()) {
4201
4
      CK = CK_IntegralComplexToFloatingComplex;
4202
10
    } else {
4203
10
      CK = CK_IntegralComplexCast;
4204
10
    }
4205
55
    From = ImpCastExprToType(From, ToType, CK,
4206
55
                             VK_RValue, /*BasePath=*/nullptr, CCK).get();
4207
55
    break;
4208
55
  }
4209
55
4210
20.6k
  case ICK_Floating_Integral:
4211
20.6k
    if (ToType->isRealFloatingType())
4212
15.2k
      From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
4213
15.2k
                               VK_RValue, /*BasePath=*/nullptr, CCK).get();
4214
5.48k
    else
4215
5.48k
      From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
4216
5.48k
                               VK_RValue, /*BasePath=*/nullptr, CCK).get();
4217
20.6k
    break;
4218
55
4219
0
  case ICK_Compatible_Conversion:
4220
0
    From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(),
4221
0
                             /*BasePath=*/nullptr, CCK).get();
4222
0
    break;
4223
55
4224
94.9k
  case ICK_Writeback_Conversion:
4225
94.9k
  case ICK_Pointer_Conversion: {
4226
94.9k
    if (SCS.IncompatibleObjC && 
Action != AA_Casting18
) {
4227
      // Diagnose incompatible Objective-C conversions
4228
13
      if (Action == AA_Initializing || 
Action == AA_Assigning9
)
4229
10
        Diag(From->getBeginLoc(),
4230
10
             diag::ext_typecheck_convert_incompatible_pointer)
4231
10
            << ToType << From->getType() << Action << From->getSourceRange()
4232
10
            << 0;
4233
3
      else
4234
3
        Diag(From->getBeginLoc(),
4235
3
             diag::ext_typecheck_convert_incompatible_pointer)
4236
3
            << From->getType() << ToType << Action << From->getSourceRange()
4237
3
            << 0;
4238
13
4239
13
      if (From->getType()->isObjCObjectPointerType() &&
4240
9
          ToType->isObjCObjectPointerType())
4241
9
        EmitRelatedResultTypeNote(From);
4242
94.9k
    } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4243
674
               !CheckObjCARCUnavailableWeakConversion(ToType,
4244
10
                                                      From->getType())) {
4245
10
      if (Action == AA_Initializing)
4246
6
        Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
4247
4
      else
4248
4
        Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4249
4
            << (Action == AA_Casting) << From->getType() << ToType
4250
4
            << From->getSourceRange();
4251
10
    }
4252
94.9k
4253
    // Defer address space conversion to the third conversion.
4254
94.9k
    QualType FromPteeType = From->getType()->getPointeeType();
4255
94.9k
    QualType ToPteeType = ToType->getPointeeType();
4256
94.9k
    QualType NewToType = ToType;
4257
94.9k
    if (!FromPteeType.isNull() && 
!ToPteeType.isNull()49.4k
&&
4258
49.4k
        FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {
4259
3
      NewToType = Context.removeAddrSpaceQualType(ToPteeType);
4260
3
      NewToType = Context.getAddrSpaceQualType(NewToType,
4261
3
                                               FromPteeType.getAddressSpace());
4262
3
      if (ToType->isObjCObjectPointerType())
4263
0
        NewToType = Context.getObjCObjectPointerType(NewToType);
4264
3
      else if (ToType->isBlockPointerType())
4265
0
        NewToType = Context.getBlockPointerType(NewToType);
4266
3
      else
4267
3
        NewToType = Context.getPointerType(NewToType);
4268
3
    }
4269
94.9k
4270
94.9k
    CastKind Kind;
4271
94.9k
    CXXCastPath BasePath;
4272
94.9k
    if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))
4273
13
      return ExprError();
4274
94.9k
4275
    // Make sure we extend blocks if necessary.
4276
    // FIXME: doing this here is really ugly.
4277
94.9k
    if (Kind == CK_BlockPointerToObjCPointerCast) {
4278
24
      ExprResult E = From;
4279
24
      (void) PrepareCastToObjCObjectPointer(E);
4280
24
      From = E.get();
4281
24
    }
4282
94.9k
    if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4283
674
      CheckObjCConversion(SourceRange(), NewToType, From, CCK);
4284
94.9k
    From = ImpCastExprToType(From, NewToType, Kind, VK_RValue, &BasePath, CCK)
4285
94.9k
             .get();
4286
94.9k
    break;
4287
94.9k
  }
4288
94.9k
4289
635
  case ICK_Pointer_Member: {
4290
635
    CastKind Kind;
4291
635
    CXXCastPath BasePath;
4292
635
    if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
4293
24
      return ExprError();
4294
611
    if (CheckExceptionSpecCompatibility(From, ToType))
4295
0
      return ExprError();
4296
611
4297
    // We may not have been able to figure out what this member pointer resolved
4298
    // to up until this exact point.  Attempt to lock-in it's inheritance model.
4299
611
    if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4300
122
      (void)isCompleteType(From->getExprLoc(), From->getType());
4301
122
      (void)isCompleteType(From->getExprLoc(), ToType);
4302
122
    }
4303
611
4304
611
    From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
4305
611
             .get();
4306
611
    break;
4307
611
  }
4308
611
4309
99.2k
  case ICK_Boolean_Conversion:
4310
    // Perform half-to-boolean conversion via float.
4311
99.2k
    if (From->getType()->isHalfType()) {
4312
0
      From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
4313
0
      FromType = Context.FloatTy;
4314
0
    }
4315
99.2k
4316
99.2k
    From = ImpCastExprToType(From, Context.BoolTy,
4317
99.2k
                             ScalarTypeToBooleanCastKind(FromType),
4318
99.2k
                             VK_RValue, /*BasePath=*/nullptr, CCK).get();
4319
99.2k
    break;
4320
611
4321
0
  case ICK_Derived_To_Base: {
4322
0
    CXXCastPath BasePath;
4323
0
    if (CheckDerivedToBaseConversion(
4324
0
            From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4325
0
            From->getSourceRange(), &BasePath, CStyle))
4326
0
      return ExprError();
4327
0
4328
0
    From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4329
0
                      CK_DerivedToBase, From->getValueKind(),
4330
0
                      &BasePath, CCK).get();
4331
0
    break;
4332
0
  }
4333
0
4334
232k
  case ICK_Vector_Conversion:
4335
232k
    From = ImpCastExprToType(From, ToType, CK_BitCast,
4336
232k
                             VK_RValue, /*BasePath=*/nullptr, CCK).get();
4337
232k
    break;
4338
0
4339
4
  case ICK_SVE_Vector_Conversion:
4340
4
    From = ImpCastExprToType(From, ToType, CK_BitCast, VK_RValue,
4341
4
                             /*BasePath=*/nullptr, CCK)
4342
4
               .get();
4343
4
    break;
4344
0
4345
46
  case ICK_Vector_Splat: {
4346
    // Vector splat from any arithmetic type to a vector.
4347
46
    Expr *Elem = prepareVectorSplat(ToType, From).get();
4348
46
    From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
4349
46
                             /*BasePath=*/nullptr, CCK).get();
4350
46
    break;
4351
0
  }
4352
0
4353
176
  case ICK_Complex_Real:
4354
    // Case 1.  x -> _Complex y
4355
176
    if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4356
160
      QualType ElType = ToComplex->getElementType();
4357
160
      bool isFloatingComplex = ElType->isRealFloatingType();
4358
160
4359
      // x -> y
4360
160
      if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4361
        // do nothing
4362
94
      } else if (From->getType()->isRealFloatingType()) {
4363
26
        From = ImpCastExprToType(From, ElType,
4364
26
                isFloatingComplex ? CK_FloatingCast : 
CK_FloatingToIntegral0
).get();
4365
68
      } else {
4366
68
        assert(From->getType()->isIntegerType());
4367
68
        From = ImpCastExprToType(From, ElType,
4368
66
                isFloatingComplex ? CK_IntegralToFloating : 
CK_IntegralCast2
).get();
4369
68
      }
4370
      // y -> _Complex y
4371
160
      From = ImpCastExprToType(From, ToType,
4372
153
                   isFloatingComplex ? CK_FloatingRealToComplex
4373
7
                                     : CK_IntegralRealToComplex).get();
4374
160
4375
    // Case 2.  _Complex x -> y
4376
16
    } else {
4377
16
      auto *FromComplex = From->getType()->castAs<ComplexType>();
4378
16
      QualType ElType = FromComplex->getElementType();
4379
16
      bool isFloatingComplex = ElType->isRealFloatingType();
4380
16
4381
      // _Complex x -> x
4382
16
      From = ImpCastExprToType(From, ElType,
4383
8
                   isFloatingComplex ? CK_FloatingComplexToReal
4384
8
                                     : CK_IntegralComplexToReal,
4385
16
                               VK_RValue, /*BasePath=*/nullptr, CCK).get();
4386
16
4387
      // x -> y
4388
16
      if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4389
        // do nothing
4390
5
      } else if (ToType->isRealFloatingType()) {
4391
5
        From = ImpCastExprToType(From, ToType,
4392
4
                   isFloatingComplex ? 
CK_FloatingCast1
: CK_IntegralToFloating,
4393
5
                                 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4394
0
      } else {
4395
0
        assert(ToType->isIntegerType());
4396
0
        From = ImpCastExprToType(From, ToType,
4397
0
                   isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
4398
0
                                 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4399
0
      }
4400
16
    }
4401
176
    break;
4402
0
4403
5
  case ICK_Block_Pointer_Conversion: {
4404
5
    LangAS AddrSpaceL =
4405
5
        ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4406
5
    LangAS AddrSpaceR =
4407
5
        FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4408
5
    assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&
4409
5
           "Invalid cast");
4410
5
    CastKind Kind =
4411
5
        AddrSpaceL != AddrSpaceR ? 
CK_AddressSpaceConversion0
: CK_BitCast;
4412
5
    From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
4413
5
                             VK_RValue, /*BasePath=*/nullptr, CCK).get();
4414
5
    break;
4415
0
  }
4416
0
4417
0
  case ICK_TransparentUnionConversion: {
4418
0
    ExprResult FromRes = From;
4419
0
    Sema::AssignConvertType ConvTy =
4420
0
      CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4421
0
    if (FromRes.isInvalid())
4422
0
      return ExprError();
4423
0
    From = FromRes.get();
4424
0
    assert ((ConvTy == Sema::Compatible) &&
4425
0
            "Improper transparent union conversion");
4426
0
    (void)ConvTy;
4427
0
    break;
4428
0
  }
4429
0
4430
0
  case ICK_Zero_Event_Conversion:
4431
0
  case ICK_Zero_Queue_Conversion:
4432
0
    From = ImpCastExprToType(From, ToType,
4433
0
                             CK_ZeroToOCLOpaqueType,
4434
0
                             From->getValueKind()).get();
4435
0
    break;
4436
0
4437
0
  case ICK_Lvalue_To_Rvalue:
4438
0
  case ICK_Array_To_Pointer:
4439
0
  case ICK_Function_To_Pointer:
4440
0
  case ICK_Function_Conversion:
4441
0
  case ICK_Qualification:
4442
0
  case ICK_Num_Conversion_Kinds:
4443
0
  case ICK_C_Only_Conversion:
4444
0
  case ICK_Incompatible_Pointer_Conversion:
4445
0
    llvm_unreachable("Improper second standard conversion");
4446
9.87M
  }
4447
9.87M
4448
9.87M
  switch (SCS.Third) {
4449
9.83M
  case ICK_Identity:
4450
    // Nothing to do.
4451
9.83M
    break;
4452
0
4453
122
  case ICK_Function_Conversion:
4454
    // If both sides are functions (or pointers/references to them), there could
4455
    // be incompatible exception declarations.
4456
122
    if (CheckExceptionSpecCompatibility(From, ToType))
4457
0
      return ExprError();
4458
122
4459
122
    From = ImpCastExprToType(From, ToType, CK_NoOp,
4460
122
                             VK_RValue, /*BasePath=*/nullptr, CCK).get();
4461
122
    break;
4462
122
4463
37.5k
  case ICK_Qualification: {
4464
37.5k
    ExprValueKind VK = From->getValueKind();
4465
37.5k
    CastKind CK = CK_NoOp;
4466
37.5k
4467
37.5k
    if (ToType->isReferenceType() &&
4468
0
        ToType->getPointeeType().getAddressSpace() !=
4469
0
            From->getType().getAddressSpace())
4470
0
      CK = CK_AddressSpaceConversion;
4471
37.5k
4472
37.5k
    if (ToType->isPointerType() &&
4473
37.4k
        ToType->getPointeeType().getAddressSpace() !=
4474
37.4k
            From->getType()->getPointeeType().getAddressSpace())
4475
46
      CK = CK_AddressSpaceConversion;
4476
37.5k
4477
37.5k
    From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4478
37.5k
                             /*BasePath=*/nullptr, CCK)
4479
37.5k
               .get();
4480
37.5k
4481
37.5k
    if (SCS.DeprecatedStringLiteralToCharPtr &&
4482
318
        !getLangOpts().WritableStrings) {
4483
317
      Diag(From->getBeginLoc(),
4484
317
           getLangOpts().CPlusPlus11
4485
154
               ? diag::ext_deprecated_string_literal_conversion
4486
163
               : diag::warn_deprecated_string_literal_conversion)
4487
317
          << ToType.getNonReferenceType();
4488
317
    }
4489
37.5k
4490
37.5k
    break;
4491
122
  }
4492
122
4493
0
  default:
4494
0
    llvm_unreachable("Improper third standard conversion");
4495
9.87M
  }
4496
9.87M
4497
  // If this conversion sequence involved a scalar -> atomic conversion, perform
4498
  // that conversion now.
4499
9.87M
  if (!ToAtomicType.isNull()) {
4500
497
    assert(Context.hasSameType(
4501
497
        ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4502
497
    From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4503
497
                             VK_RValue, nullptr, CCK).get();
4504
497
  }
4505
9.87M
4506
  // Materialize a temporary if we're implicitly converting to a reference
4507
  // type. This is not required by the C++ rules but is necessary to maintain
4508
  // AST invariants.
4509
9.87M
  if (ToType->isReferenceType() && 
From->isRValue()171
) {
4510
2
    ExprResult Res = TemporaryMaterializationConversion(From);
4511
2
    if (Res.isInvalid())
4512
0
      return ExprError();
4513
2
    From = Res.get();
4514
2
  }
4515
9.87M
4516
  // If this conversion sequence succeeded and involved implicitly converting a
4517
  // _Nullable type to a _Nonnull one, complain.
4518
9.87M
  if (!isCast(CCK))
4519
9.36M
    diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4520
9.36M
                                        From->getBeginLoc());
4521
9.87M
4522
9.87M
  return From;
4523
9.87M
}
4524
4525
/// Check the completeness of a type in a unary type trait.
4526
///
4527
/// If the particular type trait requires a complete type, tries to complete
4528
/// it. If completing the type fails, a diagnostic is emitted and false
4529
/// returned. If completing the type succeeds or no completion was required,
4530
/// returns true.
4531
static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
4532
                                                SourceLocation Loc,
4533
89.6k
                                                QualType ArgTy) {
4534
  // C++0x [meta.unary.prop]p3:
4535
  //   For all of the class templates X declared in this Clause, instantiating
4536
  //   that template with a template argument that is a class template
4537
  //   specialization may result in the implicit instantiation of the template
4538
  //   argument if and only if the semantics of X require that the argument
4539
  //   must be a complete type.
4540
  // We apply this rule to all the type trait expressions used to implement
4541
  // these class templates. We also try to follow any GCC documented behavior
4542
  // in these expressions to ensure portability of standard libraries.
4543
89.6k
  switch (UTT) {
4544
0
  default: llvm_unreachable("not a UTT");
4545
    // is_complete_type somewhat obviously cannot require a complete type.
4546
64.9k
  case UTT_IsCompleteType:
4547
    // Fall-through
4548
64.9k
4549
    // These traits are modeled on the type predicates in C++0x
4550
    // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4551
    // requiring a complete type, as whether or not they return true cannot be
4552
    // impacted by the completeness of the type.
4553
64.9k
  case UTT_IsVoid:
4554
64.9k
  case UTT_IsIntegral:
4555
64.9k
  case UTT_IsFloatingPoint:
4556
64.9k
  case UTT_IsArray:
4557
64.9k
  case UTT_IsPointer:
4558
64.9k
  case UTT_IsLvalueReference:
4559
64.9k
  case UTT_IsRvalueReference:
4560
64.9k
  case UTT_IsMemberFunctionPointer:
4561
64.9k
  case UTT_IsMemberObjectPointer:
4562
64.9k
  case UTT_IsEnum:
4563
64.9k
  case UTT_IsUnion:
4564
64.9k
  case UTT_IsClass:
4565
64.9k
  case UTT_IsFunction:
4566
64.9k
  case UTT_IsReference:
4567
64.9k
  case UTT_IsArithmetic:
4568
64.9k
  case UTT_IsFundamental:
4569
64.9k
  case UTT_IsObject:
4570
64.9k
  case UTT_IsScalar:
4571
64.9k
  case UTT_IsCompound:
4572
64.9k
  case UTT_IsMemberPointer:
4573
    // Fall-through
4574
64.9k
4575
    // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4576
    // which requires some of its traits to have the complete type. However,
4577
    // the completeness of the type cannot impact these traits' semantics, and
4578
    // so they don't require it. This matches the comments on these traits in
4579
    // Table 49.
4580
64.9k
  case UTT_IsConst:
4581
64.9k
  case UTT_IsVolatile:
4582
64.9k
  case UTT_IsSigned:
4583
64.9k
  case UTT_IsUnsigned:
4584
64.9k
4585
  // This type trait always returns false, checking the type is moot.
4586
64.9k
  case UTT_IsInterfaceClass:
4587
64.9k
    return true;
4588
64.9k
4589
  // C++14 [meta.unary.prop]:
4590
  //   If T is a non-union class type, T shall be a complete type.
4591
9.12k
  case UTT_IsEmpty:
4592
9.12k
  case UTT_IsPolymorphic:
4593
9.12k
  case UTT_IsAbstract:
4594
9.12k
    if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4595
4.35k
      if (!RD->isUnion())
4596
4.33k
        return !S.RequireCompleteType(
4597
4.33k
            Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4598
4.78k
    return true;
4599
4.78k
4600
  // C++14 [meta.unary.prop]:
4601
  //   If T is a class type, T shall be a complete type.
4602
8.23k
  case UTT_IsFinal:
4603
8.23k
  case UTT_IsSealed:
4604
8.23k
    if (ArgTy->getAsCXXRecordDecl())
4605
4.33k
      return !S.RequireCompleteType(
4606
4.33k
          Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4607
3.89k
    return true;
4608
3.89k
4609
  // C++1z [meta.unary.prop]:
4610
  //   remove_all_extents_t<T> shall be a complete type or cv void.
4611
6.30k
  case UTT_IsAggregate:
4612
6.30k
  case UTT_IsTrivial:
4613
6.30k
  case UTT_IsTriviallyCopyable:
4614
6.30k
  case UTT_IsStandardLayout:
4615
6.30k
  case UTT_IsPOD:
4616
6.30k
  case UTT_IsLiteral:
4617
  // Per the GCC type traits documentation, T shall be a complete type, cv void,
4618
  // or an array of unknown bound. But GCC actually imposes the same constraints
4619
  // as above.
4620
6.30k
  case UTT_HasNothrowAssign:
4621
6.30k
  case UTT_HasNothrowMoveAssign:
4622
6.30k
  case UTT_HasNothrowConstructor:
4623
6.30k
  case UTT_HasNothrowCopy:
4624
6.30k
  case UTT_HasTrivialAssign:
4625
6.30k
  case UTT_HasTrivialMoveAssign:
4626
6.30k
  case UTT_HasTrivialDefaultConstructor:
4627
6.30k
  case UTT_HasTrivialMoveConstructor:
4628
6.30k
  case UTT_HasTrivialCopy:
4629
6.30k
  case UTT_HasTrivialDestructor:
4630
6.30k
  case UTT_HasVirtualDestructor:
4631
6.30k
    ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4632
6.30k
    LLVM_FALLTHROUGH;
4633
6.30k
4634
  // C++1z [meta.unary.prop]:
4635
  //   T shall be a complete type, cv void, or an array of unknown bound.
4636
7.34k
  case UTT_IsDestructible:
4637
7.34k
  case UTT_IsNothrowDestructible:
4638
7.34k
  case UTT_IsTriviallyDestructible:
4639
7.34k
  case UTT_HasUniqueObjectRepresentations:
4640
7.34k
    if (ArgTy->isIncompleteArrayType() || 
ArgTy->isVoidType()7.31k
)
4641
165
      return true;
4642
7.18k
4643
7.18k
    return !S.RequireCompleteType(
4644
7.18k
        Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4645
89.6k
  }
4646
89.6k
}
4647
4648
static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4649
                               Sema &Self, SourceLocation KeyLoc, ASTContext &C,
4650
                               bool (CXXRecordDecl::*HasTrivial)() const,
4651
                               bool (CXXRecordDecl::*HasNonTrivial)() const,
4652
                               bool (CXXMethodDecl::*IsDesiredOp)() const)
4653
81
{
4654
81
  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4655
81
  if ((RD->*HasTrivial)() && 
!(RD->*HasNonTrivial)()18
)
4656
18
    return true;
4657
63
4658
63
  DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4659
63
  DeclarationNameInfo NameInfo(Name, KeyLoc);
4660
63
  LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4661
63
  if (Self.LookupQualifiedName(Res, RD)) {
4662
63
    bool FoundOperator = false;
4663
63
    Res.suppressDiagnostics();
4664
63
    for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4665
135
         Op != OpEnd; 
++Op72
) {
4666
93
      if (isa<FunctionTemplateDecl>(*Op))
4667
3
        continue;
4668
90
4669
90
      CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4670
90
      if((Operator->*IsDesiredOp)()) {
4671
54
        FoundOperator = true;
4672
54
        auto *CPT = Operator->getType()->castAs<FunctionProtoType>();
4673
54
        CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4674
54
        if (!CPT || !CPT->isNothrow())
4675
21
          return false;
4676
54
      }
4677
90
    }
4678
42
    return FoundOperator;
4679
0
  }
4680
0
  return false;
4681
0
}
4682
4683
static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
4684
74.8k
                                   SourceLocation KeyLoc, QualType T) {
4685
74.8k
  assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
4686
74.8k
4687
74.8k
  ASTContext &C = Self.Context;
4688
74.8k
  switch(UTT) {
4689
0
  default: llvm_unreachable("not a UTT");
4690
    // Type trait expressions corresponding to the primary type category
4691
    // predicates in C++0x [meta.unary.cat].
4692
2.98k
  case UTT_IsVoid:
4693
2.98k
    return T->isVoidType();
4694
2.36k
  case UTT_IsIntegral:
4695
2.36k
    return T->isIntegralType(C);
4696
72
  case UTT_IsFloatingPoint:
4697
72
    return T->isFloatingType();
4698
18.9k
  case UTT_IsArray:
4699
18.9k
    return T->isArrayType();
4700
1.58k
  case UTT_IsPointer:
4701
1.58k
    return T->isAnyPointerType();
4702
1.18k
  case UTT_IsLvalueReference:
4703
1.18k
    return T->isLValueReferenceType();
4704
1.60k
  case UTT_IsRvalueReference:
4705
1.60k
    return T->isRValueReferenceType();
4706
287
  case UTT_IsMemberFunctionPointer:
4707
287
    return T->isMemberFunctionPointerType();
4708
219
  case UTT_IsMemberObjectPointer:
4709
219
    return T->isMemberDataPointerType();
4710
1.19k
  case UTT_IsEnum:
4711
1.19k
    return T->isEnumeralType();
4712
32
  case UTT_IsUnion:
4713
32
    return T->isUnionType();
4714
42
  case UTT_IsClass:
4715
42
    return T->isClassType() || 
T->isStructureType()39
||
T->isInterfaceType()30
;
4716
18.8k
  case UTT_IsFunction:
4717
18.8k
    return T->isFunctionType();
4718
0
4719
    // Type trait expressions which correspond to the convenient composition
4720
    // predicates in C++0x [meta.unary.comp].
4721
1.78k
  case UTT_IsReference:
4722
1.78k
    return T->isReferenceType();
4723
72
  case UTT_IsArithmetic:
4724
72
    return T->isArithmeticType() && 
!T->isEnumeralType()47
;
4725
75
  case UTT_IsFundamental:
4726
75
    return T->isFundamentalType();
4727
49
  case UTT_IsObject:
4728
49
    return T->isObjectType();
4729
87
  case UTT_IsScalar:
4730
    // Note: semantic analysis depends on Objective-C lifetime types to be
4731
    // considered scalar types. However, such types do not actually behave
4732
    // like scalar types at run time (since they may require retain/release
4733
    // operations), so we report them as non-scalar.
4734
87
    if (T->isObjCLifetimeType()) {
4735
8
      switch (T.getObjCLifetime()) {
4736
4
      case Qualifiers::OCL_None:
4737
4
      case Qualifiers::OCL_ExplicitNone:
4738
4
        return true;
4739
4
4740
4
      case Qualifiers::OCL_Strong:
4741
4
      case Qualifiers::OCL_Weak:
4742
4
      case Qualifiers::OCL_Autoreleasing:
4743
4
        return false;
4744
79
      }
4745
79
    }
4746
79
4747
79
    return T->isScalarType();
4748
90
  case UTT_IsCompound:
4749
90
    return T->isCompoundType();
4750
93
  case UTT_IsMemberPointer:
4751
93
    return T->isMemberPointerType();
4752
79
4753
    // Type trait expressions which correspond to the type property predicates
4754
    // in C++0x [meta.unary.prop].
4755
776
  case UTT_IsConst:
4756
776
    return T.isConstQualified();
4757
689
  case UTT_IsVolatile:
4758
689
    return T.isVolatileQualified();
4759
904
  case UTT_IsTrivial:
4760
904
    return T.isTrivialType(C);
4761
285
  case UTT_IsTriviallyCopyable:
4762
285
    return T.isTriviallyCopyableType(C);
4763
879
  case UTT_IsStandardLayout:
4764
879
    return T->isStandardLayoutType();
4765
202
  case UTT_IsPOD:
4766
202
    return T.isPODType(C);
4767
85
  case UTT_IsLiteral:
4768
85
    return T->isLiteralType(C);
4769
7.74k
  case UTT_IsEmpty:
4770
7.74k
    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4771
4.32k
      return !RD->isUnion() && 
RD->isEmpty()4.31k
;
4772
3.42k
    return false;
4773
46
  case UTT_IsPolymorphic:
4774
46
    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4775
19
      return !RD->isUnion() && 
RD->isPolymorphic()13
;
4776
27
    return false;
4777
14
  case UTT_IsAbstract:
4778
14
    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4779
8
      return !RD->isUnion() && 
RD->isAbstract()7
;
4780
6
    return false;
4781
153
  case UTT_IsAggregate:
4782
    // Report vector extensions and complex types as aggregates because they
4783
    // support aggregate initialization. GCC mirrors this behavior for vectors
4784
    // but not _Complex.
4785
153
    return T->isAggregateType() || 
T->isVectorType()71
||
T->isExtVectorType()65
||
4786
65
           T->isAnyComplexType();
4787
  // __is_interface_class only returns true when CL is invoked in /CLR mode and
4788
  // even then only when it is used with the 'interface struct ...' syntax
4789
  // Clang doesn't support /CLR which makes this type trait moot.
4790
10
  case UTT_IsInterfaceClass:
4791
10
    return false;
4792
7.77k
  case UTT_IsFinal:
4793
7.77k
  case UTT_IsSealed:
4794
7.77k
    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4795
4.33k
      return RD->hasAttr<FinalAttr>();
4796
3.44k
    return false;
4797
1.88k
  case UTT_IsSigned:
4798
    // Enum types should always return false.
4799
    // Floating points should always return true.
4800
1.88k
    return !T->isEnumeralType() && 
(1.88k
T->isFloatingType()1.88k
||
T->isSignedIntegerType()1.87k
);
4801
75
  case UTT_IsUnsigned:
4802
75
    return T->isUnsignedIntegerType();
4803
3.44k
4804
    // Type trait expressions which query classes regarding their construction,
4805
    // destruction, and copying. Rather than being based directly on the
4806
    // related type predicates in the standard, they are specified by both
4807
    // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4808
    // specifications.
4809
    //
4810
    //   1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4811
    //   2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4812
    //
4813
    // Note that these builtins do not behave as documented in g++: if a class
4814
    // has both a trivial and a non-trivial special member of a particular kind,
4815
    // they return false! For now, we emulate this behavior.
4816
    // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4817
    // does not correctly compute triviality in the presence of multiple special
4818
    // members of the same kind. Revisit this once the g++ bug is fixed.
4819
159
  case UTT_HasTrivialDefaultConstructor:
4820
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4821
    //   If __is_pod (type) is true then the trait is true, else if type is
4822
    //   a cv class or union type (or array thereof) with a trivial default
4823
    //   constructor ([class.ctor]) then the trait is true, else it is false.
4824
159
    if (T.isPODType(C))
4825
64
      return true;
4826
95
    if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4827
82
      return RD->hasTrivialDefaultConstructor() &&
4828
21
             !RD->hasNonTrivialDefaultConstructor();
4829
13
    return false;
4830
37
  case UTT_HasTrivialMoveConstructor:
4831
    //  This trait is implemented by MSVC 2012 and needed to parse the
4832
    //  standard library headers. Specifically this is used as the logic
4833
    //  behind std::is_trivially_move_constructible (20.9.4.3).
4834
37
    if (T.isPODType(C))
4835
19
      return true;
4836
18
    if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4837
18
      return RD->hasTrivialMoveConstructor() && 
!RD->hasNonTrivialMoveConstructor()3
;
4838
0
    return false;
4839
119
  case UTT_HasTrivialCopy:
4840
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4841
    //   If __is_pod (type) is true or type is a reference type then
4842
    //   the trait is true, else if type is a cv class or union type
4843
    //   with a trivial copy constructor ([class.copy]) then the trait
4844
    //   is true, else it is false.
4845
119
    if (T.isPODType(C) || 
T->isReferenceType()65
)
4846
57
      return true;
4847
62
    if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4848
49
      return RD->hasTrivialCopyConstructor() &&
4849
28
             !RD->hasNonTrivialCopyConstructor();
4850
13
    return false;
4851
31
  case UTT_HasTrivialMoveAssign:
4852
    //  This trait is implemented by MSVC 2012 and needed to parse the
4853
    //  standard library headers. Specifically it is used as the logic
4854
    //  behind std::is_trivially_move_assignable (20.9.4.3)
4855
31
    if (T.isPODType(C))
4856
16
      return true;
4857
15
    if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4858
15
      return RD->hasTrivialMoveAssignment() && 
!RD->hasNonTrivialMoveAssignment()0
;
4859
0
    return false;
4860
115
  case UTT_HasTrivialAssign:
4861
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4862
    //   If type is const qualified or is a reference type then the
4863
    //   trait is false. Otherwise if __is_pod (type) is true then the
4864
    //   trait is true, else if type is a cv class or union type with
4865
    //   a trivial copy assignment ([class.copy]) then the trait is
4866
    //   true, else it is false.
4867
    // Note: the const and reference restrictions are interesting,
4868
    // given that const and reference members don't prevent a class
4869
    // from having a trivial copy assignment operator (but do cause
4870
    // errors if the copy assignment operator is actually used, q.v.
4871
    // [class.copy]p12).
4872
115
4873
115
    if (T.isConstQualified())
4874
12
      return false;
4875
103
    if (T.isPODType(C))
4876
50
      return true;
4877
53
    if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4878
40
      return RD->hasTrivialCopyAssignment() &&
4879
22
             !RD->hasNonTrivialCopyAssignment();
4880
13
    return false;
4881
221
  case UTT_IsDestructible:
4882
221
  case UTT_IsTriviallyDestructible:
4883
221
  case UTT_IsNothrowDestructible:
4884
    // C++14 [meta.unary.prop]:
4885
    //   For reference types, is_destructible<T>::value is true.
4886
221
    if (T->isReferenceType())
4887
9
      return true;
4888
212
4889
    // Objective-C++ ARC: autorelease types don't require destruction.
4890
212
    if (T->isObjCLifetimeType() &&
4891
0
        T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4892
0
      return true;
4893
212
4894
    // C++14 [meta.unary.prop]:
4895
    //   For incomplete types and function types, is_destructible<T>::value is
4896
    //   false.
4897
212
    if (T->isIncompleteType() || 
T->isFunctionType()167
)
4898
45
      return false;
4899
167
4900
    // A type that requires destruction (via a non-trivial destructor or ARC
4901
    // lifetime semantics) is not trivially-destructible.
4902
167
    if (UTT == UTT_IsTriviallyDestructible && 
T.isDestructedType()100
)
4903
21
      return false;
4904
146
4905
    // C++14 [meta.unary.prop]:
4906
    //   For object types and given U equal to remove_all_extents_t<T>, if the
4907
    //   expression std::declval<U&>().~U() is well-formed when treated as an
4908
    //   unevaluated operand (Clause 5), then is_destructible<T>::value is true
4909
146
    if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4910
67
      CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4911
67
      if (!Destructor)
4912
0
        return false;
4913
      //  C++14 [dcl.fct.def.delete]p2:
4914
      //    A program that refers to a deleted function implicitly or
4915
      //    explicitly, other than to declare it, is ill-formed.
4916
67
      if (Destructor->isDeleted())
4917
13
        return false;
4918
54
      if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4919
6
        return false;
4920
48
      if (UTT == UTT_IsNothrowDestructible) {
4921
21
        auto *CPT = Destructor->getType()->castAs<FunctionProtoType>();
4922
21
        CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4923
21
        if (!CPT || !CPT->isNothrow())
4924
3
          return false;
4925
124
      }
4926
48
    }
4927
124
    return true;
4928
124
4929
117
  case UTT_HasTrivialDestructor:
4930
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4931
    //   If __is_pod (type) is true or type is a reference type
4932
    //   then the trait is true, else if type is a cv class or union
4933
    //   type (or array thereof) with a trivial destructor
4934
    //   ([class.dtor]) then the trait is true, else it is
4935
    //   false.
4936
117
    if (T.isPODType(C) || 
T->isReferenceType()61
)
4937
59
      return true;
4938
58
4939
    // Objective-C++ ARC: autorelease types don't require destruction.
4940
58
    if (T->isObjCLifetimeType() &&
4941
4
        T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4942
1
      return true;
4943
57
4944
57
    if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4945
48
      return RD->hasTrivialDestructor();
4946
9
    return false;
4947
  // TODO: Propagate nothrowness for implicitly declared special members.
4948
108
  case UTT_HasNothrowAssign:
4949
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4950
    //   If type is const qualified or is a reference type then the
4951
    //   trait is false. Otherwise if __has_trivial_assign (type)
4952
    //   is true then the trait is true, else if type is a cv class
4953
    //   or union type with copy assignment operators that are known
4954
    //   not to throw an exception then the trait is true, else it is
4955
    //   false.
4956
108
    if (C.getBaseElementType(T).isConstQualified())
4957
12
      return false;
4958
96
    if (T->isReferenceType())
4959
3
      return false;
4960
93
    if (T.isPODType(C) || 
T->isObjCLifetimeType()52
)
4961
45
      return true;
4962
48
4963
48
    if (const RecordType *RT = T->getAs<RecordType>())
4964
42
      return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4965
42
                                &CXXRecordDecl::hasTrivialCopyAssignment,
4966
42
                                &CXXRecordDecl::hasNonTrivialCopyAssignment,
4967
42
                                &CXXMethodDecl::isCopyAssignmentOperator);
4968
6
    return false;
4969
67
  case UTT_HasNothrowMoveAssign:
4970
    //  This trait is implemented by MSVC 2012 and needed to parse the
4971
    //  standard library headers. Specifically this is used as the logic
4972
    //  behind std::is_nothrow_move_assignable (20.9.4.3).
4973
67
    if (T.isPODType(C))
4974
28
      return true;
4975
39
4976
39
    if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4977
39
      return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4978
39
                                &CXXRecordDecl::hasTrivialMoveAssignment,
4979
39
                                &CXXRecordDecl::hasNonTrivialMoveAssignment,
4980
39
                                &CXXMethodDecl::isMoveAssignmentOperator);
4981
0
    return false;
4982
107
  case UTT_HasNothrowCopy:
4983
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4984
    //   If __has_trivial_copy (type) is true then the trait is true, else
4985
    //   if type is a cv class or union type with copy constructors that are
4986
    //   known not to throw an exception then the trait is true, else it is
4987
    //   false.
4988
107
    if (T.isPODType(C) || 
T->isReferenceType()60
||
T->isObjCLifetimeType()57
)
4989
54
      return true;
4990
53
    if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4991
44
      if (RD->hasTrivialCopyConstructor() &&
4992
19
          !RD->hasNonTrivialCopyConstructor())
4993
19
        return true;
4994
25
4995
25
      bool FoundConstructor = false;
4996
25
      unsigned FoundTQs;
4997
50
      for (const auto *ND : Self.LookupConstructors(RD)) {
4998
        // A template constructor is never a copy constructor.
4999
        // FIXME: However, it may actually be selected at the actual overload
5000
        // resolution point.
5001
50
        if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5002
3
          continue;
5003
        // UsingDecl itself is not a constructor
5004
47
        if (isa<UsingDecl>(ND))
5005
1
          continue;
5006
46
        auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5007
46
        if (Constructor->isCopyConstructor(FoundTQs)) {
5008
31
          FoundConstructor = true;
5009
31
          auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5010
31
          CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5011
31
          if (!CPT)
5012
0
            return false;
5013
          // TODO: check whether evaluating default arguments can throw.
5014
          // For now, we'll be conservative and assume that they can throw.
5015
31
          if (!CPT->isNothrow() || 
CPT->getNumParams() > 124
)
5016
7
            return false;
5017
31
        }
5018
46
      }
5019
25
5020
18
      return FoundConstructor;
5021
9
    }
5022
9
    return false;
5023
104
  case UTT_HasNothrowConstructor:
5024
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5025
    //   If __has_trivial_constructor (type) is true then the trait is
5026
    //   true, else if type is a cv class or union type (or array
5027
    //   thereof) with a default constructor that is known not to
5028
    //   throw an exception then the trait is true, else it is false.
5029
104
    if (T.isPODType(C) || 
T->isObjCLifetimeType()57
)
5030
51
      return true;
5031
53
    if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5032
44
      if (RD->hasTrivialDefaultConstructor() &&
5033
6
          !RD->hasNonTrivialDefaultConstructor())
5034
6
        return true;
5035
38
5036
38
      bool FoundConstructor = false;
5037
84
      for (const auto *ND : Self.LookupConstructors(RD)) {
5038
        // FIXME: In C++0x, a constructor template can be a default constructor.
5039
84
        if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5040
4
          continue;
5041
        // UsingDecl itself is not a constructor
5042
80
        if (isa<UsingDecl>(ND))
5043
2
          continue;
5044
78
        auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5045
78
        if (Constructor->isDefaultConstructor()) {
5046
29
          FoundConstructor = true;
5047
29
          auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5048
29
          CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5049
29
          if (!CPT)
5050
0
            return false;
5051
          // FIXME: check whether evaluating default arguments can throw.
5052
          // For now, we'll be conservative and assume that they can throw.
5053
29
          if (!CPT->isNothrow() || 
CPT->getNumParams() > 020
)
5054
12
            return false;
5055
29
        }
5056
78
      }
5057
26
      return FoundConstructor;
5058
9
    }
5059
9
    return false;
5060
85
  case UTT_HasVirtualDestructor:
5061
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5062
    //   If type is a class type with a virtual destructor ([class.dtor])
5063
    //   then the trait is true, else it is false.
5064
85
    if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5065
42
      if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
5066
42
        return Destructor->isVirtual();
5067
43
    return false;
5068
43
5069
    // These type trait expressions are modeled on the specifications for the
5070
    // Embarcadero C++0x type trait functions:
5071
    //   http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5072
50
  case UTT_IsCompleteType:
5073
    // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
5074
    //   Returns True if and only if T is a complete type at the point of the
5075
    //   function call.
5076
50
    return !T->isIncompleteType();
5077
360
  case UTT_HasUniqueObjectRepresentations:
5078
360
    return C.hasUniqueObjectRepresentations(T);
5079
74.8k
  }
5080
74.8k
}
5081
5082
static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5083
                                    QualType RhsT, SourceLocation KeyLoc);
5084
5085
static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
5086
                              ArrayRef<TypeSourceInfo *> Args,
5087
179k
                              SourceLocation RParenLoc) {
5088
179k
  if (Kind <= UTT_Last)
5089
74.8k
    return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
5090
104k
5091
  // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
5092
  // traits to avoid duplication.
5093
104k
  if (Kind <= BTT_Last && 
Kind != BTT_ReferenceBindsToTemporary93.6k
)
5094
92.8k
    return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
5095
92.8k
                                   Args[1]->getType(), RParenLoc);
5096
12.0k
5097
12.0k
  switch (Kind) {
5098
12.0k
  c