Coverage Report

Created: 2020-02-25 14:32

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