blob: 9e5c7354a5ebe7b7552f00c72bc43c22b8db7599 [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Chris Lattner29375652006-12-04 18:06:35 +00006//
7//===----------------------------------------------------------------------===//
James Dennett84053fb2012-06-22 05:14:59 +00008///
9/// \file
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010/// Implements semantic analysis for C++ expressions.
James Dennett84053fb2012-06-22 05:14:59 +000011///
12//===----------------------------------------------------------------------===//
Chris Lattner29375652006-12-04 18:06:35 +000013
Saar Raza0f50d72020-01-18 09:11:43 +020014#include "clang/Sema/Template.h"
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Kaelyn Takata6c759512014-10-27 18:07:37 +000016#include "TreeTransform.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "TypeLocBuilder.h"
Steve Naroffaac94152007-08-25 14:02:58 +000018#include "clang/AST/ASTContext.h"
Faisal Vali47d9ed42014-05-30 04:39:37 +000019#include "clang/AST/ASTLambda.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/AST/CharUnits.h"
John McCallde6836a2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000023#include "clang/AST/ExprCXX.h"
Fariborz Jahanian1d446082010-06-16 18:56:04 +000024#include "clang/AST/ExprObjC.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000025#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000026#include "clang/AST/TypeLoc.h"
Akira Hatanaka3e40c302017-07-19 17:17:50 +000027#include "clang/Basic/AlignedAllocation.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000029#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000030#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#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"
Faisal Valia17d19f2013-11-07 05:17:06 +000037#include "clang/Sema/SemaLambda.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "clang/Sema/TemplateDeduction.h"
Sebastian Redlb8fc4772012-02-16 12:59:47 +000039#include "llvm/ADT/APInt.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000040#include "llvm/ADT/STLExtras.h"
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +000041#include "llvm/Support/ErrorHandling.h"
Chris Lattner29375652006-12-04 18:06:35 +000042using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000043using namespace sema;
Chris Lattner29375652006-12-04 18:06:35 +000044
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000045/// Handle the result of the special case name lookup for inheriting
Richard Smith7447af42013-03-26 01:15:19 +000046/// 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.
49ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
50 SourceLocation NameLoc,
51 IdentifierInfo &Name) {
52 NestedNameSpecifier *NNS = SS.getScopeRep();
53
54 // Convert the nested-name-specifier into a type.
55 QualType Type;
56 switch (NNS->getKind()) {
57 case NestedNameSpecifier::TypeSpec:
58 case NestedNameSpecifier::TypeSpecWithTemplate:
59 Type = QualType(NNS->getAsType(), 0);
60 break;
61
62 case NestedNameSpecifier::Identifier:
63 // Strip off the last layer of the nested-name-specifier and build a
64 // typename type for it.
65 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
66 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
67 NNS->getAsIdentifier());
68 break;
69
70 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +000071 case NestedNameSpecifier::Super:
Richard Smith7447af42013-03-26 01:15:19 +000072 case NestedNameSpecifier::Namespace:
73 case NestedNameSpecifier::NamespaceAlias:
74 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
75 }
76
77 // This reference to the type is located entirely at the location of the
78 // final identifier in the qualified-id.
79 return CreateParsedType(Type,
80 Context.getTrivialTypeSourceInfo(Type, NameLoc));
81}
82
Richard Smith715ee072018-06-20 21:58:20 +000083ParsedType Sema::getConstructorName(IdentifierInfo &II,
84 SourceLocation NameLoc,
Richard Smith69bc9aa2018-06-22 19:50:19 +000085 Scope *S, CXXScopeSpec &SS,
86 bool EnteringContext) {
Richard Smith715ee072018-06-20 21:58:20 +000087 CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
88 assert(CurClass && &II == CurClass->getIdentifier() &&
89 "not a constructor name");
90
Richard Smith69bc9aa2018-06-22 19:50:19 +000091 // When naming a constructor as a member of a dependent context (eg, in a
92 // friend declaration or an inherited constructor declaration), form an
93 // unresolved "typename" type.
Gauthier Harnischef629c72019-06-14 08:25:52 +000094 if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) {
Richard Smith69bc9aa2018-06-22 19:50:19 +000095 QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II);
96 return ParsedType::make(T);
97 }
98
Richard Smith715ee072018-06-20 21:58:20 +000099 if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
100 return ParsedType();
101
102 // Find the injected-class-name declaration. Note that we make no attempt to
103 // diagnose cases where the injected-class-name is shadowed: the only
104 // declaration that can validly shadow the injected-class-name is a
105 // non-static data member, and if the class contains both a non-static data
106 // member and a constructor then it is ill-formed (we check that in
107 // CheckCompletedCXXClass).
108 CXXRecordDecl *InjectedClassName = nullptr;
109 for (NamedDecl *ND : CurClass->lookup(&II)) {
110 auto *RD = dyn_cast<CXXRecordDecl>(ND);
111 if (RD && RD->isInjectedClassName()) {
112 InjectedClassName = RD;
113 break;
114 }
115 }
Richard Smith2e34bbd2018-08-08 00:42:42 +0000116 if (!InjectedClassName) {
117 if (!CurClass->isInvalidDecl()) {
118 // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
119 // properly. Work around it here for now.
120 Diag(SS.getLastQualifierNameLoc(),
121 diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
122 }
Ilya Biryukova2d58252018-07-04 08:50:12 +0000123 return ParsedType();
Richard Smith2e34bbd2018-08-08 00:42:42 +0000124 }
Richard Smith715ee072018-06-20 21:58:20 +0000125
126 QualType T = Context.getTypeDeclType(InjectedClassName);
127 DiagnoseUseOfDecl(InjectedClassName, NameLoc);
128 MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
129
130 return ParsedType::make(T);
131}
132
John McCallba7bf592010-08-24 05:47:05 +0000133ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000134 IdentifierInfo &II,
John McCallba7bf592010-08-24 05:47:05 +0000135 SourceLocation NameLoc,
136 Scope *S, CXXScopeSpec &SS,
137 ParsedType ObjectTypePtr,
138 bool EnteringContext) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000139 // Determine where to perform name lookup.
140
141 // FIXME: This area of the standard is very messy, and the current
142 // wording is rather unclear about which scopes we search for the
143 // destructor name; see core issues 399 and 555. Issue 399 in
144 // particular shows where the current description of destructor name
145 // lookup is completely out of line with existing practice, e.g.,
146 // this appears to be ill-formed:
147 //
148 // namespace N {
149 // template <typename T> struct S {
150 // ~S();
151 // };
152 // }
153 //
154 // void f(N::S<int>* s) {
155 // s->N::S<int>::~S();
156 // }
157 //
Douglas Gregor46841e12010-02-23 00:15:22 +0000158 // See also PR6358 and PR6359.
Richard Smith0e3a4872020-02-07 16:34:08 -0800159 //
160 // For now, we accept all the cases in which the name given could plausibly
161 // be interpreted as a correct destructor name, issuing off-by-default
162 // extension diagnostics on the cases that don't strictly conform to the
163 // C++20 rules. This basically means we always consider looking in the
164 // nested-name-specifier prefix, the complete nested-name-specifier, and
165 // the scope, and accept if we find the expected type in any of the three
166 // places.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000167
Richard Smith64e033f2015-01-15 00:48:52 +0000168 if (SS.isInvalid())
David Blaikieefdccaa2016-01-15 23:43:34 +0000169 return nullptr;
Richard Smith64e033f2015-01-15 00:48:52 +0000170
Richard Smith0e3a4872020-02-07 16:34:08 -0800171 // Whether we've failed with a diagnostic already.
172 bool Failed = false;
173
174 llvm::SmallVector<NamedDecl*, 8> FoundDecls;
175 llvm::SmallSet<CanonicalDeclPtr<Decl>, 8> FoundDeclSet;
176
Douglas Gregorfe17d252010-02-16 19:09:40 +0000177 // If we have an object type, it's because we are in a
178 // pseudo-destructor-expression or a member access expression, and
179 // we know what type we're looking for.
Richard Smith0e3a4872020-02-07 16:34:08 -0800180 QualType SearchType =
181 ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000182
Richard Smith0e3a4872020-02-07 16:34:08 -0800183 auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000184 // FIXME: Should we be suppressing ambiguities here?
Richard Smith0e3a4872020-02-07 16:34:08 -0800185 if (Found.isAmbiguous()) {
186 Failed = true;
David Blaikieefdccaa2016-01-15 23:43:34 +0000187 return nullptr;
Richard Smith0e3a4872020-02-07 16:34:08 -0800188 }
189
190 for (NamedDecl *D : Found) {
191 // Don't list a class twice in the lookup failure diagnostic if it's
192 // found by both its injected-class-name and by the name in the enclosing
193 // scope.
194 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
195 if (RD->isInjectedClassName())
196 D = cast<NamedDecl>(RD->getParent());
197
198 if (FoundDeclSet.insert(D).second)
199 FoundDecls.push_back(D);
200 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000201
202 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
203 QualType T = Context.getTypeDeclType(Type);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000204 if (SearchType.isNull() || SearchType->isDependentType() ||
205 Context.hasSameUnqualifiedType(T, SearchType)) {
Richard Smith76f888d2020-02-10 02:17:43 -0800206 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Richard Smithc278c002014-01-22 00:30:17 +0000207 return CreateParsedType(T,
208 Context.getTrivialTypeSourceInfo(T, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000209 }
210 }
211
Richard Smith0e3a4872020-02-07 16:34:08 -0800212 return nullptr;
213 };
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000214
Richard Smith0e3a4872020-02-07 16:34:08 -0800215 bool IsDependent = false;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000216
Richard Smith0e3a4872020-02-07 16:34:08 -0800217 auto LookupInObjectType = [&]() -> ParsedType {
218 if (Failed || SearchType.isNull())
219 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000220
Richard Smith0e3a4872020-02-07 16:34:08 -0800221 IsDependent |= SearchType->isDependentType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000222
Richard Smith76f888d2020-02-10 02:17:43 -0800223 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
Richard Smith0e3a4872020-02-07 16:34:08 -0800224 DeclContext *LookupCtx = computeDeclContext(SearchType);
225 if (!LookupCtx)
226 return nullptr;
227 LookupQualifiedName(Found, LookupCtx);
228 return CheckLookupResult(Found);
229 };
Douglas Gregorfe17d252010-02-16 19:09:40 +0000230
Richard Smith0e3a4872020-02-07 16:34:08 -0800231 auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType {
232 if (Failed)
233 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000234
Richard Smith0e3a4872020-02-07 16:34:08 -0800235 IsDependent |= isDependentScopeSpecifier(LookupSS);
236 DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext);
237 if (!LookupCtx)
238 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000239
Richard Smith76f888d2020-02-10 02:17:43 -0800240 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
Richard Smith0e3a4872020-02-07 16:34:08 -0800241 if (RequireCompleteDeclContext(LookupSS, LookupCtx)) {
242 Failed = true;
243 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000244 }
Richard Smith0e3a4872020-02-07 16:34:08 -0800245 LookupQualifiedName(Found, LookupCtx);
246 return CheckLookupResult(Found);
247 };
248
249 auto LookupInScope = [&]() -> ParsedType {
250 if (Failed || !S)
251 return nullptr;
252
Richard Smith76f888d2020-02-10 02:17:43 -0800253 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
Richard Smith0e3a4872020-02-07 16:34:08 -0800254 LookupName(Found, S);
255 return CheckLookupResult(Found);
256 };
257
258 // C++2a [basic.lookup.qual]p6:
259 // In a qualified-id of the form
260 //
261 // nested-name-specifier[opt] type-name :: ~ type-name
262 //
263 // the second type-name is looked up in the same scope as the first.
264 //
265 // We interpret this as meaning that if you do a dual-scope lookup for the
266 // first name, you also do a dual-scope lookup for the second name, per
267 // C++ [basic.lookup.classref]p4:
268 //
269 // If the id-expression in a class member access is a qualified-id of the
270 // form
271 //
272 // class-name-or-namespace-name :: ...
273 //
274 // the class-name-or-namespace-name following the . or -> is first looked
275 // up in the class of the object expression and the name, if found, is used.
276 // Otherwise, it is looked up in the context of the entire
277 // postfix-expression.
278 //
279 // This looks in the same scopes as for an unqualified destructor name:
280 //
281 // C++ [basic.lookup.classref]p3:
282 // If the unqualified-id is ~ type-name, the type-name is looked up
283 // in the context of the entire postfix-expression. If the type T
284 // of the object expression is of a class type C, the type-name is
285 // also looked up in the scope of class C. At least one of the
286 // lookups shall find a name that refers to cv T.
287 //
288 // FIXME: The intent is unclear here. Should type-name::~type-name look in
289 // the scope anyway if it finds a non-matching name declared in the class?
290 // If both lookups succeed and find a dependent result, which result should
291 // we retain? (Same question for p->~type-name().)
292
293 if (NestedNameSpecifier *Prefix =
294 SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) {
295 // This is
296 //
297 // nested-name-specifier type-name :: ~ type-name
298 //
299 // Look for the second type-name in the nested-name-specifier.
300 CXXScopeSpec PrefixSS;
301 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
302 if (ParsedType T = LookupInNestedNameSpec(PrefixSS))
303 return T;
304 } else {
305 // This is one of
306 //
307 // type-name :: ~ type-name
308 // ~ type-name
309 //
310 // Look in the scope and (if any) the object type.
311 if (ParsedType T = LookupInScope())
312 return T;
313 if (ParsedType T = LookupInObjectType())
314 return T;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000315 }
316
Richard Smith0e3a4872020-02-07 16:34:08 -0800317 if (Failed)
318 return nullptr;
319
320 if (IsDependent) {
321 // We didn't find our type, but that's OK: it's dependent anyway.
Simon Pilgrim75c26882016-09-30 14:25:09 +0000322
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000323 // FIXME: What if we have no nested-name-specifier?
324 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
325 SS.getWithLocInContext(Context),
326 II, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +0000327 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000328 }
329
Richard Smith0e3a4872020-02-07 16:34:08 -0800330 // The remaining cases are all non-standard extensions imitating the behavior
331 // of various other compilers.
332 unsigned NumNonExtensionDecls = FoundDecls.size();
333
334 if (SS.isSet()) {
335 // For compatibility with older broken C++ rules and existing code,
336 //
337 // nested-name-specifier :: ~ type-name
338 //
339 // also looks for type-name within the nested-name-specifier.
340 if (ParsedType T = LookupInNestedNameSpec(SS)) {
341 Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope)
342 << SS.getRange()
343 << FixItHint::CreateInsertion(SS.getEndLoc(),
344 ("::" + II.getName()).str());
345 return T;
David Blaikie5e026f52013-03-20 17:42:13 +0000346 }
Richard Smith0e3a4872020-02-07 16:34:08 -0800347
348 // For compatibility with other compilers and older versions of Clang,
349 //
350 // nested-name-specifier type-name :: ~ type-name
351 //
352 // also looks for type-name in the scope. Unfortunately, we can't
353 // reasonably apply this fallback for dependent nested-name-specifiers.
354 if (SS.getScopeRep()->getPrefix()) {
355 if (ParsedType T = LookupInScope()) {
356 Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope)
357 << FixItHint::CreateRemoval(SS.getRange());
358 Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here)
359 << GetTypeFromParser(T);
360 return T;
361 }
362 }
363 }
364
365 // We didn't find anything matching; tell the user what we did find (if
366 // anything).
367
368 // Don't tell the user about declarations we shouldn't have found.
369 FoundDecls.resize(NumNonExtensionDecls);
370
371 // List types before non-types.
372 std::stable_sort(FoundDecls.begin(), FoundDecls.end(),
373 [](NamedDecl *A, NamedDecl *B) {
374 return isa<TypeDecl>(A->getUnderlyingDecl()) >
375 isa<TypeDecl>(B->getUnderlyingDecl());
376 });
377
378 // Suggest a fixit to properly name the destroyed type.
379 auto MakeFixItHint = [&]{
380 const CXXRecordDecl *Destroyed = nullptr;
381 // FIXME: If we have a scope specifier, suggest its last component?
382 if (!SearchType.isNull())
383 Destroyed = SearchType->getAsCXXRecordDecl();
384 else if (S)
385 Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity());
386 if (Destroyed)
387 return FixItHint::CreateReplacement(SourceRange(NameLoc),
388 Destroyed->getNameAsString());
389 return FixItHint();
390 };
391
392 if (FoundDecls.empty()) {
393 // FIXME: Attempt typo-correction?
394 Diag(NameLoc, diag::err_undeclared_destructor_name)
395 << &II << MakeFixItHint();
396 } else if (!SearchType.isNull() && FoundDecls.size() == 1) {
397 if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) {
398 assert(!SearchType.isNull() &&
399 "should only reject a type result if we have a search type");
400 QualType T = Context.getTypeDeclType(TD);
401 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
402 << T << SearchType << MakeFixItHint();
403 } else {
404 Diag(NameLoc, diag::err_destructor_expr_nontype)
405 << &II << MakeFixItHint();
406 }
407 } else {
408 Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype
409 : diag::err_destructor_expr_mismatch)
410 << &II << SearchType << MakeFixItHint();
411 }
412
413 for (NamedDecl *FoundD : FoundDecls) {
414 if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl()))
415 Diag(FoundD->getLocation(), diag::note_destructor_type_here)
416 << Context.getTypeDeclType(TD);
417 else
418 Diag(FoundD->getLocation(), diag::note_destructor_nontype_here)
419 << FoundD;
David Blaikie5e026f52013-03-20 17:42:13 +0000420 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000421
David Blaikieefdccaa2016-01-15 23:43:34 +0000422 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000423}
424
Richard Smithef2cd8f2017-02-08 20:39:08 +0000425ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
426 ParsedType ObjectType) {
427 if (DS.getTypeSpecType() == DeclSpec::TST_error)
428 return nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000429
Richard Smithef2cd8f2017-02-08 20:39:08 +0000430 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
431 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
432 return nullptr;
433 }
434
435 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
436 "unexpected type in getDestructorType");
437 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
438
439 // If we know the type of the object, check that the correct destructor
440 // type was named now; we can give better diagnostics this way.
441 QualType SearchType = GetTypeFromParser(ObjectType);
442 if (!SearchType.isNull() && !SearchType->isDependentType() &&
443 !Context.hasSameUnqualifiedType(T, SearchType)) {
David Blaikieecd8a942011-12-08 16:13:53 +0000444 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
445 << T << SearchType;
David Blaikieefdccaa2016-01-15 23:43:34 +0000446 return nullptr;
Richard Smithef2cd8f2017-02-08 20:39:08 +0000447 }
448
449 return ParsedType::make(T);
David Blaikieecd8a942011-12-08 16:13:53 +0000450}
451
Richard Smithd091dc12013-12-05 00:58:33 +0000452bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
453 const UnqualifiedId &Name) {
Faisal Vali2ab8c152017-12-30 04:15:27 +0000454 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
Richard Smithd091dc12013-12-05 00:58:33 +0000455
456 if (!SS.isValid())
457 return false;
458
459 switch (SS.getScopeRep()->getKind()) {
460 case NestedNameSpecifier::Identifier:
461 case NestedNameSpecifier::TypeSpec:
462 case NestedNameSpecifier::TypeSpecWithTemplate:
463 // Per C++11 [over.literal]p2, literal operators can only be declared at
464 // namespace scope. Therefore, this unqualified-id cannot name anything.
465 // Reject it early, because we have no AST representation for this in the
466 // case where the scope is dependent.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000467 Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
468 << SS.getScopeRep();
Richard Smithd091dc12013-12-05 00:58:33 +0000469 return true;
470
471 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +0000472 case NestedNameSpecifier::Super:
Richard Smithd091dc12013-12-05 00:58:33 +0000473 case NestedNameSpecifier::Namespace:
474 case NestedNameSpecifier::NamespaceAlias:
475 return false;
476 }
477
478 llvm_unreachable("unknown nested name specifier kind");
479}
480
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000481/// Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000482ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000483 SourceLocation TypeidLoc,
484 TypeSourceInfo *Operand,
485 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000486 // C++ [expr.typeid]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000487 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor9da64192010-04-26 22:37:10 +0000488 // that is the operand of typeid are always ignored.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000489 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor9da64192010-04-26 22:37:10 +0000490 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000491 Qualifiers Quals;
492 QualType T
493 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
494 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000495 if (T->getAs<RecordType>() &&
496 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
497 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000498
David Majnemer6f3150a2014-11-21 21:09:12 +0000499 if (T->isVariablyModifiedType())
500 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
501
Richard Smith5d96b4c2019-10-03 18:55:23 +0000502 if (CheckQualifiedFunctionForTypeId(T, TypeidLoc))
503 return ExprError();
504
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000505 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
506 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000507}
508
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000509/// Build a C++ typeid expression with an expression operand.
John McCalldadc5752010-08-24 06:29:42 +0000510ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000511 SourceLocation TypeidLoc,
512 Expr *E,
513 SourceLocation RParenLoc) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000514 bool WasEvaluated = false;
Douglas Gregor9da64192010-04-26 22:37:10 +0000515 if (E && !E->isTypeDependent()) {
John McCall50a2c2c2011-10-11 23:14:30 +0000516 if (E->getType()->isPlaceholderType()) {
517 ExprResult result = CheckPlaceholderExpr(E);
518 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000519 E = result.get();
John McCall50a2c2c2011-10-11 23:14:30 +0000520 }
521
Douglas Gregor9da64192010-04-26 22:37:10 +0000522 QualType T = E->getType();
523 if (const RecordType *RecordT = T->getAs<RecordType>()) {
524 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
525 // C++ [expr.typeid]p3:
526 // [...] If the type of the expression is a class type, the class
527 // shall be completely-defined.
528 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
529 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000530
Douglas Gregor9da64192010-04-26 22:37:10 +0000531 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000532 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000533 // polymorphic class type [...] [the] expression is an unevaluated
534 // operand. [...]
Richard Smithef8bf432012-08-13 20:08:14 +0000535 if (RecordD->isPolymorphic() && E->isGLValue()) {
Eli Friedman456f0182012-01-20 01:26:23 +0000536 // The subexpression is potentially evaluated; switch the context
537 // and recheck the subexpression.
Benjamin Kramerd81108f2012-11-14 15:08:31 +0000538 ExprResult Result = TransformToPotentiallyEvaluated(E);
Eli Friedman456f0182012-01-20 01:26:23 +0000539 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000540 E = Result.get();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000541
542 // We require a vtable to query the type at run time.
543 MarkVTableUsed(TypeidLoc, RecordD);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000544 WasEvaluated = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000545 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000546 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000547
Richard Smith4a6861a2019-10-09 02:04:54 +0000548 ExprResult Result = CheckUnevaluatedOperand(E);
549 if (Result.isInvalid())
550 return ExprError();
551 E = Result.get();
552
Douglas Gregor9da64192010-04-26 22:37:10 +0000553 // C++ [expr.typeid]p4:
554 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000555 // cv-qualified type, the result of the typeid expression refers to a
556 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor9da64192010-04-26 22:37:10 +0000557 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000558 Qualifiers Quals;
559 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
560 if (!Context.hasSameType(T, UnqualT)) {
561 T = UnqualT;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000562 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
Douglas Gregor9da64192010-04-26 22:37:10 +0000563 }
564 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000565
David Majnemer6f3150a2014-11-21 21:09:12 +0000566 if (E->getType()->isVariablyModifiedType())
567 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
568 << E->getType());
Richard Smith51ec0cf2017-02-21 01:17:38 +0000569 else if (!inTemplateInstantiation() &&
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000570 E->HasSideEffects(Context, WasEvaluated)) {
571 // The expression operand for typeid is in an unevaluated expression
572 // context, so side effects could result in unintended consequences.
573 Diag(E->getExprLoc(), WasEvaluated
574 ? diag::warn_side_effects_typeid
575 : diag::warn_side_effects_unevaluated_context);
576 }
David Majnemer6f3150a2014-11-21 21:09:12 +0000577
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000578 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
579 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000580}
581
582/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000583ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000584Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
585 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Anastasia Stulova46b55fa2019-07-18 10:02:35 +0000586 // typeid is not supported in OpenCL.
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +0000587 if (getLangOpts().OpenCLCPlusPlus) {
588 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
589 << "typeid");
590 }
591
Douglas Gregor9da64192010-04-26 22:37:10 +0000592 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000593 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000594 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000595
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000596 if (!CXXTypeInfoDecl) {
597 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
598 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
599 LookupQualifiedName(R, getStdNamespace());
600 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
Nico Weber5f968832012-06-19 23:58:27 +0000601 // Microsoft's typeinfo doesn't have type_info in std but in the global
602 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
Alp Tokerbfa39342014-01-14 12:51:41 +0000603 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
Nico Weber5f968832012-06-19 23:58:27 +0000604 LookupQualifiedName(R, Context.getTranslationUnitDecl());
605 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
606 }
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000607 if (!CXXTypeInfoDecl)
608 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
609 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000610
Nico Weber1b7f39d2012-05-20 01:27:21 +0000611 if (!getLangOpts().RTTI) {
612 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
613 }
614
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000615 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000616
Douglas Gregor9da64192010-04-26 22:37:10 +0000617 if (isType) {
618 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000619 TypeSourceInfo *TInfo = nullptr;
John McCallba7bf592010-08-24 05:47:05 +0000620 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
621 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000622 if (T.isNull())
623 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000624
Douglas Gregor9da64192010-04-26 22:37:10 +0000625 if (!TInfo)
626 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000627
Douglas Gregor9da64192010-04-26 22:37:10 +0000628 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000629 }
Mike Stump11289f42009-09-09 15:08:12 +0000630
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000631 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000632 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000633}
634
David Majnemer1dbc7a72016-03-27 04:46:07 +0000635/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
636/// a single GUID.
637static void
638getUuidAttrOfType(Sema &SemaRef, QualType QT,
639 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
640 // Optionally remove one level of pointer, reference or array indirection.
641 const Type *Ty = QT.getTypePtr();
642 if (QT->isPointerType() || QT->isReferenceType())
643 Ty = QT->getPointeeType().getTypePtr();
644 else if (QT->isArrayType())
645 Ty = Ty->getBaseElementTypeUnsafe();
646
Reid Klecknere516eab2016-12-13 18:58:09 +0000647 const auto *TD = Ty->getAsTagDecl();
648 if (!TD)
David Majnemer1dbc7a72016-03-27 04:46:07 +0000649 return;
650
Reid Klecknere516eab2016-12-13 18:58:09 +0000651 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000652 UuidAttrs.insert(Uuid);
653 return;
654 }
655
656 // __uuidof can grab UUIDs from template arguments.
Reid Klecknere516eab2016-12-13 18:58:09 +0000657 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000658 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
659 for (const TemplateArgument &TA : TAL.asArray()) {
660 const UuidAttr *UuidForTA = nullptr;
661 if (TA.getKind() == TemplateArgument::Type)
662 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
663 else if (TA.getKind() == TemplateArgument::Declaration)
664 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
665
666 if (UuidForTA)
667 UuidAttrs.insert(UuidForTA);
668 }
669 }
670}
671
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000672/// Build a Microsoft __uuidof expression with a type operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000673ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
674 SourceLocation TypeidLoc,
675 TypeSourceInfo *Operand,
676 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000677 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000678 if (!Operand->getType()->isDependentType()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000679 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
680 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
681 if (UuidAttrs.empty())
682 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
683 if (UuidAttrs.size() > 1)
684 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000685 UuidStr = UuidAttrs.back()->getGuid();
Francois Pichetb7577652010-12-27 01:32:00 +0000686 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000687
David Majnemer2041b462016-03-28 03:19:50 +0000688 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000689 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000690}
691
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000692/// Build a Microsoft __uuidof expression with an expression operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000693ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
694 SourceLocation TypeidLoc,
695 Expr *E,
696 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000697 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000698 if (!E->getType()->isDependentType()) {
David Majnemer2041b462016-03-28 03:19:50 +0000699 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
700 UuidStr = "00000000-0000-0000-0000-000000000000";
701 } else {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000702 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
703 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
704 if (UuidAttrs.empty())
David Majnemer59c0ec22013-09-07 06:59:46 +0000705 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
David Majnemer1dbc7a72016-03-27 04:46:07 +0000706 if (UuidAttrs.size() > 1)
707 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000708 UuidStr = UuidAttrs.back()->getGuid();
David Majnemer59c0ec22013-09-07 06:59:46 +0000709 }
Francois Pichetb7577652010-12-27 01:32:00 +0000710 }
David Majnemer59c0ec22013-09-07 06:59:46 +0000711
David Majnemer2041b462016-03-28 03:19:50 +0000712 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000713 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000714}
715
716/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
717ExprResult
718Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
719 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000720 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000721 if (!MSVCGuidDecl) {
722 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
723 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
724 LookupQualifiedName(R, Context.getTranslationUnitDecl());
725 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
726 if (!MSVCGuidDecl)
727 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000728 }
729
Francois Pichet9f4f2072010-09-08 12:20:18 +0000730 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000731
Francois Pichet9f4f2072010-09-08 12:20:18 +0000732 if (isType) {
733 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000734 TypeSourceInfo *TInfo = nullptr;
Francois Pichet9f4f2072010-09-08 12:20:18 +0000735 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
736 &TInfo);
737 if (T.isNull())
738 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000739
Francois Pichet9f4f2072010-09-08 12:20:18 +0000740 if (!TInfo)
741 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
742
743 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
744 }
745
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000746 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000747 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
748}
749
Steve Naroff66356bd2007-09-16 14:56:35 +0000750/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000751ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000752Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000753 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000754 "Unknown C++ Boolean value!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000755 return new (Context)
756 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Bill Wendling4073ed52007-02-13 01:51:42 +0000757}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000758
Sebastian Redl576fd422009-05-10 18:38:11 +0000759/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000760ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000761Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000762 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
Sebastian Redl576fd422009-05-10 18:38:11 +0000763}
764
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000765/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000766ExprResult
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000767Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
768 bool IsThrownVarInScope = false;
769 if (Ex) {
770 // C++0x [class.copymove]p31:
Nico Weberb58e51c2014-11-19 05:21:39 +0000771 // When certain criteria are met, an implementation is allowed to omit the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000772 // copy/move construction of a class object [...]
773 //
David Blaikie3c8c46e2014-11-19 05:48:40 +0000774 // - in a throw-expression, when the operand is the name of a
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000775 // non-volatile automatic object (other than a function or catch-
Nico Weberb58e51c2014-11-19 05:21:39 +0000776 // clause parameter) whose scope does not extend beyond the end of the
David Blaikie3c8c46e2014-11-19 05:48:40 +0000777 // innermost enclosing try-block (if there is one), the copy/move
778 // operation from the operand to the exception object (15.1) can be
779 // omitted by constructing the automatic object directly into the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000780 // exception object
781 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
782 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
783 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
784 for( ; S; S = S->getParent()) {
785 if (S->isDeclScope(Var)) {
786 IsThrownVarInScope = true;
787 break;
788 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000789
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000790 if (S->getFlags() &
791 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
792 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
793 Scope::TryScope))
794 break;
795 }
796 }
797 }
798 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000799
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000800 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
801}
802
Simon Pilgrim75c26882016-09-30 14:25:09 +0000803ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000804 bool IsThrownVarInScope) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000805 // Don't report an error if 'throw' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000806 if (!getLangOpts().CXXExceptions &&
Alexey Bataev3167b302019-02-22 14:42:48 +0000807 !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) {
Alexey Bataevc416e642019-02-08 18:02:25 +0000808 // Delay error emission for the OpenMP device code.
Alexey Bataev7feae052019-02-20 19:37:17 +0000809 targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";
Alexey Bataevc416e642019-02-08 18:02:25 +0000810 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000811
Justin Lebar2a8db342016-09-28 22:45:54 +0000812 // Exceptions aren't allowed in CUDA device code.
813 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +0000814 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
815 << "throw" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +0000816
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000817 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
818 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
819
John Wiegley01296292011-04-08 18:41:53 +0000820 if (Ex && !Ex->isTypeDependent()) {
David Majnemerba3e5ec2015-03-13 18:26:17 +0000821 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
822 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
John Wiegley01296292011-04-08 18:41:53 +0000823 return ExprError();
David Majnemerba3e5ec2015-03-13 18:26:17 +0000824
825 // Initialize the exception result. This implicitly weeds out
826 // abstract types or types with inaccessible copy constructors.
827
828 // C++0x [class.copymove]p31:
829 // When certain criteria are met, an implementation is allowed to omit the
830 // copy/move construction of a class object [...]
831 //
832 // - in a throw-expression, when the operand is the name of a
833 // non-volatile automatic object (other than a function or
834 // catch-clause
835 // parameter) whose scope does not extend beyond the end of the
836 // innermost enclosing try-block (if there is one), the copy/move
837 // operation from the operand to the exception object (15.1) can be
838 // omitted by constructing the automatic object directly into the
839 // exception object
840 const VarDecl *NRVOVariable = nullptr;
841 if (IsThrownVarInScope)
Richard Trieu09c163b2018-03-15 03:00:55 +0000842 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict);
David Majnemerba3e5ec2015-03-13 18:26:17 +0000843
844 InitializedEntity Entity = InitializedEntity::InitializeException(
845 OpLoc, ExceptionObjectTy,
846 /*NRVO=*/NRVOVariable != nullptr);
847 ExprResult Res = PerformMoveOrCopyInitialization(
848 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
849 if (Res.isInvalid())
850 return ExprError();
851 Ex = Res.get();
John Wiegley01296292011-04-08 18:41:53 +0000852 }
David Majnemerba3e5ec2015-03-13 18:26:17 +0000853
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000854 return new (Context)
855 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000856}
857
David Majnemere7a818f2015-03-06 18:53:55 +0000858static void
859collectPublicBases(CXXRecordDecl *RD,
860 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
861 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
862 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
863 bool ParentIsPublic) {
864 for (const CXXBaseSpecifier &BS : RD->bases()) {
865 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
866 bool NewSubobject;
867 // Virtual bases constitute the same subobject. Non-virtual bases are
868 // always distinct subobjects.
869 if (BS.isVirtual())
870 NewSubobject = VBases.insert(BaseDecl).second;
871 else
872 NewSubobject = true;
873
874 if (NewSubobject)
875 ++SubobjectsSeen[BaseDecl];
876
877 // Only add subobjects which have public access throughout the entire chain.
878 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
879 if (PublicPath)
880 PublicSubobjectsSeen.insert(BaseDecl);
881
882 // Recurse on to each base subobject.
883 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
884 PublicPath);
885 }
886}
887
888static void getUnambiguousPublicSubobjects(
889 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
890 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
891 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
892 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
893 SubobjectsSeen[RD] = 1;
894 PublicSubobjectsSeen.insert(RD);
895 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
896 /*ParentIsPublic=*/true);
897
898 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
899 // Skip ambiguous objects.
900 if (SubobjectsSeen[PublicSubobject] > 1)
901 continue;
902
903 Objects.push_back(PublicSubobject);
904 }
905}
906
Sebastian Redl4de47b42009-04-27 20:27:31 +0000907/// CheckCXXThrowOperand - Validate the operand of a throw.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000908bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
909 QualType ExceptionObjectTy, Expr *E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000910 // If the type of the exception would be an incomplete type or a pointer
911 // to an incomplete type other than (cv) void the program is ill-formed.
David Majnemerd09a51c2015-03-03 01:50:05 +0000912 QualType Ty = ExceptionObjectTy;
John McCall2e6567a2010-04-22 01:10:34 +0000913 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000914 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000915 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000916 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000917 }
918 if (!isPointer || !Ty->isVoidType()) {
919 if (RequireCompleteType(ThrowLoc, Ty,
David Majnemerba3e5ec2015-03-13 18:26:17 +0000920 isPointer ? diag::err_throw_incomplete_ptr
921 : diag::err_throw_incomplete,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000922 E->getSourceRange()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000923 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000924
David Majnemerd09a51c2015-03-03 01:50:05 +0000925 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
Douglas Gregorae298422012-05-04 17:09:59 +0000926 diag::err_throw_abstract_type, E))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000927 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000928 }
929
Eli Friedman91a3d272010-06-03 20:39:03 +0000930 // If the exception has class type, we need additional handling.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000931 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
932 if (!RD)
933 return false;
Eli Friedman91a3d272010-06-03 20:39:03 +0000934
Douglas Gregor88d292c2010-05-13 16:44:06 +0000935 // If we are throwing a polymorphic class type or pointer thereof,
936 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000937 MarkVTableUsed(ThrowLoc, RD);
938
Eli Friedman36ebbec2010-10-12 20:32:36 +0000939 // If a pointer is thrown, the referenced object will not be destroyed.
940 if (isPointer)
David Majnemerba3e5ec2015-03-13 18:26:17 +0000941 return false;
Eli Friedman36ebbec2010-10-12 20:32:36 +0000942
Richard Smitheec915d62012-02-18 04:13:32 +0000943 // If the class has a destructor, we must be able to call it.
David Majnemere7a818f2015-03-06 18:53:55 +0000944 if (!RD->hasIrrelevantDestructor()) {
945 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
946 MarkFunctionReferenced(E->getExprLoc(), Destructor);
947 CheckDestructorAccess(E->getExprLoc(), Destructor,
948 PDiag(diag::err_access_dtor_exception) << Ty);
949 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000950 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000951 }
952 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000953
David Majnemerdfa6d202015-03-11 18:36:39 +0000954 // The MSVC ABI creates a list of all types which can catch the exception
955 // object. This list also references the appropriate copy constructor to call
956 // if the object is caught by value and has a non-trivial copy constructor.
David Majnemere7a818f2015-03-06 18:53:55 +0000957 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000958 // We are only interested in the public, unambiguous bases contained within
959 // the exception object. Bases which are ambiguous or otherwise
960 // inaccessible are not catchable types.
David Majnemere7a818f2015-03-06 18:53:55 +0000961 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
962 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
David Majnemerdfa6d202015-03-11 18:36:39 +0000963
David Majnemere7a818f2015-03-06 18:53:55 +0000964 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000965 // Attempt to lookup the copy constructor. Various pieces of machinery
966 // will spring into action, like template instantiation, which means this
967 // cannot be a simple walk of the class's decls. Instead, we must perform
968 // lookup and overload resolution.
969 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
Reid Kleckner812bdb32019-10-30 14:38:11 -0700970 if (!CD || CD->isDeleted())
David Majnemerdfa6d202015-03-11 18:36:39 +0000971 continue;
972
973 // Mark the constructor referenced as it is used by this throw expression.
974 MarkFunctionReferenced(E->getExprLoc(), CD);
975
976 // Skip this copy constructor if it is trivial, we don't need to record it
977 // in the catchable type data.
978 if (CD->isTrivial())
979 continue;
980
981 // The copy constructor is non-trivial, create a mapping from this class
982 // type to this constructor.
983 // N.B. The selection of copy constructor is not sensitive to this
984 // particular throw-site. Lookup will be performed at the catch-site to
985 // ensure that the copy constructor is, in fact, accessible (via
986 // friendship or any other means).
987 Context.addCopyConstructorForExceptionObject(Subobject, CD);
988
989 // We don't keep the instantiated default argument expressions around so
990 // we must rebuild them here.
991 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
Reid Klecknerc01ee752016-11-23 16:51:30 +0000992 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
993 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000994 }
995 }
996 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000997
Akira Hatanakac39a2432019-05-10 02:16:37 +0000998 // Under the Itanium C++ ABI, memory for the exception object is allocated by
999 // the runtime with no ability for the compiler to request additional
1000 // alignment. Warn if the exception type requires alignment beyond the minimum
1001 // guaranteed by the target C++ runtime.
1002 if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) {
1003 CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
1004 CharUnits ExnObjAlign = Context.getExnObjectAlignment();
1005 if (ExnObjAlign < TypeAlign) {
1006 Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
1007 Diag(ThrowLoc, diag::note_throw_underaligned_obj)
1008 << Ty << (unsigned)TypeAlign.getQuantity()
1009 << (unsigned)ExnObjAlign.getQuantity();
1010 }
1011 }
1012
David Majnemerba3e5ec2015-03-13 18:26:17 +00001013 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001014}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001015
Faisal Vali67b04462016-06-11 16:41:54 +00001016static QualType adjustCVQualifiersForCXXThisWithinLambda(
1017 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
1018 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
1019
1020 QualType ClassType = ThisTy->getPointeeType();
1021 LambdaScopeInfo *CurLSI = nullptr;
1022 DeclContext *CurDC = CurSemaContext;
1023
1024 // Iterate through the stack of lambdas starting from the innermost lambda to
1025 // the outermost lambda, checking if '*this' is ever captured by copy - since
1026 // that could change the cv-qualifiers of the '*this' object.
1027 // The object referred to by '*this' starts out with the cv-qualifiers of its
1028 // member function. We then start with the innermost lambda and iterate
1029 // outward checking to see if any lambda performs a by-copy capture of '*this'
1030 // - and if so, any nested lambda must respect the 'constness' of that
1031 // capturing lamdbda's call operator.
1032 //
1033
Faisal Vali999f27e2017-05-02 20:56:34 +00001034 // Since the FunctionScopeInfo stack is representative of the lexical
1035 // nesting of the lambda expressions during initial parsing (and is the best
1036 // place for querying information about captures about lambdas that are
1037 // partially processed) and perhaps during instantiation of function templates
1038 // that contain lambda expressions that need to be transformed BUT not
1039 // necessarily during instantiation of a nested generic lambda's function call
1040 // operator (which might even be instantiated at the end of the TU) - at which
1041 // time the DeclContext tree is mature enough to query capture information
1042 // reliably - we use a two pronged approach to walk through all the lexically
1043 // enclosing lambda expressions:
1044 //
1045 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
1046 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
1047 // enclosed by the call-operator of the LSI below it on the stack (while
1048 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
1049 // the stack represents the innermost lambda.
1050 //
1051 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
1052 // represents a lambda's call operator. If it does, we must be instantiating
1053 // a generic lambda's call operator (represented by the Current LSI, and
1054 // should be the only scenario where an inconsistency between the LSI and the
1055 // DeclContext should occur), so climb out the DeclContexts if they
1056 // represent lambdas, while querying the corresponding closure types
1057 // regarding capture information.
Faisal Vali67b04462016-06-11 16:41:54 +00001058
Faisal Vali999f27e2017-05-02 20:56:34 +00001059 // 1) Climb down the function scope info stack.
Faisal Vali67b04462016-06-11 16:41:54 +00001060 for (int I = FunctionScopes.size();
Faisal Vali999f27e2017-05-02 20:56:34 +00001061 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
1062 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
1063 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
Faisal Vali67b04462016-06-11 16:41:54 +00001064 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
1065 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001066
1067 if (!CurLSI->isCXXThisCaptured())
Faisal Vali67b04462016-06-11 16:41:54 +00001068 continue;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001069
Faisal Vali67b04462016-06-11 16:41:54 +00001070 auto C = CurLSI->getCXXThisCapture();
1071
1072 if (C.isCopyCapture()) {
1073 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1074 if (CurLSI->CallOperator->isConst())
1075 ClassType.addConst();
1076 return ASTCtx.getPointerType(ClassType);
1077 }
1078 }
Faisal Vali999f27e2017-05-02 20:56:34 +00001079
1080 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
1081 // happen during instantiation of its nested generic lambda call operator)
Faisal Vali67b04462016-06-11 16:41:54 +00001082 if (isLambdaCallOperator(CurDC)) {
Faisal Vali999f27e2017-05-02 20:56:34 +00001083 assert(CurLSI && "While computing 'this' capture-type for a generic "
1084 "lambda, we must have a corresponding LambdaScopeInfo");
1085 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
1086 "While computing 'this' capture-type for a generic lambda, when we "
1087 "run out of enclosing LSI's, yet the enclosing DC is a "
1088 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1089 "lambda call oeprator");
Faisal Vali67b04462016-06-11 16:41:54 +00001090 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
Simon Pilgrim75c26882016-09-30 14:25:09 +00001091
Faisal Vali67b04462016-06-11 16:41:54 +00001092 auto IsThisCaptured =
1093 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1094 IsConst = false;
1095 IsByCopy = false;
1096 for (auto &&C : Closure->captures()) {
1097 if (C.capturesThis()) {
1098 if (C.getCaptureKind() == LCK_StarThis)
1099 IsByCopy = true;
1100 if (Closure->getLambdaCallOperator()->isConst())
1101 IsConst = true;
1102 return true;
1103 }
1104 }
1105 return false;
1106 };
1107
1108 bool IsByCopyCapture = false;
1109 bool IsConstCapture = false;
1110 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1111 while (Closure &&
1112 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1113 if (IsByCopyCapture) {
1114 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1115 if (IsConstCapture)
1116 ClassType.addConst();
1117 return ASTCtx.getPointerType(ClassType);
1118 }
1119 Closure = isLambdaCallOperator(Closure->getParent())
1120 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1121 : nullptr;
1122 }
1123 }
1124 return ASTCtx.getPointerType(ClassType);
1125}
1126
Eli Friedman73a04092012-01-07 04:59:52 +00001127QualType Sema::getCurrentThisType() {
1128 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +00001129 QualType ThisTy = CXXThisTypeOverride;
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001130
Richard Smith938f40b2011-06-11 17:19:42 +00001131 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1132 if (method && method->isInstance())
Brian Gesiak5488ab42019-01-11 01:54:53 +00001133 ThisTy = method->getThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001134 }
Faisal Validc6b5962016-03-21 09:25:37 +00001135
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001136 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
Richard Smith51ec0cf2017-02-21 01:17:38 +00001137 inTemplateInstantiation()) {
Faisal Validc6b5962016-03-21 09:25:37 +00001138
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001139 assert(isa<CXXRecordDecl>(DC) &&
1140 "Trying to get 'this' type from static method?");
1141
1142 // This is a lambda call operator that is being instantiated as a default
1143 // initializer. DC must point to the enclosing class type, so we can recover
1144 // the 'this' type from it.
1145
1146 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1147 // There are no cv-qualifiers for 'this' within default initializers,
1148 // per [expr.prim.general]p4.
1149 ThisTy = Context.getPointerType(ClassTy);
Faisal Validc6b5962016-03-21 09:25:37 +00001150 }
Faisal Vali67b04462016-06-11 16:41:54 +00001151
1152 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1153 // might need to be adjusted if the lambda or any of its enclosing lambda's
1154 // captures '*this' by copy.
1155 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1156 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1157 CurContext, Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001158 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +00001159}
1160
Simon Pilgrim75c26882016-09-30 14:25:09 +00001161Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
Douglas Gregor3024f072012-04-16 07:05:22 +00001162 Decl *ContextDecl,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001163 Qualifiers CXXThisTypeQuals,
Simon Pilgrim75c26882016-09-30 14:25:09 +00001164 bool Enabled)
Douglas Gregor3024f072012-04-16 07:05:22 +00001165 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1166{
1167 if (!Enabled || !ContextDecl)
1168 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00001169
1170 CXXRecordDecl *Record = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00001171 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1172 Record = Template->getTemplatedDecl();
1173 else
1174 Record = cast<CXXRecordDecl>(ContextDecl);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001175
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001176 QualType T = S.Context.getRecordType(Record);
1177 T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1178
1179 S.CXXThisTypeOverride = S.Context.getPointerType(T);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001180
Douglas Gregor3024f072012-04-16 07:05:22 +00001181 this->Enabled = true;
1182}
1183
1184
1185Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1186 if (Enabled) {
1187 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1188 }
1189}
1190
Simon Pilgrim75c26882016-09-30 14:25:09 +00001191bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
Faisal Validc6b5962016-03-21 09:25:37 +00001192 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1193 const bool ByCopy) {
Eli Friedman73a04092012-01-07 04:59:52 +00001194 // We don't need to capture this in an unevaluated context.
John McCallf413f5e2013-05-03 00:10:13 +00001195 if (isUnevaluatedContext() && !Explicit)
Faisal Valia17d19f2013-11-07 05:17:06 +00001196 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001197
Faisal Validc6b5962016-03-21 09:25:37 +00001198 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
Eli Friedman73a04092012-01-07 04:59:52 +00001199
Reid Kleckner87a31802018-03-12 21:43:02 +00001200 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1201 ? *FunctionScopeIndexToStopAt
1202 : FunctionScopes.size() - 1;
Faisal Validc6b5962016-03-21 09:25:37 +00001203
Simon Pilgrim75c26882016-09-30 14:25:09 +00001204 // Check that we can capture the *enclosing object* (referred to by '*this')
1205 // by the capturing-entity/closure (lambda/block/etc) at
1206 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1207
1208 // Note: The *enclosing object* can only be captured by-value by a
1209 // closure that is a lambda, using the explicit notation:
Faisal Validc6b5962016-03-21 09:25:37 +00001210 // [*this] { ... }.
1211 // Every other capture of the *enclosing object* results in its by-reference
1212 // capture.
1213
1214 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1215 // stack), we can capture the *enclosing object* only if:
1216 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1217 // - or, 'L' has an implicit capture.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001218 // AND
Faisal Validc6b5962016-03-21 09:25:37 +00001219 // -- there is no enclosing closure
Simon Pilgrim75c26882016-09-30 14:25:09 +00001220 // -- or, there is some enclosing closure 'E' that has already captured the
1221 // *enclosing object*, and every intervening closure (if any) between 'E'
Faisal Validc6b5962016-03-21 09:25:37 +00001222 // and 'L' can implicitly capture the *enclosing object*.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001223 // -- or, every enclosing closure can implicitly capture the
Faisal Validc6b5962016-03-21 09:25:37 +00001224 // *enclosing object*
Simon Pilgrim75c26882016-09-30 14:25:09 +00001225
1226
Faisal Validc6b5962016-03-21 09:25:37 +00001227 unsigned NumCapturingClosures = 0;
Reid Kleckner87a31802018-03-12 21:43:02 +00001228 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +00001229 if (CapturingScopeInfo *CSI =
1230 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1231 if (CSI->CXXThisCaptureIndex != 0) {
1232 // 'this' is already being captured; there isn't anything more to do.
Malcolm Parsons87a03622017-01-13 15:01:06 +00001233 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
Eli Friedman73a04092012-01-07 04:59:52 +00001234 break;
1235 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001236 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1237 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1238 // This context can't implicitly capture 'this'; fail out.
1239 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001240 Diag(Loc, diag::err_this_capture)
1241 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001242 return true;
1243 }
Eli Friedman20139d32012-01-11 02:36:31 +00001244 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +00001245 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001246 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001247 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Faisal Validc6b5962016-03-21 09:25:37 +00001248 (Explicit && idx == MaxFunctionScopesIndex)) {
1249 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1250 // iteration through can be an explicit capture, all enclosing closures,
1251 // if any, must perform implicit captures.
1252
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001253 // This closure can capture 'this'; continue looking upwards.
Faisal Validc6b5962016-03-21 09:25:37 +00001254 NumCapturingClosures++;
Eli Friedman73a04092012-01-07 04:59:52 +00001255 continue;
1256 }
Eli Friedman20139d32012-01-11 02:36:31 +00001257 // This context can't implicitly capture 'this'; fail out.
Faisal Valia17d19f2013-11-07 05:17:06 +00001258 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001259 Diag(Loc, diag::err_this_capture)
1260 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001261 return true;
Eli Friedman73a04092012-01-07 04:59:52 +00001262 }
Eli Friedman73a04092012-01-07 04:59:52 +00001263 break;
1264 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001265 if (!BuildAndDiagnose) return false;
Faisal Validc6b5962016-03-21 09:25:37 +00001266
1267 // If we got here, then the closure at MaxFunctionScopesIndex on the
1268 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1269 // (including implicit by-reference captures in any enclosing closures).
1270
1271 // In the loop below, respect the ByCopy flag only for the closure requesting
1272 // the capture (i.e. first iteration through the loop below). Ignore it for
Simon Pilgrimb17efcb2016-11-15 18:28:07 +00001273 // all enclosing closure's up to NumCapturingClosures (since they must be
Faisal Validc6b5962016-03-21 09:25:37 +00001274 // implicitly capturing the *enclosing object* by reference (see loop
1275 // above)).
1276 assert((!ByCopy ||
1277 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1278 "Only a lambda can capture the enclosing object (referred to by "
1279 "*this) by copy");
Faisal Vali67b04462016-06-11 16:41:54 +00001280 QualType ThisTy = getCurrentThisType();
Reid Kleckner87a31802018-03-12 21:43:02 +00001281 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1282 --idx, --NumCapturingClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +00001283 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001284
Richard Smith30116532019-05-28 23:09:46 +00001285 // The type of the corresponding data member (not a 'this' pointer if 'by
1286 // copy').
1287 QualType CaptureType = ThisTy;
1288 if (ByCopy) {
1289 // If we are capturing the object referred to by '*this' by copy, ignore
1290 // any cv qualifiers inherited from the type of the member function for
1291 // the type of the closure-type's corresponding data member and any use
1292 // of 'this'.
1293 CaptureType = ThisTy->getPointeeType();
1294 CaptureType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1295 }
1296
Faisal Validc6b5962016-03-21 09:25:37 +00001297 bool isNested = NumCapturingClosures > 1;
Richard Smithb5a45bb2019-05-31 01:17:04 +00001298 CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);
Eli Friedman73a04092012-01-07 04:59:52 +00001299 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001300 return false;
Eli Friedman73a04092012-01-07 04:59:52 +00001301}
1302
Richard Smith938f40b2011-06-11 17:19:42 +00001303ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +00001304 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1305 /// is a non-lvalue expression whose value is the address of the object for
1306 /// which the function is called.
1307
Douglas Gregor09deffa2011-10-18 16:47:30 +00001308 QualType ThisTy = getCurrentThisType();
Richard Smith8458c9e2019-05-24 01:35:07 +00001309 if (ThisTy.isNull())
1310 return Diag(Loc, diag::err_invalid_this_use);
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001311 return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
Richard Smith8458c9e2019-05-24 01:35:07 +00001312}
John McCallf3a88602011-02-03 08:15:49 +00001313
Richard Smith8458c9e2019-05-24 01:35:07 +00001314Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type,
1315 bool IsImplicit) {
1316 auto *This = new (Context) CXXThisExpr(Loc, Type, IsImplicit);
1317 MarkThisReferenced(This);
1318 return This;
1319}
1320
1321void Sema::MarkThisReferenced(CXXThisExpr *This) {
1322 CheckCXXThisCapture(This->getExprLoc());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001323}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001324
Douglas Gregor3024f072012-04-16 07:05:22 +00001325bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1326 // If we're outside the body of a member function, then we'll have a specified
1327 // type for 'this'.
1328 if (CXXThisTypeOverride.isNull())
1329 return false;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001330
Douglas Gregor3024f072012-04-16 07:05:22 +00001331 // Determine whether we're looking into a class that's currently being
1332 // defined.
1333 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1334 return Class && Class->isBeingDefined();
1335}
1336
Vedant Kumara14a1f92018-01-17 18:53:51 +00001337/// 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()").
John McCalldadc5752010-08-24 06:29:42 +00001341ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +00001342Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001343 SourceLocation LParenOrBraceLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001344 MultiExprArg exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001345 SourceLocation RParenOrBraceLoc,
1346 bool ListInitialization) {
Douglas Gregor7df89f52010-02-05 19:11:37 +00001347 if (!TypeRep)
1348 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001349
John McCall97513962010-01-15 18:39:57 +00001350 TypeSourceInfo *TInfo;
1351 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1352 if (!TInfo)
1353 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +00001354
Vedant Kumara14a1f92018-01-17 18:53:51 +00001355 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1356 RParenOrBraceLoc, ListInitialization);
Richard Smithb8c414c2016-06-30 20:24:30 +00001357 // Avoid creating a non-type-dependent expression that contains typos.
1358 // Non-type-dependent expressions are liable to be discarded without
1359 // checking for embedded typos.
1360 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1361 !Result.get()->isTypeDependent())
1362 Result = CorrectDelayedTyposInExpr(Result.get());
1363 return Result;
Douglas Gregor2b88c112010-09-08 00:15:04 +00001364}
1365
Douglas Gregor2b88c112010-09-08 00:15:04 +00001366ExprResult
1367Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001368 SourceLocation LParenOrBraceLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001369 MultiExprArg Exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001370 SourceLocation RParenOrBraceLoc,
1371 bool ListInitialization) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00001372 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +00001373 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001374
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001375 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Vedant Kumara14a1f92018-01-17 18:53:51 +00001376 // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1377 // directly. We work around this by dropping the locations of the braces.
1378 SourceRange Locs = ListInitialization
1379 ? SourceRange()
1380 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1381 return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(),
1382 Exprs, Locs.getEnd());
Douglas Gregor0950e412009-03-13 21:01:28 +00001383 }
1384
Richard Smith600b5262017-01-26 20:40:47 +00001385 assert((!ListInitialization ||
1386 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1387 "List initialization must have initializer list as expression.");
Vedant Kumara14a1f92018-01-17 18:53:51 +00001388 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
Sebastian Redld74dd492012-02-12 18:41:05 +00001389
Richard Smith60437622017-02-09 19:17:44 +00001390 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1391 InitializationKind Kind =
1392 Exprs.size()
1393 ? ListInitialization
Vedant Kumara14a1f92018-01-17 18:53:51 +00001394 ? InitializationKind::CreateDirectList(
1395 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1396 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1397 RParenOrBraceLoc)
1398 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1399 RParenOrBraceLoc);
Richard Smith60437622017-02-09 19:17:44 +00001400
1401 // C++1z [expr.type.conv]p1:
1402 // If the type is a placeholder for a deduced class type, [...perform class
1403 // template argument deduction...]
1404 DeducedType *Deduced = Ty->getContainedDeducedType();
1405 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1406 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1407 Kind, Exprs);
1408 if (Ty.isNull())
1409 return ExprError();
1410 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1411 }
1412
Douglas Gregordd04d332009-01-16 18:33:17 +00001413 // C++ [expr.type.conv]p1:
Richard Smith49a6b6e2017-03-24 01:14:25 +00001414 // If the expression list is a parenthesized single expression, the type
1415 // conversion expression is equivalent (in definedness, and if defined in
1416 // meaning) to the corresponding cast expression.
1417 if (Exprs.size() == 1 && !ListInitialization &&
1418 !isa<InitListExpr>(Exprs[0])) {
John McCallb50451a2011-10-05 07:41:44 +00001419 Expr *Arg = Exprs[0];
Vedant Kumara14a1f92018-01-17 18:53:51 +00001420 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1421 RParenOrBraceLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001422 }
1423
Richard Smith49a6b6e2017-03-24 01:14:25 +00001424 // For an expression of the form T(), T shall not be an array type.
Eli Friedman576cbd02012-02-29 00:00:28 +00001425 QualType ElemTy = Ty;
1426 if (Ty->isArrayType()) {
1427 if (!ListInitialization)
Richard Smith49a6b6e2017-03-24 01:14:25 +00001428 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1429 << FullRange);
Eli Friedman576cbd02012-02-29 00:00:28 +00001430 ElemTy = Context.getBaseElementType(Ty);
1431 }
1432
Richard Smith49a6b6e2017-03-24 01:14:25 +00001433 // There doesn't seem to be an explicit rule against this but sanity demands
1434 // we only construct objects with object types.
1435 if (Ty->isFunctionType())
1436 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1437 << Ty << FullRange);
David Majnemer7eddcff2015-09-14 07:05:00 +00001438
Richard Smith49a6b6e2017-03-24 01:14:25 +00001439 // C++17 [expr.type.conv]p2:
1440 // If the type is cv void and the initializer is (), the expression is a
1441 // prvalue of the specified type that performs no initialization.
Eli Friedman576cbd02012-02-29 00:00:28 +00001442 if (!Ty->isVoidType() &&
1443 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001444 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +00001445 return ExprError();
1446
Richard Smith49a6b6e2017-03-24 01:14:25 +00001447 // Otherwise, the expression is a prvalue of the specified type whose
1448 // result object is direct-initialized (11.6) with the initializer.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001449 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1450 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001451
Richard Smith49a6b6e2017-03-24 01:14:25 +00001452 if (Result.isInvalid())
Richard Smith90061902013-09-23 02:20:00 +00001453 return Result;
1454
1455 Expr *Inner = Result.get();
1456 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1457 Inner = BTE->getSubExpr();
Richard Smith49a6b6e2017-03-24 01:14:25 +00001458 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1459 !isa<CXXScalarValueInitExpr>(Inner)) {
Richard Smith1ae689c2015-01-28 22:06:01 +00001460 // If we created a CXXTemporaryObjectExpr, that node also represents the
1461 // functional cast. Otherwise, create an explicit cast to represent
1462 // the syntactic form of a functional-style cast that was used here.
1463 //
1464 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1465 // would give a more consistent AST representation than using a
1466 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1467 // is sometimes handled by initialization and sometimes not.
Richard Smith90061902013-09-23 02:20:00 +00001468 QualType ResultType = Result.get()->getType();
Vedant Kumara14a1f92018-01-17 18:53:51 +00001469 SourceRange Locs = ListInitialization
1470 ? SourceRange()
1471 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001472 Result = CXXFunctionalCastExpr::Create(
Vedant Kumara14a1f92018-01-17 18:53:51 +00001473 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1474 Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd());
Sebastian Redl2b80af42012-02-13 19:55:43 +00001475 }
1476
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001477 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001478}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001479
Artem Belevich78929ef2018-09-21 17:29:33 +00001480bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) {
1481 // [CUDA] Ignore this function, if we can't call it.
1482 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
1483 if (getLangOpts().CUDA &&
1484 IdentifyCUDAPreference(Caller, Method) <= CFP_WrongSide)
1485 return false;
1486
1487 SmallVector<const FunctionDecl*, 4> PreventedBy;
1488 bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1489
1490 if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1491 return Result;
1492
1493 // In case of CUDA, return true if none of the 1-argument deallocator
1494 // functions are actually callable.
1495 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1496 assert(FD->getNumParams() == 1 &&
1497 "Only single-operand functions should be in PreventedBy");
1498 return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice;
1499 });
1500}
1501
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001502/// Determine whether the given function is a non-placement
Richard Smithb2f0f052016-10-10 18:54:32 +00001503/// deallocation function.
1504static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001505 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
Artem Belevich78929ef2018-09-21 17:29:33 +00001506 return S.isUsualDeallocationFunction(Method);
Richard Smithb2f0f052016-10-10 18:54:32 +00001507
1508 if (FD->getOverloadedOperator() != OO_Delete &&
1509 FD->getOverloadedOperator() != OO_Array_Delete)
1510 return false;
1511
1512 unsigned UsualParams = 1;
1513
1514 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1515 S.Context.hasSameUnqualifiedType(
1516 FD->getParamDecl(UsualParams)->getType(),
1517 S.Context.getSizeType()))
1518 ++UsualParams;
1519
1520 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1521 S.Context.hasSameUnqualifiedType(
1522 FD->getParamDecl(UsualParams)->getType(),
1523 S.Context.getTypeDeclType(S.getStdAlignValT())))
1524 ++UsualParams;
1525
1526 return UsualParams == FD->getNumParams();
1527}
1528
1529namespace {
1530 struct UsualDeallocFnInfo {
1531 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
Richard Smithf75dcbe2016-10-11 00:21:10 +00001532 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
Richard Smithb2f0f052016-10-10 18:54:32 +00001533 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
Richard Smith5b349582017-10-13 01:55:36 +00001534 Destroying(false), HasSizeT(false), HasAlignValT(false),
1535 CUDAPref(Sema::CFP_Native) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001536 // A function template declaration is never a usual deallocation function.
1537 if (!FD)
1538 return;
Richard Smith5b349582017-10-13 01:55:36 +00001539 unsigned NumBaseParams = 1;
1540 if (FD->isDestroyingOperatorDelete()) {
1541 Destroying = true;
1542 ++NumBaseParams;
1543 }
Eric Fiselier8e920502019-01-16 02:34:36 +00001544
1545 if (NumBaseParams < FD->getNumParams() &&
1546 S.Context.hasSameUnqualifiedType(
1547 FD->getParamDecl(NumBaseParams)->getType(),
1548 S.Context.getSizeType())) {
1549 ++NumBaseParams;
1550 HasSizeT = true;
1551 }
1552
1553 if (NumBaseParams < FD->getNumParams() &&
1554 FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1555 ++NumBaseParams;
1556 HasAlignValT = true;
Richard Smithb2f0f052016-10-10 18:54:32 +00001557 }
Richard Smithf75dcbe2016-10-11 00:21:10 +00001558
1559 // In CUDA, determine how much we'd like / dislike to call this.
1560 if (S.getLangOpts().CUDA)
1561 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1562 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001563 }
1564
Eric Fiselierfa752f22018-03-21 19:19:48 +00001565 explicit operator bool() const { return FD; }
Richard Smithb2f0f052016-10-10 18:54:32 +00001566
Richard Smithf75dcbe2016-10-11 00:21:10 +00001567 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1568 bool WantAlign) const {
Richard Smith5b349582017-10-13 01:55:36 +00001569 // C++ P0722:
1570 // A destroying operator delete is preferred over a non-destroying
1571 // operator delete.
1572 if (Destroying != Other.Destroying)
1573 return Destroying;
1574
Richard Smithf75dcbe2016-10-11 00:21:10 +00001575 // C++17 [expr.delete]p10:
1576 // If the type has new-extended alignment, a function with a parameter
1577 // of type std::align_val_t is preferred; otherwise a function without
1578 // such a parameter is preferred
1579 if (HasAlignValT != Other.HasAlignValT)
1580 return HasAlignValT == WantAlign;
1581
1582 if (HasSizeT != Other.HasSizeT)
1583 return HasSizeT == WantSize;
1584
1585 // Use CUDA call preference as a tiebreaker.
1586 return CUDAPref > Other.CUDAPref;
1587 }
1588
Richard Smithb2f0f052016-10-10 18:54:32 +00001589 DeclAccessPair Found;
1590 FunctionDecl *FD;
Richard Smith5b349582017-10-13 01:55:36 +00001591 bool Destroying, HasSizeT, HasAlignValT;
Richard Smithf75dcbe2016-10-11 00:21:10 +00001592 Sema::CUDAFunctionPreference CUDAPref;
Richard Smithb2f0f052016-10-10 18:54:32 +00001593 };
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.
1600static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1601 return S.getLangOpts().AlignedAllocation &&
1602 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1603 S.getASTContext().getTargetInfo().getNewAlign();
1604}
1605
1606/// Select the correct "usual" deallocation function to use from a selection of
1607/// deallocation functions (either global or class-scope).
1608static UsualDeallocFnInfo resolveDeallocationOverload(
1609 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1610 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1611 UsualDeallocFnInfo Best;
1612
Richard Smithb2f0f052016-10-10 18:54:32 +00001613 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00001614 UsualDeallocFnInfo Info(S, I.getPair());
1615 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1616 Info.CUDAPref == Sema::CFP_Never)
Richard Smithb2f0f052016-10-10 18:54:32 +00001617 continue;
1618
1619 if (!Best) {
1620 Best = Info;
1621 if (BestFns)
1622 BestFns->push_back(Info);
1623 continue;
1624 }
1625
Richard Smithf75dcbe2016-10-11 00:21:10 +00001626 if (Best.isBetterThan(Info, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001627 continue;
1628
1629 // If more than one preferred function is found, all non-preferred
1630 // functions are eliminated from further consideration.
Richard Smithf75dcbe2016-10-11 00:21:10 +00001631 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001632 BestFns->clear();
1633
1634 Best = Info;
1635 if (BestFns)
1636 BestFns->push_back(Info);
1637 }
1638
1639 return Best;
1640}
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).
John McCall284c48f2011-01-27 09:37:56 +00001646static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1647 QualType allocType) {
1648 const RecordType *record =
1649 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1650 if (!record) return false;
1651
1652 // Try to find an operator delete[] in class scope.
1653
1654 DeclarationName deleteName =
1655 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1656 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1657 S.LookupQualifiedName(ops, record->getDecl());
1658
1659 // We're just doing this for information.
1660 ops.suppressDiagnostics();
1661
1662 // Very likely: there's no operator delete[].
1663 if (ops.empty()) return false;
1664
1665 // If it's ambiguous, it should be illegal to call operator delete[]
1666 // on this thing, so it doesn't matter if we allocate extra space or not.
1667 if (ops.isAmbiguous()) return false;
1668
Richard Smithb2f0f052016-10-10 18:54:32 +00001669 // C++17 [expr.delete]p10:
1670 // If the deallocation functions have class scope, the one without a
1671 // parameter of type std::size_t is selected.
1672 auto Best = resolveDeallocationOverload(
1673 S, ops, /*WantSize*/false,
1674 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1675 return Best && Best.HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00001676}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001677
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001678/// Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +00001679///
Sebastian Redld74dd492012-02-12 18:41:05 +00001680/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +00001681/// @code new (memory) int[size][4] @endcode
1682/// or
1683/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001684///
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.
James Dennettf14a6e52012-06-15 22:23:43 +00001692/// \param Initializer The initializing expression or initializer-list, or null
1693/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001694ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001695Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001696 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001697 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001698 Declarator &D, Expr *Initializer) {
Richard Smithb9fb1212019-05-06 03:47:15 +00001699 Optional<Expr *> ArraySize;
Sebastian Redl351bb782008-12-02 14:43:59 +00001700 // If the specified type is an array, unwrap it and save the expression.
1701 if (D.getNumTypeObjects() > 0 &&
1702 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
Richard Smith3beb7c62017-01-12 02:27:38 +00001703 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smithbfbff072017-02-10 22:35:37 +00001704 if (D.getDeclSpec().hasAutoTypeSpec())
Richard Smith30482bc2011-02-20 03:19:35 +00001705 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1706 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001707 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001708 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1709 << D.getSourceRange());
Richard Smithb9fb1212019-05-06 03:47:15 +00001710 if (!Chunk.Arr.NumElts && !Initializer)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001711 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1712 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001713
Sebastian Redl351bb782008-12-02 14:43:59 +00001714 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001715 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001716 }
1717
Douglas Gregor73341c42009-09-11 00:18:58 +00001718 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001719 if (ArraySize) {
1720 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001721 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1722 break;
1723
1724 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1725 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001726 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001727 if (getLangOpts().CPlusPlus14) {
Fangrui Song99337e22018-07-20 08:19:20 +00001728 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1729 // shall be a converted constant expression (5.19) of type std::size_t
1730 // and shall evaluate to a strictly positive value.
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001731 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1732 assert(IntWidth && "Builtin type of size 0?");
1733 llvm::APSInt Value(IntWidth);
1734 Array.NumElts
1735 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1736 CCEK_NewExpr)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001737 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001738 } else {
1739 Array.NumElts
Craig Topperc3ec1492014-05-26 06:22:03 +00001740 = VerifyIntegerConstantExpression(NumElts, nullptr,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001741 diag::err_new_array_nonconst)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001742 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001743 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001744 if (!Array.NumElts)
1745 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001746 }
1747 }
1748 }
1749 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001750
Craig Topperc3ec1492014-05-26 06:22:03 +00001751 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
John McCall8cb7bdf2010-06-04 23:28:52 +00001752 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001753 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001754 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001755
Sebastian Redl6047f072012-02-16 12:22:20 +00001756 SourceRange DirectInitRange;
Richard Smith49a6b6e2017-03-24 01:14:25 +00001757 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
Sebastian Redl6047f072012-02-16 12:22:20 +00001758 DirectInitRange = List->getSourceRange();
1759
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001760 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1761 PlacementLParen, PlacementArgs, PlacementRParen,
1762 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001763 Initializer);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001764}
1765
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001766static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1767 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001768 if (!Init)
1769 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001770 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1771 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001772 if (isa<ImplicitValueInitExpr>(Init))
1773 return true;
1774 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1775 return !CCE->isListInitialization() &&
1776 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001777 else if (Style == CXXNewExpr::ListInit) {
1778 assert(isa<InitListExpr>(Init) &&
1779 "Shouldn't create list CXXConstructExprs for arrays.");
1780 return true;
1781 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001782 return false;
1783}
1784
Akira Hatanaka71645c22018-12-21 07:05:36 +00001785bool
1786Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const {
1787 if (!getLangOpts().AlignedAllocationUnavailable)
1788 return false;
1789 if (FD.isDefined())
1790 return false;
1791 bool IsAligned = false;
1792 if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned)
1793 return true;
1794 return false;
1795}
1796
Akira Hatanakacae83f72017-06-29 18:48:40 +00001797// Emit a diagnostic if an aligned allocation/deallocation function that is not
1798// implemented in the standard library is selected.
Akira Hatanaka71645c22018-12-21 07:05:36 +00001799void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1800 SourceLocation Loc) {
1801 if (isUnavailableAlignedAllocationFunction(FD)) {
1802 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001803 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
Akira Hatanaka71645c22018-12-21 07:05:36 +00001804 getASTContext().getTargetInfo().getPlatformName());
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001805
Akira Hatanaka71645c22018-12-21 07:05:36 +00001806 OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator();
1807 bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
1808 Diag(Loc, diag::err_aligned_allocation_unavailable)
Volodymyr Sapsaie5015ab2018-08-03 23:12:37 +00001809 << IsDelete << FD.getType().getAsString() << OSName
1810 << alignedAllocMinVersion(T.getOS()).getAsString();
Akira Hatanaka71645c22018-12-21 07:05:36 +00001811 Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
Akira Hatanakacae83f72017-06-29 18:48:40 +00001812 }
1813}
1814
John McCalldadc5752010-08-24 06:29:42 +00001815ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001816Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001817 SourceLocation PlacementLParen,
1818 MultiExprArg PlacementArgs,
1819 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001820 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001821 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001822 TypeSourceInfo *AllocTypeInfo,
Richard Smithb9fb1212019-05-06 03:47:15 +00001823 Optional<Expr *> ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001824 SourceRange DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001825 Expr *Initializer) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001826 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001827 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001828
Sebastian Redl6047f072012-02-16 12:22:20 +00001829 CXXNewExpr::InitializationStyle initStyle;
1830 if (DirectInitRange.isValid()) {
1831 assert(Initializer && "Have parens but no initializer.");
1832 initStyle = CXXNewExpr::CallInit;
1833 } else if (Initializer && isa<InitListExpr>(Initializer))
1834 initStyle = CXXNewExpr::ListInit;
1835 else {
1836 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1837 isa<CXXConstructExpr>(Initializer)) &&
1838 "Initializer expression that cannot have been implicitly created.");
1839 initStyle = CXXNewExpr::NoInit;
1840 }
1841
1842 Expr **Inits = &Initializer;
1843 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001844 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1845 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1846 Inits = List->getExprs();
1847 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001848 }
1849
Richard Smith60437622017-02-09 19:17:44 +00001850 // C++11 [expr.new]p15:
1851 // A new-expression that creates an object of type T initializes that
1852 // object as follows:
1853 InitializationKind Kind
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001854 // - If the new-initializer is omitted, the object is default-
1855 // initialized (8.5); if no initialization is performed,
1856 // the object has indeterminate value
1857 = initStyle == CXXNewExpr::NoInit
1858 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1859 // - Otherwise, the new-initializer is interpreted according to
1860 // the
1861 // initialization rules of 8.5 for direct-initialization.
1862 : initStyle == CXXNewExpr::ListInit
1863 ? InitializationKind::CreateDirectList(
1864 TypeRange.getBegin(), Initializer->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001865 Initializer->getEndLoc())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001866 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1867 DirectInitRange.getBegin(),
1868 DirectInitRange.getEnd());
Richard Smith600b5262017-01-26 20:40:47 +00001869
Richard Smith60437622017-02-09 19:17:44 +00001870 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1871 auto *Deduced = AllocType->getContainedDeducedType();
1872 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1873 if (ArraySize)
Richard Smithb9fb1212019-05-06 03:47:15 +00001874 return ExprError(
1875 Diag(ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
1876 diag::err_deduced_class_template_compound_type)
1877 << /*array*/ 2
1878 << (ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
Richard Smith60437622017-02-09 19:17:44 +00001879
1880 InitializedEntity Entity
1881 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1882 AllocType = DeduceTemplateSpecializationFromInitializer(
1883 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1884 if (AllocType.isNull())
1885 return ExprError();
1886 } else if (Deduced) {
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001887 bool Braced = (initStyle == CXXNewExpr::ListInit);
1888 if (NumInits == 1) {
1889 if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1890 Inits = p->getInits();
1891 NumInits = p->getNumInits();
1892 Braced = true;
1893 }
1894 }
1895
Sebastian Redl6047f072012-02-16 12:22:20 +00001896 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001897 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1898 << AllocType << TypeRange);
Sebastian Redl6047f072012-02-16 12:22:20 +00001899 if (NumInits > 1) {
1900 Expr *FirstBad = Inits[1];
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001901 return ExprError(Diag(FirstBad->getBeginLoc(),
Richard Smith30482bc2011-02-20 03:19:35 +00001902 diag::err_auto_new_ctor_multiple_expressions)
1903 << AllocType << TypeRange);
1904 }
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001905 if (Braced && !getLangOpts().CPlusPlus17)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001906 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001907 << AllocType << TypeRange;
Richard Smith42a22372019-04-24 02:22:38 +00001908 Expr *Deduce = Inits[0];
Richard Smith061f1e22013-04-30 21:23:01 +00001909 QualType DeducedType;
Richard Smith42a22372019-04-24 02:22:38 +00001910 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001911 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Richard Smith42a22372019-04-24 02:22:38 +00001912 << AllocType << Deduce->getType()
1913 << TypeRange << Deduce->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001914 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001915 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001916 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001917 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001918
Douglas Gregorcda95f42010-05-16 16:01:03 +00001919 // Per C++0x [expr.new]p5, the type being constructed may be a
1920 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001921 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001922 if (const ConstantArrayType *Array
1923 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001924 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1925 Context.getSizeType(),
1926 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001927 AllocType = Array->getElementType();
1928 }
1929 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001930
Douglas Gregor3999e152010-10-06 16:00:31 +00001931 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1932 return ExprError();
1933
Simon Pilgrim75c26882016-09-30 14:25:09 +00001934 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001935 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001936 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1937 AllocType->isObjCLifetimeType()) {
1938 AllocType = Context.getLifetimeQualifiedType(AllocType,
1939 AllocType->getObjCARCImplicitLifetime());
1940 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001941
John McCall31168b02011-06-15 23:02:42 +00001942 QualType ResultType = Context.getPointerType(AllocType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001943
Richard Smithb9fb1212019-05-06 03:47:15 +00001944 if (ArraySize && *ArraySize &&
1945 (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
1946 ExprResult result = CheckPlaceholderExpr(*ArraySize);
John McCall5e77d762013-04-16 07:28:30 +00001947 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001948 ArraySize = result.get();
John McCall5e77d762013-04-16 07:28:30 +00001949 }
Richard Smith8dd34252012-02-04 07:07:42 +00001950 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1951 // integral or enumeration type with a non-negative value."
1952 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1953 // enumeration type, or a class type for which a single non-explicit
1954 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001955 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001956 // std::size_t.
Richard Smith0511d232016-10-05 22:41:02 +00001957 llvm::Optional<uint64_t> KnownArraySize;
Richard Smithb9fb1212019-05-06 03:47:15 +00001958 if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001959 ExprResult ConvertedSize;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001960 if (getLangOpts().CPlusPlus14) {
Alp Toker965f8822013-11-27 05:22:15 +00001961 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1962
Richard Smithb9fb1212019-05-06 03:47:15 +00001963 ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(),
Fangrui Song99337e22018-07-20 08:19:20 +00001964 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00001965
Simon Pilgrim75c26882016-09-30 14:25:09 +00001966 if (!ConvertedSize.isInvalid() &&
Richard Smithb9fb1212019-05-06 03:47:15 +00001967 (*ArraySize)->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00001968 // Diagnose the compatibility of this conversion.
1969 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
Richard Smithb9fb1212019-05-06 03:47:15 +00001970 << (*ArraySize)->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001971 } else {
1972 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1973 protected:
1974 Expr *ArraySize;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001975
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001976 public:
1977 SizeConvertDiagnoser(Expr *ArraySize)
1978 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1979 ArraySize(ArraySize) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001980
1981 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1982 QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001983 return S.Diag(Loc, diag::err_array_size_not_integral)
1984 << S.getLangOpts().CPlusPlus11 << T;
1985 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001986
1987 SemaDiagnosticBuilder diagnoseIncomplete(
1988 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001989 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1990 << T << ArraySize->getSourceRange();
1991 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001992
1993 SemaDiagnosticBuilder diagnoseExplicitConv(
1994 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001995 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1996 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001997
1998 SemaDiagnosticBuilder noteExplicitConv(
1999 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00002000 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2001 << ConvTy->isEnumeralType() << ConvTy;
2002 }
Craig Toppere14c0f82014-03-12 04:55:44 +00002003
2004 SemaDiagnosticBuilder diagnoseAmbiguous(
2005 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00002006 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
2007 }
Craig Toppere14c0f82014-03-12 04:55:44 +00002008
2009 SemaDiagnosticBuilder noteAmbiguous(
2010 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00002011 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2012 << ConvTy->isEnumeralType() << ConvTy;
2013 }
Richard Smithccc11812013-05-21 19:05:48 +00002014
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002015 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2016 QualType T,
2017 QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00002018 return S.Diag(Loc,
2019 S.getLangOpts().CPlusPlus11
2020 ? diag::warn_cxx98_compat_array_size_conversion
2021 : diag::ext_array_size_conversion)
2022 << T << ConvTy->isEnumeralType() << ConvTy;
2023 }
Richard Smithb9fb1212019-05-06 03:47:15 +00002024 } SizeDiagnoser(*ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00002025
Richard Smithb9fb1212019-05-06 03:47:15 +00002026 ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00002027 SizeDiagnoser);
2028 }
Douglas Gregor4799d032010-06-30 00:20:43 +00002029 if (ConvertedSize.isInvalid())
2030 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002031
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002032 ArraySize = ConvertedSize.get();
Richard Smithb9fb1212019-05-06 03:47:15 +00002033 QualType SizeType = (*ArraySize)->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00002034
Douglas Gregor0bf31402010-10-08 23:50:27 +00002035 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00002036 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002037
Richard Smithbcc9bcb2012-02-04 05:35:53 +00002038 // C++98 [expr.new]p7:
2039 // The expression in a direct-new-declarator shall have integral type
2040 // with a non-negative value.
2041 //
Richard Smith0511d232016-10-05 22:41:02 +00002042 // Let's see if this is a constant < 0. If so, we reject it out of hand,
2043 // per CWG1464. Otherwise, if it's not a constant, we must have an
2044 // unparenthesized array type.
Richard Smithb9fb1212019-05-06 03:47:15 +00002045 if (!(*ArraySize)->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002046 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00002047 // We've already performed any required implicit conversion to integer or
2048 // unscoped enumeration type.
Richard Smith0511d232016-10-05 22:41:02 +00002049 // FIXME: Per CWG1464, we are required to check the value prior to
2050 // converting to size_t. This will never find a negative array size in
2051 // C++14 onwards, because Value is always unsigned here!
Richard Smithb9fb1212019-05-06 03:47:15 +00002052 if ((*ArraySize)->isIntegerConstantExpr(Value, Context)) {
Richard Smith0511d232016-10-05 22:41:02 +00002053 if (Value.isSigned() && Value.isNegative()) {
Richard Smithb9fb1212019-05-06 03:47:15 +00002054 return ExprError(Diag((*ArraySize)->getBeginLoc(),
Richard Smith0511d232016-10-05 22:41:02 +00002055 diag::err_typecheck_negative_array_size)
Richard Smithb9fb1212019-05-06 03:47:15 +00002056 << (*ArraySize)->getSourceRange());
Richard Smith0511d232016-10-05 22:41:02 +00002057 }
2058
2059 if (!AllocType->isDependentType()) {
Richard Smithbcc9bcb2012-02-04 05:35:53 +00002060 unsigned ActiveSizeBits =
2061 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
Richard Smith0511d232016-10-05 22:41:02 +00002062 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002063 return ExprError(
Richard Smithb9fb1212019-05-06 03:47:15 +00002064 Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2065 << Value.toString(10) << (*ArraySize)->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00002066 }
Richard Smith0511d232016-10-05 22:41:02 +00002067
2068 KnownArraySize = Value.getZExtValue();
Douglas Gregorf2753b32010-07-13 15:54:32 +00002069 } else if (TypeIdParens.isValid()) {
2070 // Can't have dynamic array size when the type-id is in parentheses.
Richard Smithb9fb1212019-05-06 03:47:15 +00002071 Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2072 << (*ArraySize)->getSourceRange()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002073 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2074 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002075
Douglas Gregorf2753b32010-07-13 15:54:32 +00002076 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002077 }
Sebastian Redl351bb782008-12-02 14:43:59 +00002078 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002079
John McCall036f2f62011-05-15 07:14:44 +00002080 // Note that we do *not* convert the argument in any way. It can
2081 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00002082 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002083
Craig Topperc3ec1492014-05-26 06:22:03 +00002084 FunctionDecl *OperatorNew = nullptr;
2085 FunctionDecl *OperatorDelete = nullptr;
Richard Smithb2f0f052016-10-10 18:54:32 +00002086 unsigned Alignment =
2087 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2088 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2089 bool PassAlignment = getLangOpts().AlignedAllocation &&
2090 Alignment > NewAlignment;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002091
Brian Gesiakcb024022018-04-01 22:59:22 +00002092 AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002093 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002094 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Richard Smithb9fb1212019-05-06 03:47:15 +00002095 FindAllocationFunctions(
2096 StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope,
2097 AllocType, ArraySize.hasValue(), PassAlignment, PlacementArgs,
2098 OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002099 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00002100
2101 // If this is an array allocation, compute whether the usual array
2102 // deallocation function for the type has a size_t parameter.
2103 bool UsualArrayDeleteWantsSize = false;
2104 if (ArraySize && !AllocType->isDependentType())
Richard Smithb2f0f052016-10-10 18:54:32 +00002105 UsualArrayDeleteWantsSize =
2106 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
John McCall284c48f2011-01-27 09:37:56 +00002107
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002108 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00002109 if (OperatorNew) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002110 const FunctionProtoType *Proto =
Richard Smithd6f9e732014-05-13 19:56:21 +00002111 OperatorNew->getType()->getAs<FunctionProtoType>();
2112 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2113 : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002114
Richard Smithd6f9e732014-05-13 19:56:21 +00002115 // We've already converted the placement args, just fill in any default
2116 // arguments. Skip the first parameter because we don't have a corresponding
Richard Smithb2f0f052016-10-10 18:54:32 +00002117 // argument. Skip the second parameter too if we're passing in the
2118 // alignment; we've already filled it in.
Roman Lebedevb8fdafe2020-02-26 01:36:44 +03002119 unsigned NumImplicitArgs = PassAlignment ? 2 : 1;
Richard Smithb2f0f052016-10-10 18:54:32 +00002120 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
Roman Lebedevb8fdafe2020-02-26 01:36:44 +03002121 NumImplicitArgs, PlacementArgs, AllPlaceArgs,
2122 CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00002123 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002124
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002125 if (!AllPlaceArgs.empty())
2126 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00002127
Roman Lebedevb8fdafe2020-02-26 01:36:44 +03002128 // We would like to perform some checking on the given `operator new` call,
2129 // but the PlacementArgs does not contain the implicit arguments,
2130 // namely allocation size and maybe allocation alignment,
2131 // so we need to conjure them.
Eli Friedmanff4b4072012-02-18 04:48:30 +00002132
Roman Lebedevb8fdafe2020-02-26 01:36:44 +03002133 QualType SizeTy = Context.getSizeType();
2134 unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2135
2136 llvm::APInt SingleEltSize(
2137 SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity());
2138
2139 // How many bytes do we want to allocate here?
2140 llvm::Optional<llvm::APInt> AllocationSize;
2141 if (!ArraySize.hasValue() && !AllocType->isDependentType()) {
2142 // For non-array operator new, we only want to allocate one element.
2143 AllocationSize = SingleEltSize;
2144 } else if (KnownArraySize.hasValue() && !AllocType->isDependentType()) {
2145 // For array operator new, only deal with static array size case.
2146 bool Overflow;
2147 AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize)
2148 .umul_ov(SingleEltSize, Overflow);
2149 (void)Overflow;
2150 assert(
2151 !Overflow &&
2152 "Expected that all the overflows would have been handled already.");
2153 }
2154
2155 IntegerLiteral AllocationSizeLiteral(
2156 Context,
2157 AllocationSize.getValueOr(llvm::APInt::getNullValue(SizeTyWidth)),
2158 SizeTy, SourceLocation());
2159 // Otherwise, if we failed to constant-fold the allocation size, we'll
2160 // just give up and pass-in something opaque, that isn't a null pointer.
2161 OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_RValue,
2162 OK_Ordinary, /*SourceExpr=*/nullptr);
2163
2164 // Let's synthesize the alignment argument in case we will need it.
2165 // Since we *really* want to allocate these on stack, this is slightly ugly
2166 // because there might not be a `std::align_val_t` type.
2167 EnumDecl *StdAlignValT = getStdAlignValT();
2168 QualType AlignValT =
2169 StdAlignValT ? Context.getTypeDeclType(StdAlignValT) : SizeTy;
2170 IntegerLiteral AlignmentLiteral(
2171 Context,
2172 llvm::APInt(Context.getTypeSize(SizeTy),
2173 Alignment / Context.getCharWidth()),
2174 SizeTy, SourceLocation());
2175 ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT,
2176 CK_IntegralCast, &AlignmentLiteral,
2177 VK_RValue);
2178
2179 // Adjust placement args by prepending conjured size and alignment exprs.
2180 llvm::SmallVector<Expr *, 8> CallArgs;
2181 CallArgs.reserve(NumImplicitArgs + PlacementArgs.size());
2182 CallArgs.emplace_back(AllocationSize.hasValue()
2183 ? static_cast<Expr *>(&AllocationSizeLiteral)
2184 : &OpaqueAllocationSize);
2185 if (PassAlignment)
2186 CallArgs.emplace_back(&DesiredAlignment);
2187 CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end());
2188
2189 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs);
2190
2191 checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs,
2192 /*IsMemberFunction=*/false, StartLoc, Range, CallType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002193
Richard Smithb2f0f052016-10-10 18:54:32 +00002194 // Warn if the type is over-aligned and is being allocated by (unaligned)
2195 // global operator new.
2196 if (PlacementArgs.empty() && !PassAlignment &&
2197 (OperatorNew->isImplicit() ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002198 (OperatorNew->getBeginLoc().isValid() &&
2199 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002200 if (Alignment > NewAlignment)
Nick Lewycky411fc652012-01-24 21:15:41 +00002201 Diag(StartLoc, diag::warn_overaligned_type)
2202 << AllocType
Richard Smithb2f0f052016-10-10 18:54:32 +00002203 << unsigned(Alignment / Context.getCharWidth())
2204 << unsigned(NewAlignment / Context.getCharWidth());
Nick Lewycky411fc652012-01-24 21:15:41 +00002205 }
2206 }
2207
Sebastian Redl6047f072012-02-16 12:22:20 +00002208 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002209 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2210 // dialect distinction.
Richard Smith0511d232016-10-05 22:41:02 +00002211 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002212 SourceRange InitRange(Inits[0]->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002213 Inits[NumInits - 1]->getEndLoc());
Richard Smith0511d232016-10-05 22:41:02 +00002214 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2215 return ExprError();
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00002216 }
2217
Richard Smithdd2ca572012-11-26 08:32:48 +00002218 // If we can perform the initialization, and we've not already done so,
2219 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002220 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002221 !Expr::hasAnyTypeDependentArguments(
Richard Smithc6abd962014-07-25 01:12:44 +00002222 llvm::makeArrayRef(Inits, NumInits))) {
Richard Smith0511d232016-10-05 22:41:02 +00002223 // The type we initialize is the complete type, including the array bound.
2224 QualType InitType;
2225 if (KnownArraySize)
2226 InitType = Context.getConstantArrayType(
Richard Smith772e2662019-10-04 01:25:59 +00002227 AllocType,
2228 llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2229 *KnownArraySize),
2230 *ArraySize, ArrayType::Normal, 0);
Richard Smith0511d232016-10-05 22:41:02 +00002231 else if (ArraySize)
2232 InitType =
2233 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2234 else
2235 InitType = AllocType;
2236
Douglas Gregor85dabae2009-12-16 01:38:02 +00002237 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002238 = InitializedEntity::InitializeNew(StartLoc, InitType);
Richard Smith0511d232016-10-05 22:41:02 +00002239 InitializationSequence InitSeq(*this, Entity, Kind,
2240 MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002241 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00002242 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00002243 if (FullInit.isInvalid())
2244 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002245
Sebastian Redl6047f072012-02-16 12:22:20 +00002246 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2247 // we don't want the initialized object to be destructed.
Richard Smith0511d232016-10-05 22:41:02 +00002248 // FIXME: We should not create these in the first place.
Sebastian Redl6047f072012-02-16 12:22:20 +00002249 if (CXXBindTemporaryExpr *Binder =
2250 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002251 FullInit = Binder->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002252
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002253 Initializer = FullInit.get();
Richard Smithb9fb1212019-05-06 03:47:15 +00002254
2255 // FIXME: If we have a KnownArraySize, check that the array bound of the
2256 // initializer is no greater than that constant value.
2257
2258 if (ArraySize && !*ArraySize) {
2259 auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
2260 if (CAT) {
2261 // FIXME: Track that the array size was inferred rather than explicitly
2262 // specified.
2263 ArraySize = IntegerLiteral::Create(
2264 Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
2265 } else {
2266 Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
2267 << Initializer->getSourceRange();
2268 }
2269 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002270 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002271
Douglas Gregor6642ca22010-02-26 05:06:18 +00002272 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00002273 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00002274 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2275 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002276 MarkFunctionReferenced(StartLoc, OperatorNew);
Nick Lewyckya096b142013-02-12 08:08:54 +00002277 }
2278 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00002279 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2280 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002281 MarkFunctionReferenced(StartLoc, OperatorDelete);
Nick Lewyckya096b142013-02-12 08:08:54 +00002282 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002283
Bruno Ricci9b6dfac2019-01-07 15:04:45 +00002284 return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2285 PassAlignment, UsualArrayDeleteWantsSize,
2286 PlacementArgs, TypeIdParens, ArraySize, initStyle,
2287 Initializer, ResultType, AllocTypeInfo, Range,
2288 DirectInitRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002289}
2290
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002291/// Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00002292/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00002293bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00002294 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002295 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2296 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00002297 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002298 return Diag(Loc, diag::err_bad_new_type)
2299 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002300 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002301 return Diag(Loc, diag::err_bad_new_type)
2302 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002303 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002304 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00002305 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00002306 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00002307 diag::err_allocation_of_abstract_type))
2308 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00002309 else if (AllocType->isVariablyModifiedType())
2310 return Diag(Loc, diag::err_variably_modified_new_type)
2311 << AllocType;
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002312 else if (AllocType.getAddressSpace() != LangAS::Default &&
2313 !getLangOpts().OpenCLCPlusPlus)
Douglas Gregor39d1a092011-04-15 19:46:20 +00002314 return Diag(Loc, diag::err_address_space_qualified_new)
Yaxun Liub34ec822017-04-11 17:24:23 +00002315 << AllocType.getUnqualifiedType()
2316 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002317 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002318 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2319 QualType BaseAllocType = Context.getBaseElementType(AT);
2320 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2321 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002322 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00002323 << BaseAllocType;
2324 }
2325 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00002326
Sebastian Redlbd150f42008-11-21 19:14:01 +00002327 return false;
2328}
2329
Brian Gesiak87412d92018-02-15 20:09:25 +00002330static bool resolveAllocationOverload(
2331 Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2332 bool &PassAlignment, FunctionDecl *&Operator,
2333 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002334 OverloadCandidateSet Candidates(R.getNameLoc(),
2335 OverloadCandidateSet::CSK_Normal);
2336 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2337 Alloc != AllocEnd; ++Alloc) {
2338 // Even member operator new/delete are implicitly treated as
2339 // static, so don't use AddMemberCandidate.
2340 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2341
2342 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2343 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2344 /*ExplicitTemplateArgs=*/nullptr, Args,
2345 Candidates,
2346 /*SuppressUserConversions=*/false);
2347 continue;
2348 }
2349
2350 FunctionDecl *Fn = cast<FunctionDecl>(D);
2351 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2352 /*SuppressUserConversions=*/false);
2353 }
2354
2355 // Do the resolution.
2356 OverloadCandidateSet::iterator Best;
2357 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2358 case OR_Success: {
2359 // Got one!
2360 FunctionDecl *FnDecl = Best->Function;
2361 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2362 Best->FoundDecl) == Sema::AR_inaccessible)
2363 return true;
2364
2365 Operator = FnDecl;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002366 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002367 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002368
Richard Smithb2f0f052016-10-10 18:54:32 +00002369 case OR_No_Viable_Function:
2370 // C++17 [expr.new]p13:
2371 // If no matching function is found and the allocated object type has
2372 // new-extended alignment, the alignment argument is removed from the
2373 // argument list, and overload resolution is performed again.
2374 if (PassAlignment) {
2375 PassAlignment = false;
2376 AlignArg = Args[1];
2377 Args.erase(Args.begin() + 1);
2378 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002379 Operator, &Candidates, AlignArg,
2380 Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002381 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002382
Richard Smithb2f0f052016-10-10 18:54:32 +00002383 // MSVC will fall back on trying to find a matching global operator new
2384 // if operator new[] cannot be found. Also, MSVC will leak by not
2385 // generating a call to operator delete or operator delete[], but we
2386 // will not replicate that bug.
2387 // FIXME: Find out how this interacts with the std::align_val_t fallback
2388 // once MSVC implements it.
2389 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2390 S.Context.getLangOpts().MSVCCompat) {
2391 R.clear();
2392 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2393 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2394 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2395 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002396 Operator, /*Candidates=*/nullptr,
2397 /*AlignArg=*/nullptr, Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002398 }
Richard Smith1cdec012013-09-29 04:40:38 +00002399
Brian Gesiak87412d92018-02-15 20:09:25 +00002400 if (Diagnose) {
David Blaikie5e328052019-05-03 00:44:50 +00002401 PartialDiagnosticAt PD(R.getNameLoc(), S.PDiag(diag::err_ovl_no_viable_function_in_call)
2402 << R.getLookupName() << Range);
Richard Smithb2f0f052016-10-10 18:54:32 +00002403
Brian Gesiak87412d92018-02-15 20:09:25 +00002404 // If we have aligned candidates, only note the align_val_t candidates
2405 // from AlignedCandidates and the non-align_val_t candidates from
2406 // Candidates.
2407 if (AlignedCandidates) {
2408 auto IsAligned = [](OverloadCandidate &C) {
2409 return C.Function->getNumParams() > 1 &&
2410 C.Function->getParamDecl(1)->getType()->isAlignValT();
2411 };
2412 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
Richard Smithb2f0f052016-10-10 18:54:32 +00002413
Brian Gesiak87412d92018-02-15 20:09:25 +00002414 // This was an overaligned allocation, so list the aligned candidates
2415 // first.
2416 Args.insert(Args.begin() + 1, AlignArg);
David Blaikie5e328052019-05-03 00:44:50 +00002417 AlignedCandidates->NoteCandidates(PD, S, OCD_AllCandidates, Args, "",
Brian Gesiak87412d92018-02-15 20:09:25 +00002418 R.getNameLoc(), IsAligned);
2419 Args.erase(Args.begin() + 1);
David Blaikie5e328052019-05-03 00:44:50 +00002420 Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args, "", R.getNameLoc(),
Brian Gesiak87412d92018-02-15 20:09:25 +00002421 IsUnaligned);
2422 } else {
David Blaikie5e328052019-05-03 00:44:50 +00002423 Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args);
Brian Gesiak87412d92018-02-15 20:09:25 +00002424 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002425 }
Richard Smith1cdec012013-09-29 04:40:38 +00002426 return true;
2427
Richard Smithb2f0f052016-10-10 18:54:32 +00002428 case OR_Ambiguous:
Brian Gesiak87412d92018-02-15 20:09:25 +00002429 if (Diagnose) {
David Blaikie5e328052019-05-03 00:44:50 +00002430 Candidates.NoteCandidates(
2431 PartialDiagnosticAt(R.getNameLoc(),
2432 S.PDiag(diag::err_ovl_ambiguous_call)
2433 << R.getLookupName() << Range),
Richard Smith70f59b52019-10-23 17:54:10 -07002434 S, OCD_AmbiguousCandidates, Args);
Brian Gesiak87412d92018-02-15 20:09:25 +00002435 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002436 return true;
2437
2438 case OR_Deleted: {
Brian Gesiak87412d92018-02-15 20:09:25 +00002439 if (Diagnose) {
David Blaikie5e328052019-05-03 00:44:50 +00002440 Candidates.NoteCandidates(
2441 PartialDiagnosticAt(R.getNameLoc(),
2442 S.PDiag(diag::err_ovl_deleted_call)
2443 << R.getLookupName() << Range),
2444 S, OCD_AllCandidates, Args);
Brian Gesiak87412d92018-02-15 20:09:25 +00002445 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002446 return true;
2447 }
2448 }
2449 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Douglas Gregor6642ca22010-02-26 05:06:18 +00002450}
2451
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002452bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
Brian Gesiakcb024022018-04-01 22:59:22 +00002453 AllocationFunctionScope NewScope,
2454 AllocationFunctionScope DeleteScope,
2455 QualType AllocType, bool IsArray,
2456 bool &PassAlignment, MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00002457 FunctionDecl *&OperatorNew,
Brian Gesiak87412d92018-02-15 20:09:25 +00002458 FunctionDecl *&OperatorDelete,
2459 bool Diagnose) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002460 // --- Choosing an allocation function ---
2461 // C++ 5.3.4p8 - 14 & 18
Brian Gesiakcb024022018-04-01 22:59:22 +00002462 // 1) If looking in AFS_Global scope for allocation functions, only look in
2463 // the global scope. Else, if AFS_Class, only look in the scope of the
2464 // allocated class. If AFS_Both, look in both.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002465 // 2) If an array size is given, look for operator new[], else look for
2466 // operator new.
2467 // 3) The first argument is always size_t. Append the arguments from the
2468 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002469
Richard Smithb2f0f052016-10-10 18:54:32 +00002470 SmallVector<Expr*, 8> AllocArgs;
2471 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2472
2473 // We don't care about the actual value of these arguments.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002474 // FIXME: Should the Sema create the expression and embed it in the syntax
2475 // tree? Or should the consumer just recalculate the value?
Richard Smithb2f0f052016-10-10 18:54:32 +00002476 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002477 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00002478 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00002479 Context.getSizeType(),
2480 SourceLocation());
Richard Smithb2f0f052016-10-10 18:54:32 +00002481 AllocArgs.push_back(&Size);
2482
2483 QualType AlignValT = Context.VoidTy;
2484 if (PassAlignment) {
2485 DeclareGlobalNewDelete();
2486 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2487 }
2488 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2489 if (PassAlignment)
2490 AllocArgs.push_back(&Align);
2491
2492 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
Sebastian Redlfaf68082008-12-03 20:26:15 +00002493
Douglas Gregor6642ca22010-02-26 05:06:18 +00002494 // C++ [expr.new]p8:
2495 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002496 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00002497 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002498 // type, the allocation function's name is operator new[] and the
2499 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00002500 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
Richard Smithb2f0f052016-10-10 18:54:32 +00002501 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002502
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002503 QualType AllocElemType = Context.getBaseElementType(AllocType);
2504
Richard Smithb2f0f052016-10-10 18:54:32 +00002505 // Find the allocation function.
2506 {
2507 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2508
2509 // C++1z [expr.new]p9:
2510 // If the new-expression begins with a unary :: operator, the allocation
2511 // function's name is looked up in the global scope. Otherwise, if the
2512 // allocated type is a class type T or array thereof, the allocation
2513 // function's name is looked up in the scope of T.
Brian Gesiakcb024022018-04-01 22:59:22 +00002514 if (AllocElemType->isRecordType() && NewScope != AFS_Global)
Richard Smithb2f0f052016-10-10 18:54:32 +00002515 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2516
2517 // We can see ambiguity here if the allocation function is found in
2518 // multiple base classes.
2519 if (R.isAmbiguous())
2520 return true;
2521
2522 // If this lookup fails to find the name, or if the allocated type is not
2523 // a class type, the allocation function's name is looked up in the
2524 // global scope.
Brian Gesiakcb024022018-04-01 22:59:22 +00002525 if (R.empty()) {
2526 if (NewScope == AFS_Class)
2527 return true;
2528
Richard Smithb2f0f052016-10-10 18:54:32 +00002529 LookupQualifiedName(R, Context.getTranslationUnitDecl());
Brian Gesiakcb024022018-04-01 22:59:22 +00002530 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002531
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002532 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
Sven van Haastregt1006a062019-06-26 13:31:24 +00002533 if (PlaceArgs.empty()) {
2534 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2535 } else {
2536 Diag(StartLoc, diag::err_openclcxx_placement_new);
2537 }
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002538 return true;
2539 }
2540
Richard Smithb2f0f052016-10-10 18:54:32 +00002541 assert(!R.empty() && "implicitly declared allocation functions not found");
2542 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2543
2544 // We do our own custom access checks below.
2545 R.suppressDiagnostics();
2546
2547 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002548 OperatorNew, /*Candidates=*/nullptr,
2549 /*AlignArg=*/nullptr, Diagnose))
Sebastian Redlfaf68082008-12-03 20:26:15 +00002550 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002551 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00002552
Richard Smithb2f0f052016-10-10 18:54:32 +00002553 // We don't need an operator delete if we're running under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002554 if (!getLangOpts().Exceptions) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002555 OperatorDelete = nullptr;
John McCall0f55a032010-04-20 02:18:25 +00002556 return false;
2557 }
2558
Richard Smithb2f0f052016-10-10 18:54:32 +00002559 // Note, the name of OperatorNew might have been changed from array to
2560 // non-array by resolveAllocationOverload.
2561 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2562 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2563 ? OO_Array_Delete
2564 : OO_Delete);
2565
Douglas Gregor6642ca22010-02-26 05:06:18 +00002566 // C++ [expr.new]p19:
2567 //
2568 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002569 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00002570 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002571 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00002572 // the scope of T. If this lookup fails to find the name, or if
2573 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002574 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002575 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Brian Gesiakcb024022018-04-01 22:59:22 +00002576 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00002577 auto *RD =
2578 cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00002579 LookupQualifiedName(FoundDelete, RD);
2580 }
John McCallfb6f5262010-03-18 08:19:33 +00002581 if (FoundDelete.isAmbiguous())
2582 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00002583
Richard Smithb2f0f052016-10-10 18:54:32 +00002584 bool FoundGlobalDelete = FoundDelete.empty();
Douglas Gregor6642ca22010-02-26 05:06:18 +00002585 if (FoundDelete.empty()) {
Brian Gesiakcb024022018-04-01 22:59:22 +00002586 if (DeleteScope == AFS_Class)
2587 return true;
2588
Douglas Gregor6642ca22010-02-26 05:06:18 +00002589 DeclareGlobalNewDelete();
2590 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2591 }
2592
2593 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00002594
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002595 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00002596
John McCalld3be2c82010-09-14 21:34:24 +00002597 // Whether we're looking for a placement operator delete is dictated
2598 // by whether we selected a placement operator new, not by whether
2599 // we had explicit placement arguments. This matters for things like
2600 // struct A { void *operator new(size_t, int = 0); ... };
2601 // A *a = new A()
Richard Smithb2f0f052016-10-10 18:54:32 +00002602 //
2603 // We don't have any definition for what a "placement allocation function"
2604 // is, but we assume it's any allocation function whose
2605 // parameter-declaration-clause is anything other than (size_t).
2606 //
2607 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2608 // This affects whether an exception from the constructor of an overaligned
2609 // type uses the sized or non-sized form of aligned operator delete.
2610 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2611 OperatorNew->isVariadic();
John McCalld3be2c82010-09-14 21:34:24 +00002612
2613 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002614 // C++ [expr.new]p20:
2615 // A declaration of a placement deallocation function matches the
2616 // declaration of a placement allocation function if it has the
2617 // same number of parameters and, after parameter transformations
2618 // (8.3.5), all parameter types except the first are
2619 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002620 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00002621 // To perform this comparison, we compute the function type that
2622 // the deallocation function should have, and use that type both
2623 // for template argument deduction and for comparison purposes.
2624 QualType ExpectedFunctionType;
2625 {
2626 const FunctionProtoType *Proto
2627 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002628
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002629 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002630 ArgTypes.push_back(Context.VoidPtrTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00002631 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2632 ArgTypes.push_back(Proto->getParamType(I));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002633
John McCalldb40c7f2010-12-14 08:05:40 +00002634 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithb2f0f052016-10-10 18:54:32 +00002635 // FIXME: This is not part of the standard's rule.
John McCalldb40c7f2010-12-14 08:05:40 +00002636 EPI.Variadic = Proto->isVariadic();
2637
Douglas Gregor6642ca22010-02-26 05:06:18 +00002638 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00002639 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002640 }
2641
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002642 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00002643 DEnd = FoundDelete.end();
2644 D != DEnd; ++D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002645 FunctionDecl *Fn = nullptr;
Richard Smithbaa47832016-12-01 02:11:49 +00002646 if (FunctionTemplateDecl *FnTmpl =
2647 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002648 // Perform template argument deduction to try to match the
2649 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00002650 TemplateDeductionInfo Info(StartLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002651 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2652 Info))
Douglas Gregor6642ca22010-02-26 05:06:18 +00002653 continue;
2654 } else
2655 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2656
Richard Smithbaa47832016-12-01 02:11:49 +00002657 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2658 ExpectedFunctionType,
2659 /*AdjustExcpetionSpec*/true),
2660 ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00002661 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002662 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00002663
Richard Smithb2f0f052016-10-10 18:54:32 +00002664 if (getLangOpts().CUDA)
2665 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2666 } else {
Richard Smith1cdec012013-09-29 04:40:38 +00002667 // C++1y [expr.new]p22:
2668 // For a non-placement allocation function, the normal deallocation
2669 // function lookup is used
Richard Smithb2f0f052016-10-10 18:54:32 +00002670 //
2671 // Per [expr.delete]p10, this lookup prefers a member operator delete
2672 // without a size_t argument, but prefers a non-member operator delete
2673 // with a size_t where possible (which it always is in this case).
2674 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2675 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2676 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2677 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2678 &BestDeallocFns);
2679 if (Selected)
2680 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2681 else {
2682 // If we failed to select an operator, all remaining functions are viable
2683 // but ambiguous.
2684 for (auto Fn : BestDeallocFns)
2685 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
Richard Smith1cdec012013-09-29 04:40:38 +00002686 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002687 }
2688
2689 // C++ [expr.new]p20:
2690 // [...] If the lookup finds a single matching deallocation
2691 // function, that function will be called; otherwise, no
2692 // deallocation function will be called.
2693 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00002694 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002695
Richard Smithb2f0f052016-10-10 18:54:32 +00002696 // C++1z [expr.new]p23:
2697 // If the lookup finds a usual deallocation function (3.7.4.2)
2698 // with a parameter of type std::size_t and that function, considered
Douglas Gregor6642ca22010-02-26 05:06:18 +00002699 // as a placement deallocation function, would have been
2700 // selected as a match for the allocation function, the program
2701 // is ill-formed.
Richard Smithb2f0f052016-10-10 18:54:32 +00002702 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
Richard Smith1cdec012013-09-29 04:40:38 +00002703 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00002704 UsualDeallocFnInfo Info(*this,
2705 DeclAccessPair::make(OperatorDelete, AS_public));
Richard Smithb2f0f052016-10-10 18:54:32 +00002706 // Core issue, per mail to core reflector, 2016-10-09:
2707 // If this is a member operator delete, and there is a corresponding
2708 // non-sized member operator delete, this isn't /really/ a sized
2709 // deallocation function, it just happens to have a size_t parameter.
2710 bool IsSizedDelete = Info.HasSizeT;
2711 if (IsSizedDelete && !FoundGlobalDelete) {
2712 auto NonSizedDelete =
2713 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2714 /*WantAlign*/Info.HasAlignValT);
2715 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2716 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2717 IsSizedDelete = false;
2718 }
2719
2720 if (IsSizedDelete) {
2721 SourceRange R = PlaceArgs.empty()
2722 ? SourceRange()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002723 : SourceRange(PlaceArgs.front()->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002724 PlaceArgs.back()->getEndLoc());
Richard Smithb2f0f052016-10-10 18:54:32 +00002725 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2726 if (!OperatorDelete->isImplicit())
2727 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2728 << DeleteName;
2729 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002730 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002731
2732 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2733 Matches[0].first);
2734 } else if (!Matches.empty()) {
2735 // We found multiple suitable operators. Per [expr.new]p20, that means we
2736 // call no 'operator delete' function, but we should at least warn the user.
2737 // FIXME: Suppress this warning if the construction cannot throw.
2738 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2739 << DeleteName << AllocElemType;
2740
2741 for (auto &Match : Matches)
2742 Diag(Match.second->getLocation(),
2743 diag::note_member_declared_here) << DeleteName;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002744 }
2745
Sebastian Redlfaf68082008-12-03 20:26:15 +00002746 return false;
2747}
2748
2749/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2750/// delete. These are:
2751/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00002752/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00002753/// void* operator new(std::size_t) throw(std::bad_alloc);
2754/// void* operator new[](std::size_t) throw(std::bad_alloc);
2755/// void operator delete(void *) throw();
2756/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002757/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002758/// void* operator new(std::size_t);
2759/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002760/// void operator delete(void *) noexcept;
2761/// void operator delete[](void *) noexcept;
2762/// // C++1y:
2763/// void* operator new(std::size_t);
2764/// void* operator new[](std::size_t);
2765/// void operator delete(void *) noexcept;
2766/// void operator delete[](void *) noexcept;
2767/// void operator delete(void *, std::size_t) noexcept;
2768/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002769/// @endcode
2770/// Note that the placement and nothrow forms of new are *not* implicitly
2771/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00002772void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002773 if (GlobalNewDeleteDeclared)
2774 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002775
Anastasia Stulova46b55fa2019-07-18 10:02:35 +00002776 // The implicitly declared new and delete operators
2777 // are not supported in OpenCL.
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002778 if (getLangOpts().OpenCLCPlusPlus)
2779 return;
2780
Douglas Gregor87f54062009-09-15 22:30:29 +00002781 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002782 // [...] The following allocation and deallocation functions (18.4) are
2783 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00002784 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002785 //
Sebastian Redl37588092011-03-14 18:08:30 +00002786 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00002787 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002788 // void* operator new[](std::size_t) throw(std::bad_alloc);
2789 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00002790 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002791 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002792 // void* operator new(std::size_t);
2793 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002794 // void operator delete(void*) noexcept;
2795 // void operator delete[](void*) noexcept;
2796 // C++1y:
2797 // void* operator new(std::size_t);
2798 // void* operator new[](std::size_t);
2799 // void operator delete(void*) noexcept;
2800 // void operator delete[](void*) noexcept;
2801 // void operator delete(void*, std::size_t) noexcept;
2802 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00002803 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002804 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00002805 // new, operator new[], operator delete, operator delete[].
2806 //
2807 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2808 // "std" or "bad_alloc" as necessary to form the exception specification.
2809 // However, we do not make these implicit declarations visible to name
2810 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002811 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00002812 // The "std::bad_alloc" class has not yet been declared, so build it
2813 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002814 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2815 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002816 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002817 &PP.getIdentifierTable().get("bad_alloc"),
Craig Topperc3ec1492014-05-26 06:22:03 +00002818 nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002819 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00002820 }
Richard Smith59139022016-09-30 22:41:36 +00002821 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
Richard Smith96269c52016-09-29 22:49:46 +00002822 // The "std::align_val_t" enum class has not yet been declared, so build it
2823 // implicitly.
2824 auto *AlignValT = EnumDecl::Create(
2825 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2826 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2827 AlignValT->setIntegerType(Context.getSizeType());
2828 AlignValT->setPromotionType(Context.getSizeType());
2829 AlignValT->setImplicit(true);
2830 StdAlignValT = AlignValT;
2831 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002832
Sebastian Redlfaf68082008-12-03 20:26:15 +00002833 GlobalNewDeleteDeclared = true;
2834
2835 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2836 QualType SizeT = Context.getSizeType();
2837
Richard Smith96269c52016-09-29 22:49:46 +00002838 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2839 QualType Return, QualType Param) {
2840 llvm::SmallVector<QualType, 3> Params;
2841 Params.push_back(Param);
2842
2843 // Create up to four variants of the function (sized/aligned).
2844 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2845 (Kind == OO_Delete || Kind == OO_Array_Delete);
Richard Smith59139022016-09-30 22:41:36 +00002846 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002847
2848 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2849 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2850 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
Richard Smith96269c52016-09-29 22:49:46 +00002851 if (Sized)
2852 Params.push_back(SizeT);
2853
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002854 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
Richard Smith96269c52016-09-29 22:49:46 +00002855 if (Aligned)
2856 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2857
2858 DeclareGlobalAllocationFunction(
2859 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2860
2861 if (Aligned)
2862 Params.pop_back();
2863 }
2864 }
2865 };
2866
2867 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2868 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2869 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2870 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002871}
2872
2873/// DeclareGlobalAllocationFunction - Declares a single implicit global
2874/// allocation function if it doesn't already exist.
2875void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002876 QualType Return,
Richard Smith96269c52016-09-29 22:49:46 +00002877 ArrayRef<QualType> Params) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002878 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2879
2880 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002881 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2882 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2883 Alloc != AllocEnd; ++Alloc) {
2884 // Only look at non-template functions, as it is the predefined,
2885 // non-templated allocation function we are trying to declare here.
2886 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith96269c52016-09-29 22:49:46 +00002887 if (Func->getNumParams() == Params.size()) {
2888 llvm::SmallVector<QualType, 3> FuncParams;
2889 for (auto *P : Func->parameters())
2890 FuncParams.push_back(
2891 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2892 if (llvm::makeArrayRef(FuncParams) == Params) {
Serge Pavlovd5489072013-09-14 12:00:01 +00002893 // Make the function visible to name lookup, even if we found it in
2894 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002895 // allocation function, or is suppressing that function.
Richard Smith90dc5252017-06-23 01:04:34 +00002896 Func->setVisibleDespiteOwningModule();
Chandler Carruth93538422010-02-03 11:02:14 +00002897 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002898 }
Chandler Carruth93538422010-02-03 11:02:14 +00002899 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002900 }
2901 }
Reid Kleckner7270ef52015-03-19 17:03:58 +00002902
Erich Keane881e83d2019-03-04 14:54:52 +00002903 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
Erich Keane00022812019-05-23 16:05:21 +00002904 /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
Richard Smithc015bc22014-02-07 22:39:53 +00002905
Richard Smithf8b417c2014-02-08 00:42:45 +00002906 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002907 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002908 = (Name.getCXXOverloadedOperator() == OO_New ||
2909 Name.getCXXOverloadedOperator() == OO_Array_New);
John McCalldb40c7f2010-12-14 08:05:40 +00002910 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002911 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8b417c2014-02-08 00:42:45 +00002912 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Richard Smithc015bc22014-02-07 22:39:53 +00002913 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Richard Smith8acb4282014-07-31 21:57:55 +00002914 EPI.ExceptionSpec.Type = EST_Dynamic;
2915 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
Sebastian Redl37588092011-03-14 18:08:30 +00002916 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002917 } else {
Richard Smith8acb4282014-07-31 21:57:55 +00002918 EPI.ExceptionSpec =
2919 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002920 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002921
Artem Belevich07db5cf2016-10-21 20:34:05 +00002922 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2923 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2924 FunctionDecl *Alloc = FunctionDecl::Create(
2925 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2926 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2927 Alloc->setImplicit();
Vassil Vassilev41cafcd2017-06-09 21:36:28 +00002928 // Global allocation functions should always be visible.
Richard Smith90dc5252017-06-23 01:04:34 +00002929 Alloc->setVisibleDespiteOwningModule();
Simon Pilgrim75c26882016-09-30 14:25:09 +00002930
Petr Hosek821b38f2018-12-04 03:25:25 +00002931 Alloc->addAttr(VisibilityAttr::CreateImplicit(
2932 Context, LangOpts.GlobalAllocationFunctionVisibilityHidden
2933 ? VisibilityAttr::Hidden
2934 : VisibilityAttr::Default));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002935
Artem Belevich07db5cf2016-10-21 20:34:05 +00002936 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2937 for (QualType T : Params) {
2938 ParamDecls.push_back(ParmVarDecl::Create(
2939 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2940 /*TInfo=*/nullptr, SC_None, nullptr));
2941 ParamDecls.back()->setImplicit();
2942 }
2943 Alloc->setParams(ParamDecls);
2944 if (ExtraAttr)
2945 Alloc->addAttr(ExtraAttr);
2946 Context.getTranslationUnitDecl()->addDecl(Alloc);
2947 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2948 };
2949
2950 if (!LangOpts.CUDA)
2951 CreateAllocationFunctionDecl(nullptr);
2952 else {
2953 // Host and device get their own declaration so each can be
2954 // defined or re-declared independently.
2955 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2956 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
Richard Smithbdd14642014-02-04 01:14:30 +00002957 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002958}
2959
Richard Smith1cdec012013-09-29 04:40:38 +00002960FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2961 bool CanProvideSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00002962 bool Overaligned,
Richard Smith1cdec012013-09-29 04:40:38 +00002963 DeclarationName Name) {
2964 DeclareGlobalNewDelete();
2965
2966 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2967 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2968
Richard Smithb2f0f052016-10-10 18:54:32 +00002969 // FIXME: It's possible for this to result in ambiguity, through a
2970 // user-declared variadic operator delete or the enable_if attribute. We
2971 // should probably not consider those cases to be usual deallocation
2972 // functions. But for now we just make an arbitrary choice in that case.
2973 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2974 Overaligned);
2975 assert(Result.FD && "operator delete missing from global scope?");
2976 return Result.FD;
2977}
Richard Smith1cdec012013-09-29 04:40:38 +00002978
Richard Smithb2f0f052016-10-10 18:54:32 +00002979FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2980 CXXRecordDecl *RD) {
2981 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Richard Smith1cdec012013-09-29 04:40:38 +00002982
Richard Smithb2f0f052016-10-10 18:54:32 +00002983 FunctionDecl *OperatorDelete = nullptr;
2984 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2985 return nullptr;
2986 if (OperatorDelete)
2987 return OperatorDelete;
Artem Belevich94a55e82015-09-22 17:22:59 +00002988
Richard Smithb2f0f052016-10-10 18:54:32 +00002989 // If there's no class-specific operator delete, look up the global
2990 // non-array delete.
2991 return FindUsualDeallocationFunction(
2992 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2993 Name);
Richard Smith1cdec012013-09-29 04:40:38 +00002994}
2995
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002996bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2997 DeclarationName Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00002998 FunctionDecl *&Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002999 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003000 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00003001 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003002
John McCall27b18f82009-11-17 02:14:36 +00003003 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003004 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003005
Chandler Carruthb6f99172010-06-28 00:30:51 +00003006 Found.suppressDiagnostics();
3007
Richard Smithb2f0f052016-10-10 18:54:32 +00003008 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
Chandler Carruth9b418232010-08-08 07:04:00 +00003009
Richard Smithb2f0f052016-10-10 18:54:32 +00003010 // C++17 [expr.delete]p10:
3011 // If the deallocation functions have class scope, the one without a
3012 // parameter of type std::size_t is selected.
3013 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
3014 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
3015 /*WantAlign*/ Overaligned, &Matches);
Chandler Carruth9b418232010-08-08 07:04:00 +00003016
Richard Smithb2f0f052016-10-10 18:54:32 +00003017 // If we could find an overload, use it.
John McCall66a87592010-08-04 00:31:26 +00003018 if (Matches.size() == 1) {
Richard Smithb2f0f052016-10-10 18:54:32 +00003019 Operator = cast<CXXMethodDecl>(Matches[0].FD);
Alexis Hunt1f69a022011-05-12 22:46:29 +00003020
Richard Smithb2f0f052016-10-10 18:54:32 +00003021 // FIXME: DiagnoseUseOfDecl?
Alexis Hunt1f69a022011-05-12 22:46:29 +00003022 if (Operator->isDeleted()) {
3023 if (Diagnose) {
3024 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00003025 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00003026 }
3027 return true;
3028 }
3029
Richard Smith921bd202012-02-26 09:11:52 +00003030 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Richard Smithb2f0f052016-10-10 18:54:32 +00003031 Matches[0].Found, Diagnose) == AR_inaccessible)
Richard Smith921bd202012-02-26 09:11:52 +00003032 return true;
3033
John McCall66a87592010-08-04 00:31:26 +00003034 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00003035 }
John McCall66a87592010-08-04 00:31:26 +00003036
Richard Smithb2f0f052016-10-10 18:54:32 +00003037 // We found multiple suitable operators; complain about the ambiguity.
3038 // FIXME: The standard doesn't say to do this; it appears that the intent
3039 // is that this should never happen.
3040 if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00003041 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00003042 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
3043 << Name << RD;
Richard Smithb2f0f052016-10-10 18:54:32 +00003044 for (auto &Match : Matches)
3045 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
Alexis Huntf91729462011-05-12 22:46:25 +00003046 }
John McCall66a87592010-08-04 00:31:26 +00003047 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003048 }
3049
3050 // We did find operator delete/operator delete[] declarations, but
3051 // none of them were suitable.
3052 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00003053 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00003054 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
3055 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003056
Richard Smithb2f0f052016-10-10 18:54:32 +00003057 for (NamedDecl *D : Found)
3058 Diag(D->getUnderlyingDecl()->getLocation(),
Alexis Huntf91729462011-05-12 22:46:25 +00003059 diag::note_member_declared_here) << Name;
3060 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003061 return true;
3062 }
3063
Craig Topperc3ec1492014-05-26 06:22:03 +00003064 Operator = nullptr;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003065 return false;
3066}
3067
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003068namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003069/// Checks whether delete-expression, and new-expression used for
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003070/// initializing deletee have the same array form.
3071class MismatchingNewDeleteDetector {
3072public:
3073 enum MismatchResult {
3074 /// Indicates that there is no mismatch or a mismatch cannot be proven.
3075 NoMismatch,
3076 /// Indicates that variable is initialized with mismatching form of \a new.
3077 VarInitMismatches,
3078 /// Indicates that member is initialized with mismatching form of \a new.
3079 MemberInitMismatches,
3080 /// Indicates that 1 or more constructors' definitions could not been
3081 /// analyzed, and they will be checked again at the end of translation unit.
3082 AnalyzeLater
3083 };
3084
3085 /// \param EndOfTU True, if this is the final analysis at the end of
3086 /// translation unit. False, if this is the initial analysis at the point
3087 /// delete-expression was encountered.
3088 explicit MismatchingNewDeleteDetector(bool EndOfTU)
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00003089 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003090 HasUndefinedConstructors(false) {}
3091
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003092 /// Checks whether pointee of a delete-expression is initialized with
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003093 /// matching form of new-expression.
3094 ///
3095 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
3096 /// point where delete-expression is encountered, then a warning will be
3097 /// issued immediately. If return value is \c AnalyzeLater at the point where
3098 /// delete-expression is seen, then member will be analyzed at the end of
3099 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
3100 /// couldn't be analyzed. If at least one constructor initializes the member
3101 /// with matching type of new, the return value is \c NoMismatch.
3102 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003103 /// Analyzes a class member.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003104 /// \param Field Class member to analyze.
3105 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3106 /// for deleting the \p Field.
3107 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00003108 FieldDecl *Field;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003109 /// List of mismatching new-expressions used for initialization of the pointee
3110 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
3111 /// Indicates whether delete-expression was in array form.
3112 bool IsArrayForm;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003113
3114private:
3115 const bool EndOfTU;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003116 /// Indicates that there is at least one constructor without body.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003117 bool HasUndefinedConstructors;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003118 /// Returns \c CXXNewExpr from given initialization expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003119 /// \param E Expression used for initializing pointee in delete-expression.
NAKAMURA Takumi4bd67d82015-05-19 06:47:23 +00003120 /// E can be a single-element \c InitListExpr consisting of new-expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003121 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003122 /// Returns whether member is initialized with mismatching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003123 /// \c new either by the member initializer or in-class initialization.
3124 ///
3125 /// If bodies of all constructors are not visible at the end of translation
3126 /// unit or at least one constructor initializes member with the matching
3127 /// form of \c new, mismatch cannot be proven, and this function will return
3128 /// \c NoMismatch.
3129 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003130 /// Returns whether variable is initialized with mismatching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003131 /// \c new.
3132 ///
3133 /// If variable is initialized with matching form of \c new or variable is not
3134 /// initialized with a \c new expression, this function will return true.
3135 /// If variable is initialized with mismatching form of \c new, returns false.
3136 /// \param D Variable to analyze.
3137 bool hasMatchingVarInit(const DeclRefExpr *D);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003138 /// Checks whether the constructor initializes pointee with mismatching
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003139 /// form of \c new.
3140 ///
3141 /// Returns true, if member is initialized with matching form of \c new in
3142 /// member initializer list. Returns false, if member is initialized with the
3143 /// matching form of \c new in this constructor's initializer or given
3144 /// constructor isn't defined at the point where delete-expression is seen, or
3145 /// member isn't initialized by the constructor.
3146 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003147 /// Checks whether member is initialized with matching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003148 /// \c new in member initializer list.
3149 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3150 /// Checks whether member is initialized with mismatching form of \c new by
3151 /// in-class initializer.
3152 MismatchResult analyzeInClassInitializer();
3153};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003154}
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003155
3156MismatchingNewDeleteDetector::MismatchResult
3157MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3158 NewExprs.clear();
3159 assert(DE && "Expected delete-expression");
3160 IsArrayForm = DE->isArrayForm();
3161 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3162 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3163 return analyzeMemberExpr(ME);
3164 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3165 if (!hasMatchingVarInit(D))
3166 return VarInitMismatches;
3167 }
3168 return NoMismatch;
3169}
3170
3171const CXXNewExpr *
3172MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3173 assert(E != nullptr && "Expected a valid initializer expression");
3174 E = E->IgnoreParenImpCasts();
3175 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3176 if (ILE->getNumInits() == 1)
3177 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3178 }
3179
3180 return dyn_cast_or_null<const CXXNewExpr>(E);
3181}
3182
3183bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3184 const CXXCtorInitializer *CI) {
3185 const CXXNewExpr *NE = nullptr;
3186 if (Field == CI->getMember() &&
3187 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3188 if (NE->isArray() == IsArrayForm)
3189 return true;
3190 else
3191 NewExprs.push_back(NE);
3192 }
3193 return false;
3194}
3195
3196bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3197 const CXXConstructorDecl *CD) {
3198 if (CD->isImplicit())
3199 return false;
3200 const FunctionDecl *Definition = CD;
3201 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3202 HasUndefinedConstructors = true;
3203 return EndOfTU;
3204 }
3205 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3206 if (hasMatchingNewInCtorInit(CI))
3207 return true;
3208 }
3209 return false;
3210}
3211
3212MismatchingNewDeleteDetector::MismatchResult
3213MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3214 assert(Field != nullptr && "This should be called only for members");
Ismail Pazarbasi7ff18362015-10-26 19:20:24 +00003215 const Expr *InitExpr = Field->getInClassInitializer();
3216 if (!InitExpr)
3217 return EndOfTU ? NoMismatch : AnalyzeLater;
3218 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003219 if (NE->isArray() != IsArrayForm) {
3220 NewExprs.push_back(NE);
3221 return MemberInitMismatches;
3222 }
3223 }
3224 return NoMismatch;
3225}
3226
3227MismatchingNewDeleteDetector::MismatchResult
3228MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3229 bool DeleteWasArrayForm) {
3230 assert(Field != nullptr && "Analysis requires a valid class member.");
3231 this->Field = Field;
3232 IsArrayForm = DeleteWasArrayForm;
3233 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3234 for (const auto *CD : RD->ctors()) {
3235 if (hasMatchingNewInCtor(CD))
3236 return NoMismatch;
3237 }
3238 if (HasUndefinedConstructors)
3239 return EndOfTU ? NoMismatch : AnalyzeLater;
3240 if (!NewExprs.empty())
3241 return MemberInitMismatches;
3242 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3243 : NoMismatch;
3244}
3245
3246MismatchingNewDeleteDetector::MismatchResult
3247MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3248 assert(ME != nullptr && "Expected a member expression");
3249 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3250 return analyzeField(F, IsArrayForm);
3251 return NoMismatch;
3252}
3253
3254bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3255 const CXXNewExpr *NE = nullptr;
3256 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3257 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3258 NE->isArray() != IsArrayForm) {
3259 NewExprs.push_back(NE);
3260 }
3261 }
3262 return NewExprs.empty();
3263}
3264
3265static void
3266DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3267 const MismatchingNewDeleteDetector &Detector) {
3268 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3269 FixItHint H;
3270 if (!Detector.IsArrayForm)
3271 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3272 else {
3273 SourceLocation RSquare = Lexer::findLocationAfterToken(
3274 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3275 SemaRef.getLangOpts(), true);
3276 if (RSquare.isValid())
3277 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3278 }
3279 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3280 << Detector.IsArrayForm << H;
3281
3282 for (const auto *NE : Detector.NewExprs)
3283 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3284 << Detector.IsArrayForm;
3285}
3286
3287void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3288 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3289 return;
3290 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3291 switch (Detector.analyzeDeleteExpr(DE)) {
3292 case MismatchingNewDeleteDetector::VarInitMismatches:
3293 case MismatchingNewDeleteDetector::MemberInitMismatches: {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003294 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003295 break;
3296 }
3297 case MismatchingNewDeleteDetector::AnalyzeLater: {
3298 DeleteExprs[Detector.Field].push_back(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003299 std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003300 break;
3301 }
3302 case MismatchingNewDeleteDetector::NoMismatch:
3303 break;
3304 }
3305}
3306
3307void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3308 bool DeleteWasArrayForm) {
3309 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3310 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3311 case MismatchingNewDeleteDetector::VarInitMismatches:
3312 llvm_unreachable("This analysis should have been done for class members.");
3313 case MismatchingNewDeleteDetector::AnalyzeLater:
3314 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3315 "translation unit.");
3316 case MismatchingNewDeleteDetector::MemberInitMismatches:
3317 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3318 break;
3319 case MismatchingNewDeleteDetector::NoMismatch:
3320 break;
3321 }
3322}
3323
Sebastian Redlbd150f42008-11-21 19:14:01 +00003324/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3325/// @code ::delete ptr; @endcode
3326/// or
3327/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00003328ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00003329Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00003330 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003331 // C++ [expr.delete]p1:
3332 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00003333 // non-explicit conversion function to a pointer type. The result has type
3334 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003335 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00003336 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3337
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003338 ExprResult Ex = ExE;
Craig Topperc3ec1492014-05-26 06:22:03 +00003339 FunctionDecl *OperatorDelete = nullptr;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003340 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00003341 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00003342
John Wiegley01296292011-04-08 18:41:53 +00003343 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00003344 // Perform lvalue-to-rvalue cast, if needed.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003345 Ex = DefaultLvalueConversion(Ex.get());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00003346 if (Ex.isInvalid())
3347 return ExprError();
John McCallef429022012-03-09 04:08:29 +00003348
John Wiegley01296292011-04-08 18:41:53 +00003349 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003350
Richard Smithccc11812013-05-21 19:05:48 +00003351 class DeleteConverter : public ContextualImplicitConverter {
3352 public:
3353 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003354
Craig Toppere14c0f82014-03-12 04:55:44 +00003355 bool match(QualType ConvType) override {
Richard Smithccc11812013-05-21 19:05:48 +00003356 // FIXME: If we have an operator T* and an operator void*, we must pick
3357 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003358 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00003359 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00003360 return true;
3361 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003362 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003363
Richard Smithccc11812013-05-21 19:05:48 +00003364 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003365 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003366 return S.Diag(Loc, diag::err_delete_operand) << T;
3367 }
3368
3369 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003370 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003371 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3372 }
3373
3374 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003375 QualType T,
3376 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003377 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3378 }
3379
3380 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003381 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003382 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3383 << ConvTy;
3384 }
3385
3386 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003387 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003388 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3389 }
3390
3391 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003392 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003393 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3394 << ConvTy;
3395 }
3396
3397 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003398 QualType T,
3399 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003400 llvm_unreachable("conversion functions are permitted");
3401 }
3402 } Converter;
3403
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003404 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
Richard Smithccc11812013-05-21 19:05:48 +00003405 if (Ex.isInvalid())
3406 return ExprError();
3407 Type = Ex.get()->getType();
3408 if (!Converter.match(Type))
3409 // FIXME: PerformContextualImplicitConversion should return ExprError
3410 // itself in this case.
3411 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003412
Simon Pilgrime1485122019-10-17 11:12:31 +00003413 QualType Pointee = Type->castAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003414 QualType PointeeElem = Context.getBaseElementType(Pointee);
3415
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00003416 if (Pointee.getAddressSpace() != LangAS::Default &&
3417 !getLangOpts().OpenCLCPlusPlus)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003418 return Diag(Ex.get()->getBeginLoc(),
Eli Friedmanae4280f2011-07-26 22:25:31 +00003419 diag::err_address_space_qualified_delete)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003420 << Pointee.getUnqualifiedType()
3421 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003422
Craig Topperc3ec1492014-05-26 06:22:03 +00003423 CXXRecordDecl *PointeeRD = nullptr;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003424 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003425 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003426 // effectively bans deletion of "void*". However, most compilers support
3427 // this, so we treat it as a warning unless we're in a SFINAE context.
3428 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00003429 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003430 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003431 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00003432 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00003433 } else if (!Pointee->isDependentType()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003434 // FIXME: This can result in errors if the definition was imported from a
3435 // module but is hidden.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003436 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003437 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00003438 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3439 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3440 }
3441 }
3442
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003443 if (Pointee->isArrayType() && !ArrayForm) {
3444 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00003445 << Type << Ex.get()->getSourceRange()
Craig Topper07fa1762015-11-15 02:31:46 +00003446 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003447 ArrayForm = true;
3448 }
3449
Anders Carlssona471db02009-08-16 20:29:29 +00003450 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3451 ArrayForm ? OO_Array_Delete : OO_Delete);
3452
Eli Friedmanae4280f2011-07-26 22:25:31 +00003453 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003454 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00003455 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3456 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00003457 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003458
John McCall284c48f2011-01-27 09:37:56 +00003459 // If we're allocating an array of records, check whether the
3460 // usual operator delete[] has a size_t parameter.
3461 if (ArrayForm) {
3462 // If the user specifically asked to use the global allocator,
3463 // we'll need to do the lookup into the class.
3464 if (UseGlobal)
3465 UsualArrayDeleteWantsSize =
3466 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3467
3468 // Otherwise, the usual operator delete[] should be the
3469 // function we just found.
Richard Smithf03bd302013-12-05 08:30:59 +00003470 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
Richard Smithb2f0f052016-10-10 18:54:32 +00003471 UsualArrayDeleteWantsSize =
Richard Smithf75dcbe2016-10-11 00:21:10 +00003472 UsualDeallocFnInfo(*this,
3473 DeclAccessPair::make(OperatorDelete, AS_public))
3474 .HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00003475 }
3476
Richard Smitheec915d62012-02-18 04:13:32 +00003477 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00003478 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003479 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003480 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00003481 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3482 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003483 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00003484
Nico Weber5a9259c2016-01-15 21:45:31 +00003485 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3486 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3487 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3488 SourceLocation());
Anders Carlssona471db02009-08-16 20:29:29 +00003489 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003490
Richard Smithb2f0f052016-10-10 18:54:32 +00003491 if (!OperatorDelete) {
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00003492 if (getLangOpts().OpenCLCPlusPlus) {
3493 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3494 return ExprError();
3495 }
3496
Richard Smithb2f0f052016-10-10 18:54:32 +00003497 bool IsComplete = isCompleteType(StartLoc, Pointee);
3498 bool CanProvideSize =
3499 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3500 Pointee.isDestructedType());
3501 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3502
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003503 // Look for a global declaration.
Richard Smithb2f0f052016-10-10 18:54:32 +00003504 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3505 Overaligned, DeleteName);
3506 }
Mike Stump11289f42009-09-09 15:08:12 +00003507
Eli Friedmanfa0df832012-02-02 03:46:19 +00003508 MarkFunctionReferenced(StartLoc, OperatorDelete);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003509
Richard Smith5b349582017-10-13 01:55:36 +00003510 // Check access and ambiguity of destructor if we're going to call it.
3511 // Note that this is required even for a virtual delete.
3512 bool IsVirtualDelete = false;
Eli Friedmanae4280f2011-07-26 22:25:31 +00003513 if (PointeeRD) {
3514 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Richard Smith5b349582017-10-13 01:55:36 +00003515 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3516 PDiag(diag::err_access_dtor) << PointeeElem);
3517 IsVirtualDelete = Dtor->isVirtual();
Douglas Gregorfa778132011-02-01 15:50:11 +00003518 }
3519 }
Akira Hatanakacae83f72017-06-29 18:48:40 +00003520
Akira Hatanaka71645c22018-12-21 07:05:36 +00003521 DiagnoseUseOfDecl(OperatorDelete, StartLoc);
Richard Smith5b349582017-10-13 01:55:36 +00003522
3523 // Convert the operand to the type of the first parameter of operator
3524 // delete. This is only necessary if we selected a destroying operator
3525 // delete that we are going to call (non-virtually); converting to void*
3526 // is trivial and left to AST consumers to handle.
3527 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3528 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
Richard Smith25172012017-12-05 23:54:25 +00003529 Qualifiers Qs = Pointee.getQualifiers();
3530 if (Qs.hasCVRQualifiers()) {
3531 // Qualifiers are irrelevant to this conversion; we're only looking
3532 // for access and ambiguity.
3533 Qs.removeCVRQualifiers();
3534 QualType Unqual = Context.getPointerType(
3535 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3536 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3537 }
Richard Smith5b349582017-10-13 01:55:36 +00003538 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3539 if (Ex.isInvalid())
3540 return ExprError();
3541 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00003542 }
3543
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003544 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003545 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3546 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003547 AnalyzeDeleteExprMismatch(Result);
3548 return Result;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003549}
3550
Eric Fiselierfa752f22018-03-21 19:19:48 +00003551static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
3552 bool IsDelete,
3553 FunctionDecl *&Operator) {
3554
3555 DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
3556 IsDelete ? OO_Delete : OO_New);
3557
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003558 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
Eric Fiselierfa752f22018-03-21 19:19:48 +00003559 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
3560 assert(!R.empty() && "implicitly declared allocation functions not found");
3561 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3562
3563 // We do our own custom access checks below.
3564 R.suppressDiagnostics();
3565
3566 SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end());
3567 OverloadCandidateSet Candidates(R.getNameLoc(),
3568 OverloadCandidateSet::CSK_Normal);
3569 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3570 FnOvl != FnOvlEnd; ++FnOvl) {
3571 // Even member operator new/delete are implicitly treated as
3572 // static, so don't use AddMemberCandidate.
3573 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3574
3575 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3576 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3577 /*ExplicitTemplateArgs=*/nullptr, Args,
3578 Candidates,
3579 /*SuppressUserConversions=*/false);
3580 continue;
3581 }
3582
3583 FunctionDecl *Fn = cast<FunctionDecl>(D);
3584 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3585 /*SuppressUserConversions=*/false);
3586 }
3587
3588 SourceRange Range = TheCall->getSourceRange();
3589
3590 // Do the resolution.
3591 OverloadCandidateSet::iterator Best;
3592 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3593 case OR_Success: {
3594 // Got one!
3595 FunctionDecl *FnDecl = Best->Function;
3596 assert(R.getNamingClass() == nullptr &&
3597 "class members should not be considered");
3598
3599 if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3600 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3601 << (IsDelete ? 1 : 0) << Range;
3602 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3603 << R.getLookupName() << FnDecl->getSourceRange();
3604 return true;
3605 }
3606
3607 Operator = FnDecl;
3608 return false;
3609 }
3610
3611 case OR_No_Viable_Function:
David Blaikie5e328052019-05-03 00:44:50 +00003612 Candidates.NoteCandidates(
3613 PartialDiagnosticAt(R.getNameLoc(),
3614 S.PDiag(diag::err_ovl_no_viable_function_in_call)
3615 << R.getLookupName() << Range),
3616 S, OCD_AllCandidates, Args);
Eric Fiselierfa752f22018-03-21 19:19:48 +00003617 return true;
3618
3619 case OR_Ambiguous:
David Blaikie5e328052019-05-03 00:44:50 +00003620 Candidates.NoteCandidates(
3621 PartialDiagnosticAt(R.getNameLoc(),
3622 S.PDiag(diag::err_ovl_ambiguous_call)
3623 << R.getLookupName() << Range),
Richard Smith70f59b52019-10-23 17:54:10 -07003624 S, OCD_AmbiguousCandidates, Args);
Eric Fiselierfa752f22018-03-21 19:19:48 +00003625 return true;
3626
3627 case OR_Deleted: {
David Blaikie5e328052019-05-03 00:44:50 +00003628 Candidates.NoteCandidates(
3629 PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call)
3630 << R.getLookupName() << Range),
3631 S, OCD_AllCandidates, Args);
Eric Fiselierfa752f22018-03-21 19:19:48 +00003632 return true;
3633 }
3634 }
3635 llvm_unreachable("Unreachable, bad result from BestViableFunction");
3636}
3637
3638ExprResult
3639Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3640 bool IsDelete) {
3641 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3642 if (!getLangOpts().CPlusPlus) {
3643 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3644 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3645 << "C++";
3646 return ExprError();
3647 }
3648 // CodeGen assumes it can find the global new and delete to call,
3649 // so ensure that they are declared.
3650 DeclareGlobalNewDelete();
3651
3652 FunctionDecl *OperatorNewOrDelete = nullptr;
3653 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3654 OperatorNewOrDelete))
3655 return ExprError();
3656 assert(OperatorNewOrDelete && "should be found");
3657
Akira Hatanaka71645c22018-12-21 07:05:36 +00003658 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3659 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3660
Eric Fiselierfa752f22018-03-21 19:19:48 +00003661 TheCall->setType(OperatorNewOrDelete->getReturnType());
3662 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3663 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3664 InitializedEntity Entity =
3665 InitializedEntity::InitializeParameter(Context, ParamTy, false);
3666 ExprResult Arg = PerformCopyInitialization(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003667 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
Eric Fiselierfa752f22018-03-21 19:19:48 +00003668 if (Arg.isInvalid())
3669 return ExprError();
3670 TheCall->setArg(i, Arg.get());
3671 }
3672 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3673 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3674 "Callee expected to be implicit cast to a builtin function pointer");
3675 Callee->setType(OperatorNewOrDelete->getType());
3676
3677 return TheCallResult;
3678}
3679
Nico Weber5a9259c2016-01-15 21:45:31 +00003680void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3681 bool IsDelete, bool CallCanBeVirtual,
3682 bool WarnOnNonAbstractTypes,
3683 SourceLocation DtorLoc) {
Nico Weber955bb842017-08-30 20:25:22 +00003684 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
Nico Weber5a9259c2016-01-15 21:45:31 +00003685 return;
3686
3687 // C++ [expr.delete]p3:
3688 // In the first alternative (delete object), if the static type of the
3689 // object to be deleted is different from its dynamic type, the static
3690 // type shall be a base class of the dynamic type of the object to be
3691 // deleted and the static type shall have a virtual destructor or the
3692 // behavior is undefined.
3693 //
3694 const CXXRecordDecl *PointeeRD = dtor->getParent();
3695 // Note: a final class cannot be derived from, no issue there
3696 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3697 return;
3698
Nico Weberbf2260c2017-08-31 06:17:08 +00003699 // If the superclass is in a system header, there's nothing that can be done.
3700 // The `delete` (where we emit the warning) can be in a system header,
3701 // what matters for this warning is where the deleted type is defined.
3702 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3703 return;
3704
Brian Gesiak5488ab42019-01-11 01:54:53 +00003705 QualType ClassType = dtor->getThisType()->getPointeeType();
Nico Weber5a9259c2016-01-15 21:45:31 +00003706 if (PointeeRD->isAbstract()) {
3707 // If the class is abstract, we warn by default, because we're
3708 // sure the code has undefined behavior.
3709 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3710 << ClassType;
3711 } else if (WarnOnNonAbstractTypes) {
3712 // Otherwise, if this is not an array delete, it's a bit suspect,
3713 // but not necessarily wrong.
3714 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3715 << ClassType;
3716 }
3717 if (!IsDelete) {
3718 std::string TypeStr;
3719 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3720 Diag(DtorLoc, diag::note_delete_non_virtual)
3721 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3722 }
3723}
3724
Richard Smith03a4aa32016-06-23 19:02:52 +00003725Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3726 SourceLocation StmtLoc,
3727 ConditionKind CK) {
3728 ExprResult E =
3729 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3730 if (E.isInvalid())
3731 return ConditionError();
Richard Smithb130fe72016-06-23 19:16:49 +00003732 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3733 CK == ConditionKind::ConstexprIf);
Richard Smith03a4aa32016-06-23 19:02:52 +00003734}
3735
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003736/// Check the use of the given variable as a C++ condition in an if,
Douglas Gregor633caca2009-11-23 23:44:04 +00003737/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00003738ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00003739 SourceLocation StmtLoc,
Richard Smith03a4aa32016-06-23 19:02:52 +00003740 ConditionKind CK) {
Richard Smith27d807c2013-04-30 13:56:41 +00003741 if (ConditionVar->isInvalidDecl())
3742 return ExprError();
3743
Douglas Gregor633caca2009-11-23 23:44:04 +00003744 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003745
Douglas Gregor633caca2009-11-23 23:44:04 +00003746 // C++ [stmt.select]p2:
3747 // The declarator shall not specify a function or an array.
3748 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003749 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003750 diag::err_invalid_use_of_function_type)
3751 << ConditionVar->getSourceRange());
3752 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003753 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003754 diag::err_invalid_use_of_array_type)
3755 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00003756
Richard Smith7dcd7332019-06-04 18:30:46 +00003757 ExprResult Condition = BuildDeclRefExpr(
3758 ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
3759 ConditionVar->getLocation());
Eli Friedman2dfa7932012-01-16 21:00:51 +00003760
Richard Smith03a4aa32016-06-23 19:02:52 +00003761 switch (CK) {
3762 case ConditionKind::Boolean:
3763 return CheckBooleanCondition(StmtLoc, Condition.get());
3764
Richard Smithb130fe72016-06-23 19:16:49 +00003765 case ConditionKind::ConstexprIf:
3766 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3767
Richard Smith03a4aa32016-06-23 19:02:52 +00003768 case ConditionKind::Switch:
3769 return CheckSwitchCondition(StmtLoc, Condition.get());
John Wiegley01296292011-04-08 18:41:53 +00003770 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003771
Richard Smith03a4aa32016-06-23 19:02:52 +00003772 llvm_unreachable("unexpected condition kind");
Douglas Gregor633caca2009-11-23 23:44:04 +00003773}
3774
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003775/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
Richard Smithb130fe72016-06-23 19:16:49 +00003776ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003777 // C++ 6.4p4:
3778 // The value of a condition that is an initialized declaration in a statement
3779 // other than a switch statement is the value of the declared variable
3780 // implicitly converted to type bool. If that conversion is ill-formed, the
3781 // program is ill-formed.
3782 // The value of a condition that is an expression is the value of the
3783 // expression, implicitly converted to bool.
3784 //
Richard Smithb130fe72016-06-23 19:16:49 +00003785 // FIXME: Return this value to the caller so they don't need to recompute it.
3786 llvm::APSInt Value(/*BitWidth*/1);
3787 return (IsConstexpr && !CondExpr->isValueDependent())
3788 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3789 CCEK_ConstexprIf)
3790 : PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003791}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003792
3793/// Helper function to determine whether this is the (deprecated) C++
3794/// conversion from a string literal to a pointer to non-const char or
3795/// non-const wchar_t (for narrow and wide string literals,
3796/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00003797bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003798Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3799 // Look inside the implicit cast, if it exists.
3800 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3801 From = Cast->getSubExpr();
3802
3803 // A string literal (2.13.4) that is not a wide string literal can
3804 // be converted to an rvalue of type "pointer to char"; a wide
3805 // string literal can be converted to an rvalue of type "pointer
3806 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00003807 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003808 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00003809 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00003810 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003811 // This conversion is considered only when there is an
3812 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00003813 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3814 switch (StrLit->getKind()) {
3815 case StringLiteral::UTF8:
3816 case StringLiteral::UTF16:
3817 case StringLiteral::UTF32:
3818 // We don't allow UTF literals to be implicitly converted
3819 break;
3820 case StringLiteral::Ascii:
3821 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3822 ToPointeeType->getKind() == BuiltinType::Char_S);
3823 case StringLiteral::Wide:
Dmitry Polukhin9d64f722016-04-14 09:52:06 +00003824 return Context.typesAreCompatible(Context.getWideCharType(),
3825 QualType(ToPointeeType, 0));
Douglas Gregorfb65e592011-07-27 05:40:30 +00003826 }
3827 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003828 }
3829
3830 return false;
3831}
Douglas Gregor39c16d42008-10-24 04:54:22 +00003832
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003833static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00003834 SourceLocation CastLoc,
3835 QualType Ty,
3836 CastKind Kind,
3837 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00003838 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003839 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00003840 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00003841 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003842 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00003843 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00003844 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00003845 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003846
Richard Smith72d74052013-07-20 19:41:36 +00003847 if (S.RequireNonAbstractType(CastLoc, Ty,
3848 diag::err_allocation_of_abstract_type))
3849 return ExprError();
3850
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003851 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003852 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003853
Richard Smith5179eb72016-06-28 19:03:57 +00003854 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3855 InitializedEntity::InitializeTemporary(Ty));
Richard Smith7c9442a2015-02-24 21:44:43 +00003856 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003857 return ExprError();
Richard Smithd59b8322012-12-19 01:39:02 +00003858
Richard Smithf8adcdc2014-07-17 05:12:35 +00003859 ExprResult Result = S.BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003860 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003861 ConstructorArgs, HadMultipleCandidates,
3862 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3863 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00003864 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003865 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003866
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003867 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00003868 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003869
John McCalle3027922010-08-25 11:45:40 +00003870 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00003871 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003872
Richard Smithd3f2d322015-02-24 21:16:19 +00003873 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
Richard Smith7c9442a2015-02-24 21:44:43 +00003874 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003875 return ExprError();
3876
Douglas Gregora4253922010-04-16 22:17:36 +00003877 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00003878 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3879 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003880 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00003881 if (Result.isInvalid())
3882 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00003883 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003884 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3885 CK_UserDefinedConversion, Result.get(),
3886 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003887
Douglas Gregor668443e2011-01-20 00:18:04 +00003888 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00003889 }
3890 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003891}
Douglas Gregora4253922010-04-16 22:17:36 +00003892
Douglas Gregor5fb53972009-01-14 15:45:31 +00003893/// PerformImplicitConversion - Perform an implicit conversion of the
3894/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00003895/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003896/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003897/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00003898ExprResult
3899Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003900 const ImplicitConversionSequence &ICS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003901 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003902 CheckedConversionKind CCK) {
Richard Smith1ef75542018-06-27 20:30:34 +00003903 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
3904 if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType())
3905 return From;
3906
John McCall0d1da222010-01-12 00:44:57 +00003907 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00003908 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003909 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3910 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00003911 if (Res.isInvalid())
3912 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003913 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003914 break;
John Wiegley01296292011-04-08 18:41:53 +00003915 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003916
Anders Carlsson110b07b2009-09-15 06:28:28 +00003917 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003918
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00003919 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00003920 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00003921 QualType BeforeToType;
Richard Smithd3f2d322015-02-24 21:16:19 +00003922 assert(FD && "no conversion function for user-defined conversion seq");
Anders Carlsson110b07b2009-09-15 06:28:28 +00003923 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00003924 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003925
Anders Carlsson110b07b2009-09-15 06:28:28 +00003926 // If the user-defined conversion is specified by a conversion function,
3927 // the initial standard conversion sequence converts the source type to
3928 // the implicit object parameter of the conversion function.
3929 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00003930 } else {
3931 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00003932 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003933 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00003934 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003935 // If the user-defined conversion is specified by a constructor, the
Nico Weberb58e51c2014-11-19 05:21:39 +00003936 // initial standard conversion sequence converts the source type to
3937 // the type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00003938 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3939 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003940 }
Richard Smith72d74052013-07-20 19:41:36 +00003941 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00003942 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00003943 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00003944 PerformImplicitConversion(From, BeforeToType,
3945 ICS.UserDefined.Before, AA_Converting,
3946 CCK);
John Wiegley01296292011-04-08 18:41:53 +00003947 if (Res.isInvalid())
3948 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003949 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00003950 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003951
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003952 ExprResult CastArg = BuildCXXCastArgument(
3953 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
3954 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
3955 ICS.UserDefined.HadMultipleCandidates, From);
Anders Carlssone9766d52009-09-09 21:33:21 +00003956
3957 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00003958 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003959
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003960 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003961
Richard Smith1ef75542018-06-27 20:30:34 +00003962 // C++ [over.match.oper]p7:
3963 // [...] the second standard conversion sequence of a user-defined
3964 // conversion sequence is not applied.
3965 if (CCK == CCK_ForBuiltinOverloadedOp)
3966 return From;
3967
Richard Smith507840d2011-11-29 22:48:16 +00003968 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3969 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00003970 }
John McCall0d1da222010-01-12 00:44:57 +00003971
3972 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00003973 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00003974 PDiag(diag::err_typecheck_ambiguous_condition)
3975 << From->getSourceRange());
Richard Smith13fa4e22020-01-19 18:14:18 -08003976 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003977
Douglas Gregor39c16d42008-10-24 04:54:22 +00003978 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003979 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003980
3981 case ImplicitConversionSequence::BadConversion:
Anastasia Stulovafa755d32020-02-25 14:49:59 +00003982 Sema::AssignConvertType ConvTy =
3983 CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType());
3984 bool Diagnosed = DiagnoseAssignmentResult(
3985 ConvTy == Compatible ? Incompatible : ConvTy, From->getExprLoc(),
3986 ToType, From->getType(), From, Action);
Richard Smithe15a3702016-10-06 23:12:58 +00003987 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
John Wiegley01296292011-04-08 18:41:53 +00003988 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003989 }
3990
3991 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003992 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003993}
3994
Richard Smith507840d2011-11-29 22:48:16 +00003995/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00003996/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00003997/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00003998/// expression. Flavor is the context in which we're performing this
3999/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00004000ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00004001Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00004002 const StandardConversionSequence& SCS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004003 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00004004 CheckedConversionKind CCK) {
4005 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
Simon Pilgrim75c26882016-09-30 14:25:09 +00004006
Mike Stump87c57ac2009-05-16 07:39:55 +00004007 // Overall FIXME: we are recomputing too many types here and doing far too
4008 // much extra work. What this means is that we need to keep track of more
4009 // information that is computed when we try the implicit conversion initially,
4010 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00004011 QualType FromType = From->getType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00004012
Douglas Gregor2fe98832008-11-03 19:09:14 +00004013 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00004014 // FIXME: When can ToType be a reference type?
4015 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00004016 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00004017 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00004018 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004019 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00004020 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00004021 return ExprError();
Richard Smithf8adcdc2014-07-17 05:12:35 +00004022 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00004023 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4024 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00004025 ConstructorArgs, /*HadMultipleCandidates*/ false,
4026 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4027 CXXConstructExpr::CK_Complete, SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00004028 }
Richard Smithf8adcdc2014-07-17 05:12:35 +00004029 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00004030 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4031 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00004032 From, /*HadMultipleCandidates*/ false,
4033 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4034 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00004035 }
4036
Douglas Gregor980fb162010-04-29 18:24:40 +00004037 // Resolve overloaded function references.
4038 if (Context.hasSameType(FromType, Context.OverloadTy)) {
4039 DeclAccessPair Found;
4040 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
4041 true, Found);
4042 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00004043 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00004044
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004045 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
John Wiegley01296292011-04-08 18:41:53 +00004046 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004047
Douglas Gregor980fb162010-04-29 18:24:40 +00004048 From = FixOverloadedFunctionReference(From, Found, Fn);
4049 FromType = From->getType();
4050 }
4051
Richard Smitha23ab512013-05-23 00:30:41 +00004052 // If we're converting to an atomic type, first convert to the corresponding
4053 // non-atomic type.
4054 QualType ToAtomicType;
4055 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
4056 ToAtomicType = ToType;
4057 ToType = ToAtomic->getValueType();
4058 }
4059
George Burgess IV8d141e02015-12-14 22:00:49 +00004060 QualType InitialFromType = FromType;
Richard Smith507840d2011-11-29 22:48:16 +00004061 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00004062 switch (SCS.First) {
4063 case ICK_Identity:
David Majnemer3087a2b2014-12-28 21:47:31 +00004064 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
4065 FromType = FromAtomic->getValueType().getUnqualifiedType();
4066 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
4067 From, /*BasePath=*/nullptr, VK_RValue);
4068 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00004069 break;
4070
Eli Friedman946b7b52012-01-24 22:51:26 +00004071 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00004072 assert(From->getObjectKind() != OK_ObjCProperty);
Eli Friedman946b7b52012-01-24 22:51:26 +00004073 ExprResult FromRes = DefaultLvalueConversion(From);
4074 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004075 From = FromRes.get();
David Majnemere7029bc2014-12-16 06:31:17 +00004076 FromType = From->getType();
John McCall34376a62010-12-04 03:47:34 +00004077 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00004078 }
John McCall34376a62010-12-04 03:47:34 +00004079
Douglas Gregor39c16d42008-10-24 04:54:22 +00004080 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00004081 FromType = Context.getArrayDecayedType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00004082 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004083 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00004084 break;
4085
4086 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00004087 FromType = Context.getPointerType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00004088 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004089 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004090 break;
4091
4092 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004093 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004094 }
4095
Richard Smith507840d2011-11-29 22:48:16 +00004096 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00004097 switch (SCS.Second) {
4098 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00004099 // C++ [except.spec]p5:
4100 // [For] assignment to and initialization of pointers to functions,
4101 // pointers to member functions, and references to functions: the
4102 // target entity shall allow at least the exceptions allowed by the
4103 // source value in the assignment or initialization.
4104 switch (Action) {
4105 case AA_Assigning:
4106 case AA_Initializing:
4107 // Note, function argument passing and returning are initialization.
4108 case AA_Passing:
4109 case AA_Returning:
4110 case AA_Sending:
4111 case AA_Passing_CFAudited:
4112 if (CheckExceptionSpecCompatibility(From, ToType))
4113 return ExprError();
4114 break;
4115
4116 case AA_Casting:
4117 case AA_Converting:
4118 // Casts and implicit conversions are not initialization, so are not
4119 // checked for exception specification mismatches.
4120 break;
4121 }
Sebastian Redl5d431642009-10-10 12:04:10 +00004122 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00004123 break;
4124
4125 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00004126 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00004127 if (ToType->isBooleanType()) {
4128 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4129 SCS.Second == ICK_Integral_Promotion &&
4130 "only enums with fixed underlying type can promote to bool");
4131 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004132 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00004133 } else {
4134 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004135 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00004136 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004137 break;
4138
4139 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00004140 case ICK_Floating_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004141 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004142 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004143 break;
4144
4145 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00004146 case ICK_Complex_Conversion: {
Simon Pilgrime1485122019-10-17 11:12:31 +00004147 QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();
4148 QualType ToEl = ToType->castAs<ComplexType>()->getElementType();
John McCall8cb679e2010-11-15 09:13:47 +00004149 CastKind CK;
4150 if (FromEl->isRealFloatingType()) {
4151 if (ToEl->isRealFloatingType())
4152 CK = CK_FloatingComplexCast;
4153 else
4154 CK = CK_FloatingComplexToIntegralComplex;
4155 } else if (ToEl->isRealFloatingType()) {
4156 CK = CK_IntegralComplexToFloatingComplex;
4157 } else {
4158 CK = CK_IntegralComplexCast;
4159 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004160 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004161 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004162 break;
John McCall8cb679e2010-11-15 09:13:47 +00004163 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004164
Douglas Gregor39c16d42008-10-24 04:54:22 +00004165 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00004166 if (ToType->isRealFloatingType())
Simon Pilgrim75c26882016-09-30 14:25:09 +00004167 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004168 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004169 else
Simon Pilgrim75c26882016-09-30 14:25:09 +00004170 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004171 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004172 break;
4173
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00004174 case ICK_Compatible_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004175 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004176 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004177 break;
4178
John McCall31168b02011-06-15 23:02:42 +00004179 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004180 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004181 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00004182 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00004183 if (Action == AA_Initializing || Action == AA_Assigning)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004184 Diag(From->getBeginLoc(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004185 diag::ext_typecheck_convert_incompatible_pointer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004186 << ToType << From->getType() << Action << From->getSourceRange()
4187 << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004188 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004189 Diag(From->getBeginLoc(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004190 diag::ext_typecheck_convert_incompatible_pointer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004191 << From->getType() << ToType << Action << From->getSourceRange()
4192 << 0;
John McCall31168b02011-06-15 23:02:42 +00004193
Douglas Gregor33823722011-06-11 01:09:30 +00004194 if (From->getType()->isObjCObjectPointerType() &&
4195 ToType->isObjCObjectPointerType())
4196 EmitRelatedResultTypeNote(From);
Brian Kelley11352a82017-03-29 18:09:02 +00004197 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4198 !CheckObjCARCUnavailableWeakConversion(ToType,
4199 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00004200 if (Action == AA_Initializing)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004201 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
John McCall9c3467e2011-09-09 06:12:06 +00004202 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004203 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4204 << (Action == AA_Casting) << From->getType() << ToType
4205 << From->getSourceRange();
John McCall9c3467e2011-09-09 06:12:06 +00004206 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004207
Sven van Haastregt62364962019-12-02 14:20:15 +00004208 // Defer address space conversion to the third conversion.
4209 QualType FromPteeType = From->getType()->getPointeeType();
4210 QualType ToPteeType = ToType->getPointeeType();
4211 QualType NewToType = ToType;
4212 if (!FromPteeType.isNull() && !ToPteeType.isNull() &&
4213 FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {
4214 NewToType = Context.removeAddrSpaceQualType(ToPteeType);
4215 NewToType = Context.getAddrSpaceQualType(NewToType,
4216 FromPteeType.getAddressSpace());
4217 if (ToType->isObjCObjectPointerType())
4218 NewToType = Context.getObjCObjectPointerType(NewToType);
4219 else if (ToType->isBlockPointerType())
4220 NewToType = Context.getBlockPointerType(NewToType);
4221 else
4222 NewToType = Context.getPointerType(NewToType);
4223 }
4224
Richard Smith354abec2017-12-08 23:29:59 +00004225 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00004226 CXXCastPath BasePath;
Sven van Haastregt62364962019-12-02 14:20:15 +00004227 if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004228 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00004229
4230 // Make sure we extend blocks if necessary.
4231 // FIXME: doing this here is really ugly.
4232 if (Kind == CK_BlockPointerToObjCPointerCast) {
4233 ExprResult E = From;
4234 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004235 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00004236 }
Brian Kelley11352a82017-03-29 18:09:02 +00004237 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
Sven van Haastregt62364962019-12-02 14:20:15 +00004238 CheckObjCConversion(SourceRange(), NewToType, From, CCK);
4239 From = ImpCastExprToType(From, NewToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004240 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004241 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004242 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004243
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004244 case ICK_Pointer_Member: {
Richard Smith354abec2017-12-08 23:29:59 +00004245 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00004246 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00004247 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004248 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00004249 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00004250 return ExprError();
David Majnemerd96b9972014-08-08 00:10:39 +00004251
4252 // We may not have been able to figure out what this member pointer resolved
4253 // to up until this exact point. Attempt to lock-in it's inheritance model.
David Majnemerfc22e472015-06-12 17:55:44 +00004254 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00004255 (void)isCompleteType(From->getExprLoc(), From->getType());
4256 (void)isCompleteType(From->getExprLoc(), ToType);
David Majnemerfc22e472015-06-12 17:55:44 +00004257 }
David Majnemerd96b9972014-08-08 00:10:39 +00004258
Richard Smith507840d2011-11-29 22:48:16 +00004259 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004260 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004261 break;
4262 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004263
Abramo Bagnara7ccce982011-04-07 09:26:19 +00004264 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004265 // Perform half-to-boolean conversion via float.
4266 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004267 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004268 FromType = Context.FloatTy;
4269 }
4270
Richard Smith507840d2011-11-29 22:48:16 +00004271 From = ImpCastExprToType(From, Context.BoolTy,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004272 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004273 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004274 break;
4275
Douglas Gregor88d292c2010-05-13 16:44:06 +00004276 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00004277 CXXCastPath BasePath;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004278 if (CheckDerivedToBaseConversion(
4279 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4280 From->getSourceRange(), &BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004281 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004282
Richard Smith507840d2011-11-29 22:48:16 +00004283 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4284 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004285 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00004286 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00004287 }
4288
Douglas Gregor46188682010-05-18 22:42:18 +00004289 case ICK_Vector_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004290 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004291 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00004292 break;
4293
George Burgess IVdf1ed002016-01-13 01:52:39 +00004294 case ICK_Vector_Splat: {
Fariborz Jahanian28d94b12015-03-05 23:06:09 +00004295 // Vector splat from any arithmetic type to a vector.
George Burgess IVdf1ed002016-01-13 01:52:39 +00004296 Expr *Elem = prepareVectorSplat(ToType, From).get();
4297 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
4298 /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00004299 break;
George Burgess IVdf1ed002016-01-13 01:52:39 +00004300 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004301
Douglas Gregor46188682010-05-18 22:42:18 +00004302 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00004303 // Case 1. x -> _Complex y
4304 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4305 QualType ElType = ToComplex->getElementType();
4306 bool isFloatingComplex = ElType->isRealFloatingType();
4307
4308 // x -> y
4309 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4310 // do nothing
4311 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00004312 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004313 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00004314 } else {
4315 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00004316 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004317 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00004318 }
4319 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00004320 From = ImpCastExprToType(From, ToType,
4321 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004322 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00004323
4324 // Case 2. _Complex x -> y
4325 } else {
4326 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
4327 assert(FromComplex);
4328
4329 QualType ElType = FromComplex->getElementType();
4330 bool isFloatingComplex = ElType->isRealFloatingType();
4331
4332 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00004333 From = ImpCastExprToType(From, ElType,
4334 isFloatingComplex ? CK_FloatingComplexToReal
Simon Pilgrim75c26882016-09-30 14:25:09 +00004335 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004336 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004337
4338 // x -> y
4339 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4340 // do nothing
4341 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00004342 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004343 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004344 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004345 } else {
4346 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00004347 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004348 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004349 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004350 }
4351 }
Douglas Gregor46188682010-05-18 22:42:18 +00004352 break;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004353
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00004354 case ICK_Block_Pointer_Conversion: {
Marco Antogninid36e1302019-07-09 15:04:27 +00004355 LangAS AddrSpaceL =
Marco Antognini9eb95902019-07-17 08:52:09 +00004356 ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
Marco Antogninid36e1302019-07-09 15:04:27 +00004357 LangAS AddrSpaceR =
Marco Antognini9eb95902019-07-17 08:52:09 +00004358 FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4359 assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&
4360 "Invalid cast");
Marco Antogninid36e1302019-07-09 15:04:27 +00004361 CastKind Kind =
4362 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
4363 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004364 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00004365 break;
4366 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004367
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004368 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004369 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004370 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004371 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4372 if (FromRes.isInvalid())
4373 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004374 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004375 assert ((ConvTy == Sema::Compatible) &&
4376 "Improper transparent union conversion");
4377 (void)ConvTy;
4378 break;
4379 }
4380
Guy Benyei259f9f42013-02-07 16:05:33 +00004381 case ICK_Zero_Event_Conversion:
Egor Churaev89831422016-12-23 14:55:49 +00004382 case ICK_Zero_Queue_Conversion:
4383 From = ImpCastExprToType(From, ToType,
Andrew Savonichevb555b762018-10-23 15:19:20 +00004384 CK_ZeroToOCLOpaqueType,
Egor Churaev89831422016-12-23 14:55:49 +00004385 From->getValueKind()).get();
4386 break;
4387
Douglas Gregor46188682010-05-18 22:42:18 +00004388 case ICK_Lvalue_To_Rvalue:
4389 case ICK_Array_To_Pointer:
4390 case ICK_Function_To_Pointer:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004391 case ICK_Function_Conversion:
Douglas Gregor46188682010-05-18 22:42:18 +00004392 case ICK_Qualification:
4393 case ICK_Num_Conversion_Kinds:
George Burgess IV78ed9b42015-10-11 20:37:14 +00004394 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00004395 case ICK_Incompatible_Pointer_Conversion:
David Blaikie83d382b2011-09-23 05:06:16 +00004396 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004397 }
4398
4399 switch (SCS.Third) {
4400 case ICK_Identity:
4401 // Nothing to do.
4402 break;
4403
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004404 case ICK_Function_Conversion:
4405 // If both sides are functions (or pointers/references to them), there could
4406 // be incompatible exception declarations.
4407 if (CheckExceptionSpecCompatibility(From, ToType))
4408 return ExprError();
4409
4410 From = ImpCastExprToType(From, ToType, CK_NoOp,
4411 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4412 break;
4413
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004414 case ICK_Qualification: {
4415 // The qualification keeps the category of the inner expression, unless the
4416 // target type isn't a reference.
Anastasia Stulova04307942018-11-16 16:22:56 +00004417 ExprValueKind VK =
4418 ToType->isReferenceType() ? From->getValueKind() : VK_RValue;
4419
4420 CastKind CK = CK_NoOp;
4421
4422 if (ToType->isReferenceType() &&
4423 ToType->getPointeeType().getAddressSpace() !=
4424 From->getType().getAddressSpace())
4425 CK = CK_AddressSpaceConversion;
4426
4427 if (ToType->isPointerType() &&
4428 ToType->getPointeeType().getAddressSpace() !=
4429 From->getType()->getPointeeType().getAddressSpace())
4430 CK = CK_AddressSpaceConversion;
4431
4432 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4433 /*BasePath=*/nullptr, CCK)
4434 .get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00004435
Douglas Gregore981bb02011-03-14 16:13:32 +00004436 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004437 !getLangOpts().WritableStrings) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004438 Diag(From->getBeginLoc(),
4439 getLangOpts().CPlusPlus11
4440 ? diag::ext_deprecated_string_literal_conversion
4441 : diag::warn_deprecated_string_literal_conversion)
4442 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004443 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00004444
Douglas Gregor39c16d42008-10-24 04:54:22 +00004445 break;
Richard Smitha23ab512013-05-23 00:30:41 +00004446 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004447
Douglas Gregor39c16d42008-10-24 04:54:22 +00004448 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004449 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004450 }
4451
Douglas Gregor298f43d2012-04-12 20:42:30 +00004452 // If this conversion sequence involved a scalar -> atomic conversion, perform
4453 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00004454 if (!ToAtomicType.isNull()) {
4455 assert(Context.hasSameType(
4456 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4457 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004458 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00004459 }
4460
Richard Smith13fa4e22020-01-19 18:14:18 -08004461 // Materialize a temporary if we're implicitly converting to a reference
4462 // type. This is not required by the C++ rules but is necessary to maintain
4463 // AST invariants.
4464 if (ToType->isReferenceType() && From->isRValue()) {
4465 ExprResult Res = TemporaryMaterializationConversion(From);
4466 if (Res.isInvalid())
4467 return ExprError();
4468 From = Res.get();
4469 }
4470
George Burgess IV8d141e02015-12-14 22:00:49 +00004471 // If this conversion sequence succeeded and involved implicitly converting a
4472 // _Nullable type to a _Nonnull one, complain.
Richard Smith1ef75542018-06-27 20:30:34 +00004473 if (!isCast(CCK))
George Burgess IV8d141e02015-12-14 22:00:49 +00004474 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004475 From->getBeginLoc());
George Burgess IV8d141e02015-12-14 22:00:49 +00004476
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004477 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00004478}
4479
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004480/// Check the completeness of a type in a unary type trait.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004481///
4482/// If the particular type trait requires a complete type, tries to complete
4483/// it. If completing the type fails, a diagnostic is emitted and false
4484/// returned. If completing the type succeeds or no completion was required,
4485/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00004486static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004487 SourceLocation Loc,
4488 QualType ArgTy) {
4489 // C++0x [meta.unary.prop]p3:
4490 // For all of the class templates X declared in this Clause, instantiating
4491 // that template with a template argument that is a class template
4492 // specialization may result in the implicit instantiation of the template
4493 // argument if and only if the semantics of X require that the argument
4494 // must be a complete type.
4495 // We apply this rule to all the type trait expressions used to implement
4496 // these class templates. We also try to follow any GCC documented behavior
4497 // in these expressions to ensure portability of standard libraries.
4498 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004499 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00004500 // is_complete_type somewhat obviously cannot require a complete type.
4501 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004502 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004503
4504 // These traits are modeled on the type predicates in C++0x
4505 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4506 // requiring a complete type, as whether or not they return true cannot be
4507 // impacted by the completeness of the type.
4508 case UTT_IsVoid:
4509 case UTT_IsIntegral:
4510 case UTT_IsFloatingPoint:
4511 case UTT_IsArray:
4512 case UTT_IsPointer:
4513 case UTT_IsLvalueReference:
4514 case UTT_IsRvalueReference:
4515 case UTT_IsMemberFunctionPointer:
4516 case UTT_IsMemberObjectPointer:
4517 case UTT_IsEnum:
4518 case UTT_IsUnion:
4519 case UTT_IsClass:
4520 case UTT_IsFunction:
4521 case UTT_IsReference:
4522 case UTT_IsArithmetic:
4523 case UTT_IsFundamental:
4524 case UTT_IsObject:
4525 case UTT_IsScalar:
4526 case UTT_IsCompound:
4527 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004528 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004529
4530 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4531 // which requires some of its traits to have the complete type. However,
4532 // the completeness of the type cannot impact these traits' semantics, and
4533 // so they don't require it. This matches the comments on these traits in
4534 // Table 49.
4535 case UTT_IsConst:
4536 case UTT_IsVolatile:
4537 case UTT_IsSigned:
4538 case UTT_IsUnsigned:
David Majnemer213bea32015-11-16 06:58:51 +00004539
4540 // This type trait always returns false, checking the type is moot.
4541 case UTT_IsInterfaceClass:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004542 return true;
4543
David Majnemer213bea32015-11-16 06:58:51 +00004544 // C++14 [meta.unary.prop]:
4545 // If T is a non-union class type, T shall be a complete type.
4546 case UTT_IsEmpty:
4547 case UTT_IsPolymorphic:
4548 case UTT_IsAbstract:
4549 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4550 if (!RD->isUnion())
4551 return !S.RequireCompleteType(
4552 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4553 return true;
4554
4555 // C++14 [meta.unary.prop]:
4556 // If T is a class type, T shall be a complete type.
4557 case UTT_IsFinal:
4558 case UTT_IsSealed:
4559 if (ArgTy->getAsCXXRecordDecl())
4560 return !S.RequireCompleteType(
4561 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4562 return true;
4563
Richard Smithf03e9082017-06-01 00:28:16 +00004564 // C++1z [meta.unary.prop]:
4565 // remove_all_extents_t<T> shall be a complete type or cv void.
Eric Fiselier07360662017-04-12 22:12:15 +00004566 case UTT_IsAggregate:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004567 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004568 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004569 case UTT_IsStandardLayout:
4570 case UTT_IsPOD:
4571 case UTT_IsLiteral:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004572 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4573 // or an array of unknown bound. But GCC actually imposes the same constraints
4574 // as above.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004575 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004576 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004577 case UTT_HasNothrowConstructor:
4578 case UTT_HasNothrowCopy:
4579 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004580 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00004581 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004582 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004583 case UTT_HasTrivialCopy:
4584 case UTT_HasTrivialDestructor:
4585 case UTT_HasVirtualDestructor:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004586 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4587 LLVM_FALLTHROUGH;
4588
4589 // C++1z [meta.unary.prop]:
4590 // T shall be a complete type, cv void, or an array of unknown bound.
4591 case UTT_IsDestructible:
4592 case UTT_IsNothrowDestructible:
4593 case UTT_IsTriviallyDestructible:
Erich Keanee63e9d72017-10-24 21:31:50 +00004594 case UTT_HasUniqueObjectRepresentations:
Richard Smithf03e9082017-06-01 00:28:16 +00004595 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
Chandler Carruth8e172c62011-05-01 06:51:22 +00004596 return true;
4597
4598 return !S.RequireCompleteType(
Richard Smithf03e9082017-06-01 00:28:16 +00004599 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00004600 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00004601}
4602
Joao Matosc9523d42013-03-27 01:34:16 +00004603static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4604 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004605 bool (CXXRecordDecl::*HasTrivial)() const,
4606 bool (CXXRecordDecl::*HasNonTrivial)() const,
Joao Matosc9523d42013-03-27 01:34:16 +00004607 bool (CXXMethodDecl::*IsDesiredOp)() const)
4608{
4609 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4610 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4611 return true;
4612
4613 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4614 DeclarationNameInfo NameInfo(Name, KeyLoc);
4615 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4616 if (Self.LookupQualifiedName(Res, RD)) {
4617 bool FoundOperator = false;
4618 Res.suppressDiagnostics();
4619 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4620 Op != OpEnd; ++Op) {
4621 if (isa<FunctionTemplateDecl>(*Op))
4622 continue;
4623
4624 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4625 if((Operator->*IsDesiredOp)()) {
4626 FoundOperator = true;
4627 const FunctionProtoType *CPT =
4628 Operator->getType()->getAs<FunctionProtoType>();
4629 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Richard Smitheaf11ad2018-05-03 03:58:32 +00004630 if (!CPT || !CPT->isNothrow())
Joao Matosc9523d42013-03-27 01:34:16 +00004631 return false;
4632 }
4633 }
4634 return FoundOperator;
4635 }
4636 return false;
4637}
4638
Alp Toker95e7ff22014-01-01 05:57:51 +00004639static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004640 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004641 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00004642
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004643 ASTContext &C = Self.Context;
4644 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004645 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004646 // Type trait expressions corresponding to the primary type category
4647 // predicates in C++0x [meta.unary.cat].
4648 case UTT_IsVoid:
4649 return T->isVoidType();
4650 case UTT_IsIntegral:
4651 return T->isIntegralType(C);
4652 case UTT_IsFloatingPoint:
4653 return T->isFloatingType();
4654 case UTT_IsArray:
4655 return T->isArrayType();
4656 case UTT_IsPointer:
4657 return T->isPointerType();
4658 case UTT_IsLvalueReference:
4659 return T->isLValueReferenceType();
4660 case UTT_IsRvalueReference:
4661 return T->isRValueReferenceType();
4662 case UTT_IsMemberFunctionPointer:
4663 return T->isMemberFunctionPointerType();
4664 case UTT_IsMemberObjectPointer:
4665 return T->isMemberDataPointerType();
4666 case UTT_IsEnum:
4667 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00004668 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00004669 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004670 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00004671 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004672 case UTT_IsFunction:
4673 return T->isFunctionType();
4674
4675 // Type trait expressions which correspond to the convenient composition
4676 // predicates in C++0x [meta.unary.comp].
4677 case UTT_IsReference:
4678 return T->isReferenceType();
4679 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00004680 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004681 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00004682 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004683 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00004684 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004685 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00004686 // Note: semantic analysis depends on Objective-C lifetime types to be
4687 // considered scalar types. However, such types do not actually behave
4688 // like scalar types at run time (since they may require retain/release
4689 // operations), so we report them as non-scalar.
4690 if (T->isObjCLifetimeType()) {
4691 switch (T.getObjCLifetime()) {
4692 case Qualifiers::OCL_None:
4693 case Qualifiers::OCL_ExplicitNone:
4694 return true;
4695
4696 case Qualifiers::OCL_Strong:
4697 case Qualifiers::OCL_Weak:
4698 case Qualifiers::OCL_Autoreleasing:
4699 return false;
4700 }
4701 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004702
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00004703 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004704 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00004705 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004706 case UTT_IsMemberPointer:
4707 return T->isMemberPointerType();
4708
4709 // Type trait expressions which correspond to the type property predicates
4710 // in C++0x [meta.unary.prop].
4711 case UTT_IsConst:
4712 return T.isConstQualified();
4713 case UTT_IsVolatile:
4714 return T.isVolatileQualified();
4715 case UTT_IsTrivial:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004716 return T.isTrivialType(C);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004717 case UTT_IsTriviallyCopyable:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004718 return T.isTriviallyCopyableType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004719 case UTT_IsStandardLayout:
4720 return T->isStandardLayoutType();
4721 case UTT_IsPOD:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004722 return T.isPODType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004723 case UTT_IsLiteral:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004724 return T->isLiteralType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004725 case UTT_IsEmpty:
4726 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4727 return !RD->isUnion() && RD->isEmpty();
4728 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004729 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004730 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004731 return !RD->isUnion() && RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004732 return false;
4733 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004734 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004735 return !RD->isUnion() && RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004736 return false;
Eric Fiselier07360662017-04-12 22:12:15 +00004737 case UTT_IsAggregate:
4738 // Report vector extensions and complex types as aggregates because they
4739 // support aggregate initialization. GCC mirrors this behavior for vectors
4740 // but not _Complex.
4741 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4742 T->isAnyComplexType();
David Majnemer213bea32015-11-16 06:58:51 +00004743 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4744 // even then only when it is used with the 'interface struct ...' syntax
4745 // Clang doesn't support /CLR which makes this type trait moot.
John McCallbf4a7d72012-09-25 07:32:49 +00004746 case UTT_IsInterfaceClass:
John McCallbf4a7d72012-09-25 07:32:49 +00004747 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00004748 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00004749 case UTT_IsSealed:
4750 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004751 return RD->hasAttr<FinalAttr>();
David Majnemera5433082013-10-18 00:33:31 +00004752 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00004753 case UTT_IsSigned:
Zoe Carver511dbd82019-09-23 15:41:20 +00004754 // Enum types should always return false.
4755 // Floating points should always return true.
4756 return !T->isEnumeralType() && (T->isFloatingType() || T->isSignedIntegerType());
John Wiegley65497cc2011-04-27 23:09:49 +00004757 case UTT_IsUnsigned:
4758 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004759
4760 // Type trait expressions which query classes regarding their construction,
4761 // destruction, and copying. Rather than being based directly on the
4762 // related type predicates in the standard, they are specified by both
4763 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4764 // specifications.
4765 //
4766 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4767 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00004768 //
4769 // Note that these builtins do not behave as documented in g++: if a class
4770 // has both a trivial and a non-trivial special member of a particular kind,
4771 // they return false! For now, we emulate this behavior.
4772 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4773 // does not correctly compute triviality in the presence of multiple special
4774 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00004775 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004776 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4777 // If __is_pod (type) is true then the trait is true, else if type is
4778 // a cv class or union type (or array thereof) with a trivial default
4779 // constructor ([class.ctor]) then the trait is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004780 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004781 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004782 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4783 return RD->hasTrivialDefaultConstructor() &&
4784 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004785 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004786 case UTT_HasTrivialMoveConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004787 // This trait is implemented by MSVC 2012 and needed to parse the
4788 // standard library headers. Specifically this is used as the logic
4789 // behind std::is_trivially_move_constructible (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004790 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004791 return true;
4792 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4793 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4794 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004795 case UTT_HasTrivialCopy:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004796 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4797 // If __is_pod (type) is true or type is a reference type then
4798 // the trait is true, else if type is a cv class or union type
4799 // with a trivial copy constructor ([class.copy]) then the trait
4800 // is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004801 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004802 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004803 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4804 return RD->hasTrivialCopyConstructor() &&
4805 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004806 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004807 case UTT_HasTrivialMoveAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004808 // This trait is implemented by MSVC 2012 and needed to parse the
4809 // standard library headers. Specifically it is used as the logic
4810 // behind std::is_trivially_move_assignable (20.9.4.3)
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004811 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004812 return true;
4813 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4814 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4815 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004816 case UTT_HasTrivialAssign:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004817 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4818 // If type is const qualified or is a reference type then the
4819 // trait is false. Otherwise if __is_pod (type) is true then the
4820 // trait is true, else if type is a cv class or union type with
4821 // a trivial copy assignment ([class.copy]) then the trait is
4822 // true, else it is false.
4823 // Note: the const and reference restrictions are interesting,
4824 // given that const and reference members don't prevent a class
4825 // from having a trivial copy assignment operator (but do cause
4826 // errors if the copy assignment operator is actually used, q.v.
4827 // [class.copy]p12).
4828
Richard Smith92f241f2012-12-08 02:53:02 +00004829 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004830 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004831 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004832 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004833 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4834 return RD->hasTrivialCopyAssignment() &&
4835 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004836 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004837 case UTT_IsDestructible:
Richard Smithf03e9082017-06-01 00:28:16 +00004838 case UTT_IsTriviallyDestructible:
Alp Toker73287bf2014-01-20 00:24:09 +00004839 case UTT_IsNothrowDestructible:
David Majnemerac73de92015-08-11 03:03:28 +00004840 // C++14 [meta.unary.prop]:
4841 // For reference types, is_destructible<T>::value is true.
4842 if (T->isReferenceType())
4843 return true;
4844
4845 // Objective-C++ ARC: autorelease types don't require destruction.
4846 if (T->isObjCLifetimeType() &&
4847 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4848 return true;
4849
4850 // C++14 [meta.unary.prop]:
4851 // For incomplete types and function types, is_destructible<T>::value is
4852 // false.
4853 if (T->isIncompleteType() || T->isFunctionType())
4854 return false;
4855
Richard Smithf03e9082017-06-01 00:28:16 +00004856 // A type that requires destruction (via a non-trivial destructor or ARC
4857 // lifetime semantics) is not trivially-destructible.
4858 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4859 return false;
4860
David Majnemerac73de92015-08-11 03:03:28 +00004861 // C++14 [meta.unary.prop]:
4862 // For object types and given U equal to remove_all_extents_t<T>, if the
4863 // expression std::declval<U&>().~U() is well-formed when treated as an
4864 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4865 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4866 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4867 if (!Destructor)
4868 return false;
4869 // C++14 [dcl.fct.def.delete]p2:
4870 // A program that refers to a deleted function implicitly or
4871 // explicitly, other than to declare it, is ill-formed.
4872 if (Destructor->isDeleted())
4873 return false;
4874 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4875 return false;
4876 if (UTT == UTT_IsNothrowDestructible) {
4877 const FunctionProtoType *CPT =
4878 Destructor->getType()->getAs<FunctionProtoType>();
4879 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Richard Smitheaf11ad2018-05-03 03:58:32 +00004880 if (!CPT || !CPT->isNothrow())
David Majnemerac73de92015-08-11 03:03:28 +00004881 return false;
4882 }
4883 }
4884 return true;
4885
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004886 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00004887 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004888 // If __is_pod (type) is true or type is a reference type
4889 // then the trait is true, else if type is a cv class or union
4890 // type (or array thereof) with a trivial destructor
4891 // ([class.dtor]) then the trait is true, else it is
4892 // false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004893 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004894 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004895
John McCall31168b02011-06-15 23:02:42 +00004896 // Objective-C++ ARC: autorelease types don't require destruction.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004897 if (T->isObjCLifetimeType() &&
John McCall31168b02011-06-15 23:02:42 +00004898 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4899 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004900
Richard Smith92f241f2012-12-08 02:53:02 +00004901 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4902 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004903 return false;
4904 // TODO: Propagate nothrowness for implicitly declared special members.
4905 case UTT_HasNothrowAssign:
4906 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4907 // If type is const qualified or is a reference type then the
4908 // trait is false. Otherwise if __has_trivial_assign (type)
4909 // is true then the trait is true, else if type is a cv class
4910 // or union type with copy assignment operators that are known
4911 // not to throw an exception then the trait is true, else it is
4912 // false.
4913 if (C.getBaseElementType(T).isConstQualified())
4914 return false;
4915 if (T->isReferenceType())
4916 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004917 if (T.isPODType(C) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00004918 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004919
Joao Matosc9523d42013-03-27 01:34:16 +00004920 if (const RecordType *RT = T->getAs<RecordType>())
4921 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4922 &CXXRecordDecl::hasTrivialCopyAssignment,
4923 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4924 &CXXMethodDecl::isCopyAssignmentOperator);
4925 return false;
4926 case UTT_HasNothrowMoveAssign:
4927 // This trait is implemented by MSVC 2012 and needed to parse the
4928 // standard library headers. Specifically this is used as the logic
4929 // behind std::is_nothrow_move_assignable (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004930 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004931 return true;
4932
4933 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4934 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4935 &CXXRecordDecl::hasTrivialMoveAssignment,
4936 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4937 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004938 return false;
4939 case UTT_HasNothrowCopy:
4940 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4941 // If __has_trivial_copy (type) is true then the trait is true, else
4942 // if type is a cv class or union type with copy constructors that are
4943 // known not to throw an exception then the trait is true, else it is
4944 // false.
John McCall31168b02011-06-15 23:02:42 +00004945 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004946 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004947 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4948 if (RD->hasTrivialCopyConstructor() &&
4949 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004950 return true;
4951
4952 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004953 unsigned FoundTQs;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004954 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004955 // A template constructor is never a copy constructor.
4956 // FIXME: However, it may actually be selected at the actual overload
4957 // resolution point.
Hal Finkelfec83452016-11-27 16:26:14 +00004958 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004959 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004960 // UsingDecl itself is not a constructor
4961 if (isa<UsingDecl>(ND))
4962 continue;
4963 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004964 if (Constructor->isCopyConstructor(FoundTQs)) {
4965 FoundConstructor = true;
4966 const FunctionProtoType *CPT
4967 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004968 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4969 if (!CPT)
4970 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004971 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004972 // For now, we'll be conservative and assume that they can throw.
Richard Smitheaf11ad2018-05-03 03:58:32 +00004973 if (!CPT->isNothrow() || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00004974 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004975 }
4976 }
4977
Richard Smith938f40b2011-06-11 17:19:42 +00004978 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004979 }
4980 return false;
4981 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00004982 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004983 // If __has_trivial_constructor (type) is true then the trait is
4984 // true, else if type is a cv class or union type (or array
4985 // thereof) with a default constructor that is known not to
4986 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00004987 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004988 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004989 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4990 if (RD->hasTrivialDefaultConstructor() &&
4991 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004992 return true;
4993
Alp Tokerb4bca412014-01-20 00:23:47 +00004994 bool FoundConstructor = false;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004995 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004996 // FIXME: In C++0x, a constructor template can be a default constructor.
Hal Finkelfec83452016-11-27 16:26:14 +00004997 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004998 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004999 // UsingDecl itself is not a constructor
5000 if (isa<UsingDecl>(ND))
5001 continue;
5002 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redlc15c3262010-09-13 22:02:47 +00005003 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00005004 FoundConstructor = true;
Sebastian Redlc15c3262010-09-13 22:02:47 +00005005 const FunctionProtoType *CPT
5006 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00005007 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5008 if (!CPT)
5009 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00005010 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00005011 // For now, we'll be conservative and assume that they can throw.
Richard Smitheaf11ad2018-05-03 03:58:32 +00005012 if (!CPT->isNothrow() || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00005013 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00005014 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005015 }
Alp Tokerb4bca412014-01-20 00:23:47 +00005016 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005017 }
5018 return false;
5019 case UTT_HasVirtualDestructor:
5020 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5021 // If type is a class type with a virtual destructor ([class.dtor])
5022 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00005023 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00005024 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005025 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005026 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00005027
5028 // These type trait expressions are modeled on the specifications for the
5029 // Embarcadero C++0x type trait functions:
5030 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5031 case UTT_IsCompleteType:
5032 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
5033 // Returns True if and only if T is a complete type at the point of the
5034 // function call.
5035 return !T->isIncompleteType();
Erich Keanee63e9d72017-10-24 21:31:50 +00005036 case UTT_HasUniqueObjectRepresentations:
Erich Keane8a6b7402017-11-30 16:37:02 +00005037 return C.hasUniqueObjectRepresentations(T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005038 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005039}
Sebastian Redl5822f082009-02-07 20:10:22 +00005040
Alp Tokercbb90342013-12-13 20:49:58 +00005041static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5042 QualType RhsT, SourceLocation KeyLoc);
5043
Douglas Gregor29c42f22012-02-24 07:38:34 +00005044static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
5045 ArrayRef<TypeSourceInfo *> Args,
5046 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00005047 if (Kind <= UTT_Last)
5048 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
5049
Eric Fiselier1af6c112018-01-12 00:09:37 +00005050 // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
5051 // traits to avoid duplication.
5052 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
Alp Tokercbb90342013-12-13 20:49:58 +00005053 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
5054 Args[1]->getType(), RParenLoc);
5055
Douglas Gregor29c42f22012-02-24 07:38:34 +00005056 switch (Kind) {
Eric Fiselier1af6c112018-01-12 00:09:37 +00005057 case clang::BTT_ReferenceBindsToTemporary:
Alp Toker73287bf2014-01-20 00:24:09 +00005058 case clang::TT_IsConstructible:
5059 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00005060 case clang::TT_IsTriviallyConstructible: {
5061 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00005062 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00005063 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00005064 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00005065 // definition for is_constructible, as defined below, is known to call
5066 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00005067 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005068 // The predicate condition for a template specialization
5069 // is_constructible<T, Args...> shall be satisfied if and only if the
5070 // following variable definition would be well-formed for some invented
Douglas Gregor29c42f22012-02-24 07:38:34 +00005071 // variable t:
5072 //
5073 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00005074 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00005075
5076 // Precondition: T and all types in the parameter pack Args shall be
5077 // complete types, (possibly cv-qualified) void, or arrays of
5078 // unknown bound.
Aaron Ballman2bf2cad2015-07-21 21:18:29 +00005079 for (const auto *TSI : Args) {
5080 QualType ArgTy = TSI->getType();
Eli Friedman9ea1e162013-09-11 02:53:02 +00005081 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00005082 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00005083
Simon Pilgrim75c26882016-09-30 14:25:09 +00005084 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00005085 diag::err_incomplete_type_used_in_type_trait_expr))
5086 return false;
5087 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00005088
David Majnemer9658ecc2015-11-13 05:32:43 +00005089 // Make sure the first argument is not incomplete nor a function type.
5090 QualType T = Args[0]->getType();
5091 if (T->isIncompleteType() || T->isFunctionType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00005092 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00005093
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00005094 // Make sure the first argument is not an abstract type.
David Majnemer9658ecc2015-11-13 05:32:43 +00005095 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00005096 if (RD && RD->isAbstract())
5097 return false;
5098
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005099 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
5100 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005101 ArgExprs.reserve(Args.size() - 1);
5102 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
David Majnemer9658ecc2015-11-13 05:32:43 +00005103 QualType ArgTy = Args[I]->getType();
5104 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
5105 ArgTy = S.Context.getRValueReferenceType(ArgTy);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005106 OpaqueArgExprs.push_back(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005107 OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
David Majnemer9658ecc2015-11-13 05:32:43 +00005108 ArgTy.getNonLValueExprType(S.Context),
5109 Expr::getValueKindForType(ArgTy)));
Douglas Gregor29c42f22012-02-24 07:38:34 +00005110 }
Richard Smitha507bfc2014-07-23 20:07:08 +00005111 for (Expr &E : OpaqueArgExprs)
5112 ArgExprs.push_back(&E);
5113
Simon Pilgrim75c26882016-09-30 14:25:09 +00005114 // Perform the initialization in an unevaluated context within a SFINAE
Douglas Gregor29c42f22012-02-24 07:38:34 +00005115 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005116 EnterExpressionEvaluationContext Unevaluated(
5117 S, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005118 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
5119 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
5120 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
5121 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
5122 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005123 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005124 if (Init.Failed())
5125 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00005126
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005127 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005128 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5129 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00005130
Alp Toker73287bf2014-01-20 00:24:09 +00005131 if (Kind == clang::TT_IsConstructible)
5132 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00005133
Eric Fiselier1af6c112018-01-12 00:09:37 +00005134 if (Kind == clang::BTT_ReferenceBindsToTemporary) {
5135 if (!T->isReferenceType())
5136 return false;
5137
5138 return !Init.isDirectReferenceBinding();
5139 }
5140
Alp Toker73287bf2014-01-20 00:24:09 +00005141 if (Kind == clang::TT_IsNothrowConstructible)
5142 return S.canThrow(Result.get()) == CT_Cannot;
5143
5144 if (Kind == clang::TT_IsTriviallyConstructible) {
Brian Kelley93c640b2017-03-29 17:40:35 +00005145 // Under Objective-C ARC and Weak, if the destination has non-trivial
5146 // Objective-C lifetime, this is a non-trivial construction.
5147 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00005148 return false;
5149
5150 // The initialization succeeded; now make sure there are no non-trivial
5151 // calls.
5152 return !Result.get()->hasNonTrivialCall(S.Context);
5153 }
5154
5155 llvm_unreachable("unhandled type trait");
5156 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005157 }
Alp Tokercbb90342013-12-13 20:49:58 +00005158 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00005159 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005160
Douglas Gregor29c42f22012-02-24 07:38:34 +00005161 return false;
5162}
5163
Simon Pilgrim75c26882016-09-30 14:25:09 +00005164ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5165 ArrayRef<TypeSourceInfo *> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00005166 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00005167 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00005168
Alp Toker95e7ff22014-01-01 05:57:51 +00005169 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
5170 *this, Kind, KWLoc, Args[0]->getType()))
5171 return ExprError();
5172
Douglas Gregor29c42f22012-02-24 07:38:34 +00005173 bool Dependent = false;
5174 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5175 if (Args[I]->getType()->isDependentType()) {
5176 Dependent = true;
5177 break;
5178 }
5179 }
Alp Tokercbb90342013-12-13 20:49:58 +00005180
5181 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005182 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00005183 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
5184
5185 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
5186 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005187}
5188
Alp Toker88f64e62013-12-13 21:19:30 +00005189ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5190 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00005191 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005192 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005193 ConvertedArgs.reserve(Args.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00005194
Douglas Gregor29c42f22012-02-24 07:38:34 +00005195 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5196 TypeSourceInfo *TInfo;
5197 QualType T = GetTypeFromParser(Args[I], &TInfo);
5198 if (!TInfo)
5199 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
Simon Pilgrim75c26882016-09-30 14:25:09 +00005200
5201 ConvertedArgs.push_back(TInfo);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005202 }
Alp Tokercbb90342013-12-13 20:49:58 +00005203
Douglas Gregor29c42f22012-02-24 07:38:34 +00005204 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5205}
5206
Alp Tokercbb90342013-12-13 20:49:58 +00005207static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5208 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005209 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
5210 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005211
5212 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00005213 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005214 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00005215 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005216 // Base and Derived are not unions and name the same class type without
5217 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005218
John McCall388ef532011-01-28 22:02:36 +00005219 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
John McCall388ef532011-01-28 22:02:36 +00005220 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
Erik Pilkington07f8c432017-05-10 17:18:56 +00005221 if (!rhsRecord || !lhsRecord) {
5222 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5223 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5224 if (!LHSObjTy || !RHSObjTy)
5225 return false;
5226
5227 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5228 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5229 if (!BaseInterface || !DerivedInterface)
5230 return false;
5231
5232 if (Self.RequireCompleteType(
5233 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5234 return false;
5235
5236 return BaseInterface->isSuperClassOf(DerivedInterface);
5237 }
John McCall388ef532011-01-28 22:02:36 +00005238
5239 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
5240 == (lhsRecord == rhsRecord));
5241
Marshall Clowce781052019-05-13 19:29:23 +00005242 // Unions are never base classes, and never have base classes.
5243 // It doesn't matter if they are complete or not. See PR#41843
5244 if (lhsRecord && lhsRecord->getDecl()->isUnion())
5245 return false;
5246 if (rhsRecord && rhsRecord->getDecl()->isUnion())
5247 return false;
5248
John McCall388ef532011-01-28 22:02:36 +00005249 if (lhsRecord == rhsRecord)
Marshall Clowce781052019-05-13 19:29:23 +00005250 return true;
John McCall388ef532011-01-28 22:02:36 +00005251
5252 // C++0x [meta.rel]p2:
5253 // If Base and Derived are class types and are different types
5254 // (ignoring possible cv-qualifiers) then Derived shall be a
5255 // complete type.
Simon Pilgrim75c26882016-09-30 14:25:09 +00005256 if (Self.RequireCompleteType(KeyLoc, RhsT,
John McCall388ef532011-01-28 22:02:36 +00005257 diag::err_incomplete_type_used_in_type_trait_expr))
5258 return false;
5259
5260 return cast<CXXRecordDecl>(rhsRecord->getDecl())
5261 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5262 }
John Wiegley65497cc2011-04-27 23:09:49 +00005263 case BTT_IsSame:
5264 return Self.Context.hasSameType(LhsT, RhsT);
George Burgess IV31ac1fa2017-10-16 22:58:37 +00005265 case BTT_TypeCompatible: {
5266 // GCC ignores cv-qualifiers on arrays for this builtin.
5267 Qualifiers LhsQuals, RhsQuals;
5268 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5269 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5270 return Self.Context.typesAreCompatible(Lhs, Rhs);
5271 }
John Wiegley65497cc2011-04-27 23:09:49 +00005272 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00005273 case BTT_IsConvertibleTo: {
5274 // C++0x [meta.rel]p4:
5275 // Given the following function prototype:
5276 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005277 // template <class T>
Douglas Gregor8006e762011-01-27 20:28:01 +00005278 // typename add_rvalue_reference<T>::type create();
5279 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005280 // the predicate condition for a template specialization
5281 // is_convertible<From, To> shall be satisfied if and only if
5282 // the return expression in the following code would be
Douglas Gregor8006e762011-01-27 20:28:01 +00005283 // well-formed, including any implicit conversions to the return
5284 // type of the function:
5285 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005286 // To test() {
Douglas Gregor8006e762011-01-27 20:28:01 +00005287 // return create<From>();
5288 // }
5289 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005290 // Access checking is performed as if in a context unrelated to To and
5291 // From. Only the validity of the immediate context of the expression
Douglas Gregor8006e762011-01-27 20:28:01 +00005292 // of the return-statement (including conversions to the return type)
5293 // is considered.
5294 //
5295 // We model the initialization as a copy-initialization of a temporary
5296 // of the appropriate type, which for this expression is identical to the
5297 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005298
5299 // Functions aren't allowed to return function or array types.
5300 if (RhsT->isFunctionType() || RhsT->isArrayType())
5301 return false;
5302
5303 // A return statement in a void function must have void type.
5304 if (RhsT->isVoidType())
5305 return LhsT->isVoidType();
5306
5307 // A function definition requires a complete, non-abstract return type.
Richard Smithdb0ac552015-12-18 22:40:25 +00005308 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005309 return false;
5310
5311 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00005312 if (LhsT->isObjectType() || LhsT->isFunctionType())
5313 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005314
5315 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00005316 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00005317 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00005318 Expr::getValueKindForType(LhsT));
5319 Expr *FromPtr = &From;
Simon Pilgrim75c26882016-09-30 14:25:09 +00005320 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
Douglas Gregor8006e762011-01-27 20:28:01 +00005321 SourceLocation()));
Simon Pilgrim75c26882016-09-30 14:25:09 +00005322
5323 // Perform the initialization in an unevaluated context within a SFINAE
Eli Friedmana59b1902012-01-25 01:05:57 +00005324 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005325 EnterExpressionEvaluationContext Unevaluated(
5326 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00005327 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5328 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005329 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005330 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00005331 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00005332
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005333 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00005334 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5335 }
Alp Toker73287bf2014-01-20 00:24:09 +00005336
David Majnemerb3d96882016-05-23 17:21:55 +00005337 case BTT_IsAssignable:
Alp Toker73287bf2014-01-20 00:24:09 +00005338 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00005339 case BTT_IsTriviallyAssignable: {
5340 // C++11 [meta.unary.prop]p3:
5341 // is_trivially_assignable is defined as:
5342 // is_assignable<T, U>::value is true and the assignment, as defined by
5343 // is_assignable, is known to call no operation that is not trivial
5344 //
5345 // is_assignable is defined as:
Simon Pilgrim75c26882016-09-30 14:25:09 +00005346 // The expression declval<T>() = declval<U>() is well-formed when
Douglas Gregor1be329d2012-02-23 07:33:15 +00005347 // treated as an unevaluated operand (Clause 5).
5348 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005349 // For both, T and U shall be complete types, (possibly cv-qualified)
Douglas Gregor1be329d2012-02-23 07:33:15 +00005350 // void, or arrays of unknown bound.
5351 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00005352 Self.RequireCompleteType(KeyLoc, LhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00005353 diag::err_incomplete_type_used_in_type_trait_expr))
5354 return false;
5355 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00005356 Self.RequireCompleteType(KeyLoc, RhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00005357 diag::err_incomplete_type_used_in_type_trait_expr))
5358 return false;
5359
5360 // cv void is never assignable.
5361 if (LhsT->isVoidType() || RhsT->isVoidType())
5362 return false;
5363
Simon Pilgrim75c26882016-09-30 14:25:09 +00005364 // Build expressions that emulate the effect of declval<T>() and
Douglas Gregor1be329d2012-02-23 07:33:15 +00005365 // declval<U>().
5366 if (LhsT->isObjectType() || LhsT->isFunctionType())
5367 LhsT = Self.Context.getRValueReferenceType(LhsT);
5368 if (RhsT->isObjectType() || RhsT->isFunctionType())
5369 RhsT = Self.Context.getRValueReferenceType(RhsT);
5370 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5371 Expr::getValueKindForType(LhsT));
5372 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5373 Expr::getValueKindForType(RhsT));
Simon Pilgrim75c26882016-09-30 14:25:09 +00005374
5375 // Attempt the assignment in an unevaluated context within a SFINAE
Douglas Gregor1be329d2012-02-23 07:33:15 +00005376 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005377 EnterExpressionEvaluationContext Unevaluated(
5378 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor1be329d2012-02-23 07:33:15 +00005379 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
Erich Keane1a3b8fd2017-12-12 16:22:31 +00005380 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005381 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5382 &Rhs);
Richard Smith1e3a8d12019-10-11 17:59:09 +00005383 if (Result.isInvalid())
5384 return false;
5385
5386 // Treat the assignment as unused for the purpose of -Wdeprecated-volatile.
5387 Self.CheckUnusedVolatileAssignment(Result.get());
5388
5389 if (SFINAE.hasErrorOccurred())
Douglas Gregor1be329d2012-02-23 07:33:15 +00005390 return false;
5391
David Majnemerb3d96882016-05-23 17:21:55 +00005392 if (BTT == BTT_IsAssignable)
5393 return true;
5394
Alp Toker73287bf2014-01-20 00:24:09 +00005395 if (BTT == BTT_IsNothrowAssignable)
5396 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00005397
Alp Toker73287bf2014-01-20 00:24:09 +00005398 if (BTT == BTT_IsTriviallyAssignable) {
Brian Kelley93c640b2017-03-29 17:40:35 +00005399 // Under Objective-C ARC and Weak, if the destination has non-trivial
5400 // Objective-C lifetime, this is a non-trivial assignment.
5401 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00005402 return false;
5403
5404 return !Result.get()->hasNonTrivialCall(Self.Context);
5405 }
5406
5407 llvm_unreachable("unhandled type trait");
5408 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00005409 }
Alp Tokercbb90342013-12-13 20:49:58 +00005410 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005411 }
5412 llvm_unreachable("Unknown type trait or not implemented");
5413}
5414
John Wiegley6242b6a2011-04-28 00:16:57 +00005415ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5416 SourceLocation KWLoc,
5417 ParsedType Ty,
5418 Expr* DimExpr,
5419 SourceLocation RParen) {
5420 TypeSourceInfo *TSInfo;
5421 QualType T = GetTypeFromParser(Ty, &TSInfo);
5422 if (!TSInfo)
5423 TSInfo = Context.getTrivialTypeSourceInfo(T);
5424
5425 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5426}
5427
5428static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5429 QualType T, Expr *DimExpr,
5430 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005431 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00005432
5433 switch(ATT) {
5434 case ATT_ArrayRank:
5435 if (T->isArrayType()) {
5436 unsigned Dim = 0;
5437 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5438 ++Dim;
5439 T = AT->getElementType();
5440 }
5441 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00005442 }
John Wiegleyd3522222011-04-28 02:06:46 +00005443 return 0;
5444
John Wiegley6242b6a2011-04-28 00:16:57 +00005445 case ATT_ArrayExtent: {
5446 llvm::APSInt Value;
5447 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00005448 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00005449 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00005450 false).isInvalid())
5451 return 0;
5452 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00005453 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5454 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00005455 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00005456 }
Richard Smithf4c51d92012-02-04 09:53:13 +00005457 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00005458
5459 if (T->isArrayType()) {
5460 unsigned D = 0;
5461 bool Matched = false;
5462 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5463 if (Dim == D) {
5464 Matched = true;
5465 break;
5466 }
5467 ++D;
5468 T = AT->getElementType();
5469 }
5470
John Wiegleyd3522222011-04-28 02:06:46 +00005471 if (Matched && T->isArrayType()) {
5472 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5473 return CAT->getSize().getLimitedValue();
5474 }
John Wiegley6242b6a2011-04-28 00:16:57 +00005475 }
John Wiegleyd3522222011-04-28 02:06:46 +00005476 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00005477 }
5478 }
5479 llvm_unreachable("Unknown type trait or not implemented");
5480}
5481
5482ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5483 SourceLocation KWLoc,
5484 TypeSourceInfo *TSInfo,
5485 Expr* DimExpr,
5486 SourceLocation RParen) {
5487 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00005488
Chandler Carruthc5276e52011-05-01 08:48:21 +00005489 // FIXME: This should likely be tracked as an APInt to remove any host
5490 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005491 uint64_t Value = 0;
5492 if (!T->isDependentType())
5493 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5494
Chandler Carruthc5276e52011-05-01 08:48:21 +00005495 // While the specification for these traits from the Embarcadero C++
5496 // compiler's documentation says the return type is 'unsigned int', Clang
5497 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5498 // compiler, there is no difference. On several other platforms this is an
5499 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005500 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5501 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00005502}
5503
John Wiegleyf9f65842011-04-25 06:54:41 +00005504ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005505 SourceLocation KWLoc,
5506 Expr *Queried,
5507 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005508 // If error parsing the expression, ignore.
5509 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005510 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00005511
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005512 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005513
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005514 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00005515}
5516
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005517static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5518 switch (ET) {
5519 case ET_IsLValueExpr: return E->isLValue();
5520 case ET_IsRValueExpr: return E->isRValue();
5521 }
5522 llvm_unreachable("Expression trait not covered by switch");
5523}
5524
John Wiegleyf9f65842011-04-25 06:54:41 +00005525ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005526 SourceLocation KWLoc,
5527 Expr *Queried,
5528 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005529 if (Queried->isTypeDependent()) {
5530 // Delay type-checking for type-dependent expressions.
5531 } else if (Queried->getType()->isPlaceholderType()) {
5532 ExprResult PE = CheckPlaceholderExpr(Queried);
5533 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005534 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005535 }
5536
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005537 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00005538
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005539 return new (Context)
5540 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00005541}
5542
Richard Trieu82402a02011-09-15 21:56:47 +00005543QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00005544 ExprValueKind &VK,
5545 SourceLocation Loc,
5546 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005547 assert(!LHS.get()->getType()->isPlaceholderType() &&
5548 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00005549 "placeholders should have been weeded out by now");
5550
Richard Smith4baaa5a2016-12-03 01:14:32 +00005551 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5552 // temporary materialization conversion otherwise.
5553 if (isIndirect)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005554 LHS = DefaultLvalueConversion(LHS.get());
Richard Smith4baaa5a2016-12-03 01:14:32 +00005555 else if (LHS.get()->isRValue())
5556 LHS = TemporaryMaterializationConversion(LHS.get());
5557 if (LHS.isInvalid())
5558 return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005559
5560 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005561 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00005562 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005563
Sebastian Redl5822f082009-02-07 20:10:22 +00005564 const char *OpSpelling = isIndirect ? "->*" : ".*";
5565 // C++ 5.5p2
5566 // The binary operator .* [p3: ->*] binds its second operand, which shall
5567 // be of type "pointer to member of T" (where T is a completely-defined
5568 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00005569 QualType RHSType = RHS.get()->getType();
5570 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005571 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005572 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005573 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00005574 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005575 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005576
Sebastian Redl5822f082009-02-07 20:10:22 +00005577 QualType Class(MemPtr->getClass(), 0);
5578
Douglas Gregord07ba342010-10-13 20:41:14 +00005579 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5580 // member pointer points must be completely-defined. However, there is no
5581 // reason for this semantic distinction, and the rule is not enforced by
5582 // other compilers. Therefore, we do not check this property, as it is
5583 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00005584
Sebastian Redl5822f082009-02-07 20:10:22 +00005585 // C++ 5.5p2
5586 // [...] to its first operand, which shall be of class T or of a class of
5587 // which T is an unambiguous and accessible base class. [p3: a pointer to
5588 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00005589 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005590 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005591 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5592 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005593 else {
5594 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005595 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00005596 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00005597 return QualType();
5598 }
5599 }
5600
Richard Trieu82402a02011-09-15 21:56:47 +00005601 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005602 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005603 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5604 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005605 return QualType();
5606 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005607
Richard Smith0f59cb32015-12-18 21:45:41 +00005608 if (!IsDerivedFrom(Loc, LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005609 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00005610 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005611 return QualType();
5612 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005613
5614 CXXCastPath BasePath;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005615 if (CheckDerivedToBaseConversion(
5616 LHSType, Class, Loc,
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005617 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005618 &BasePath))
Richard Smithdb05cd32013-12-12 03:40:18 +00005619 return QualType();
5620
Eli Friedman1fcf66b2010-01-16 00:00:48 +00005621 // Cast LHS to type of use.
Richard Smith01e4a7f22017-06-09 22:25:28 +00005622 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5623 if (isIndirect)
5624 UseType = Context.getPointerType(UseType);
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005625 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005626 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00005627 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00005628 }
5629
Richard Trieu82402a02011-09-15 21:56:47 +00005630 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00005631 // Diagnose use of pointer-to-member type which when used as
5632 // the functional cast in a pointer-to-member expression.
5633 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5634 return QualType();
5635 }
John McCall7decc9e2010-11-18 06:31:45 +00005636
Sebastian Redl5822f082009-02-07 20:10:22 +00005637 // C++ 5.5p2
5638 // The result is an object or a function of the type specified by the
5639 // second operand.
5640 // The cv qualifiers are the union of those in the pointer and the left side,
5641 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00005642 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00005643 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00005644
Douglas Gregor1d042092011-01-26 16:40:18 +00005645 // C++0x [expr.mptr.oper]p6:
5646 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005647 // ill-formed if the second operand is a pointer to member function with
5648 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5649 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00005650 // is a pointer to member function with ref-qualifier &&.
5651 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5652 switch (Proto->getRefQualifier()) {
5653 case RQ_None:
5654 // Do nothing
5655 break;
5656
5657 case RQ_LValue:
Richard Smith25923272017-08-25 01:47:55 +00005658 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
Nicolas Lesser1ad0e9f2018-07-13 16:27:45 +00005659 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
5660 // is (exactly) 'const'.
5661 if (Proto->isConst() && !Proto->isVolatile())
Richard Smith25923272017-08-25 01:47:55 +00005662 Diag(Loc, getLangOpts().CPlusPlus2a
5663 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5664 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5665 else
5666 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5667 << RHSType << 1 << LHS.get()->getSourceRange();
5668 }
Douglas Gregor1d042092011-01-26 16:40:18 +00005669 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005670
Douglas Gregor1d042092011-01-26 16:40:18 +00005671 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005672 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005673 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005674 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005675 break;
5676 }
5677 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005678
John McCall7decc9e2010-11-18 06:31:45 +00005679 // C++ [expr.mptr.oper]p6:
5680 // The result of a .* expression whose second operand is a pointer
5681 // to a data member is of the same value category as its
5682 // first operand. The result of a .* expression whose second
5683 // operand is a pointer to a member function is a prvalue. The
5684 // result of an ->* expression is an lvalue if its second operand
5685 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00005686 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00005687 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00005688 return Context.BoundMemberTy;
5689 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00005690 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00005691 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00005692 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00005693 }
John McCall7decc9e2010-11-18 06:31:45 +00005694
Sebastian Redl5822f082009-02-07 20:10:22 +00005695 return Result;
5696}
Sebastian Redl1a99f442009-04-16 17:51:27 +00005697
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005698/// Try to convert a type to another according to C++11 5.16p3.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005699///
5700/// This is part of the parameter validation for the ? operator. If either
5701/// value operand is a class type, the two operands are attempted to be
5702/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005703/// It returns true if the program is ill-formed and has already been diagnosed
5704/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005705static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5706 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00005707 bool &HaveConversion,
5708 QualType &ToType) {
5709 HaveConversion = false;
5710 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005711
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005712 InitializationKind Kind =
5713 InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation());
Richard Smith2414bca2016-04-25 19:30:37 +00005714 // C++11 5.16p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005715 // The process for determining whether an operand expression E1 of type T1
5716 // can be converted to match an operand expression E2 of type T2 is defined
5717 // as follows:
Richard Smith2414bca2016-04-25 19:30:37 +00005718 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5719 // implicitly converted to type "lvalue reference to T2", subject to the
5720 // constraint that in the conversion the reference must bind directly to
5721 // an lvalue.
5722 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005723 // implicitly converted to the type "rvalue reference to R2", subject to
Richard Smith2414bca2016-04-25 19:30:37 +00005724 // the constraint that the reference must bind directly.
5725 if (To->isLValue() || To->isXValue()) {
5726 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5727 : Self.Context.getRValueReferenceType(ToType);
5728
Douglas Gregor838fcc32010-03-26 20:14:36 +00005729 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005730
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005731 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005732 if (InitSeq.isDirectReferenceBinding()) {
5733 ToType = T;
5734 HaveConversion = true;
5735 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005736 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005737
Douglas Gregor838fcc32010-03-26 20:14:36 +00005738 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005739 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005740 }
John McCall65eb8792010-02-25 01:37:24 +00005741
Sebastian Redl1a99f442009-04-16 17:51:27 +00005742 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5743 // -- if E1 and E2 have class type, and the underlying class types are
5744 // the same or one is a base class of the other:
5745 QualType FTy = From->getType();
5746 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005747 const RecordType *FRec = FTy->getAs<RecordType>();
5748 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005749 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Richard Smith0f59cb32015-12-18 21:45:41 +00005750 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5751 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5752 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005753 // E1 can be converted to match E2 if the class of T2 is the
5754 // same type as, or a base class of, the class of T1, and
5755 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00005756 if (FRec == TRec || FDerivedFromT) {
5757 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005758 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005759 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005760 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005761 HaveConversion = true;
5762 return false;
5763 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005764
Douglas Gregor838fcc32010-03-26 20:14:36 +00005765 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005766 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005767 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005768 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005769
Douglas Gregor838fcc32010-03-26 20:14:36 +00005770 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005771 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005772
Douglas Gregor838fcc32010-03-26 20:14:36 +00005773 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5774 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005775 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00005776 // an rvalue).
5777 //
5778 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5779 // to the array-to-pointer or function-to-pointer conversions.
Richard Smith16d31502016-12-21 01:31:56 +00005780 TTy = TTy.getNonLValueExprType(Self.Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005781
Douglas Gregor838fcc32010-03-26 20:14:36 +00005782 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005783 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005784 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00005785 ToType = TTy;
5786 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005787 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005788
Sebastian Redl1a99f442009-04-16 17:51:27 +00005789 return false;
5790}
5791
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005792/// Try to find a common type for two according to C++0x 5.16p5.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005793///
5794/// This is part of the parameter validation for the ? operator. If either
5795/// value operand is a class type, overload resolution is used to find a
5796/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00005797static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005798 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005799 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00005800 OverloadCandidateSet CandidateSet(QuestionLoc,
5801 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00005802 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005803 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005804
5805 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005806 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00005807 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005808 // We found a match. Perform the conversions on the arguments and move on.
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005809 ExprResult LHSRes = Self.PerformImplicitConversion(
5810 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5811 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005812 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005813 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005814 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00005815
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005816 ExprResult RHSRes = Self.PerformImplicitConversion(
5817 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5818 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005819 if (RHSRes.isInvalid())
5820 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005821 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00005822 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00005823 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005824 return false;
John Wiegley01296292011-04-08 18:41:53 +00005825 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005826
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005827 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005828
5829 // Emit a better diagnostic if one of the expressions is a null pointer
5830 // constant and the other is a pointer type. In this case, the user most
5831 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005832 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005833 return true;
5834
5835 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005836 << LHS.get()->getType() << RHS.get()->getType()
5837 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005838 return true;
5839
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005840 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005841 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00005842 << LHS.get()->getType() << RHS.get()->getType()
5843 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00005844 // FIXME: Print the possible common types by printing the return types of
5845 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005846 break;
5847
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005848 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00005849 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005850 }
5851 return true;
5852}
5853
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005854/// Perform an "extended" implicit conversion as returned by
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005855/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00005856static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005857 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005858 InitializationKind Kind =
5859 InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005860 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005861 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005862 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005863 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005864 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005865
John Wiegley01296292011-04-08 18:41:53 +00005866 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005867 return false;
5868}
5869
Erich Keane349636d2019-12-05 06:17:39 -08005870// Check the condition operand of ?: to see if it is valid for the GCC
5871// extension.
5872static bool isValidVectorForConditionalCondition(ASTContext &Ctx,
5873 QualType CondTy) {
5874 if (!CondTy->isVectorType() || CondTy->isExtVectorType())
5875 return false;
5876 const QualType EltTy =
5877 cast<VectorType>(CondTy.getCanonicalType())->getElementType();
5878
5879 assert(!EltTy->isBooleanType() && !EltTy->isEnumeralType() &&
5880 "Vectors cant be boolean or enum types");
5881 return EltTy->isIntegralType(Ctx);
5882}
5883
5884QualType Sema::CheckGNUVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
5885 ExprResult &RHS,
5886 SourceLocation QuestionLoc) {
5887 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5888 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
5889
5890 QualType CondType = Cond.get()->getType();
5891 const auto *CondVT = CondType->getAs<VectorType>();
5892 QualType CondElementTy = CondVT->getElementType();
5893 unsigned CondElementCount = CondVT->getNumElements();
5894 QualType LHSType = LHS.get()->getType();
5895 const auto *LHSVT = LHSType->getAs<VectorType>();
5896 QualType RHSType = RHS.get()->getType();
5897 const auto *RHSVT = RHSType->getAs<VectorType>();
5898
5899 QualType ResultType;
5900
5901 // FIXME: In the future we should define what the Extvector conditional
5902 // operator looks like.
5903 if (LHSVT && isa<ExtVectorType>(LHSVT)) {
5904 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
5905 << /*isExtVector*/ true << LHSType;
5906 return {};
5907 }
5908
5909 if (RHSVT && isa<ExtVectorType>(RHSVT)) {
5910 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
5911 << /*isExtVector*/ true << RHSType;
5912 return {};
5913 }
5914
5915 if (LHSVT && RHSVT) {
5916 // If both are vector types, they must be the same type.
5917 if (!Context.hasSameType(LHSType, RHSType)) {
5918 Diag(QuestionLoc, diag::err_conditional_vector_mismatched_vectors)
5919 << LHSType << RHSType;
5920 return {};
5921 }
5922 ResultType = LHSType;
5923 } else if (LHSVT || RHSVT) {
5924 ResultType = CheckVectorOperands(
5925 LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true,
5926 /*AllowBoolConversions*/ false);
5927 if (ResultType.isNull())
5928 return {};
5929 } else {
5930 // Both are scalar.
5931 QualType ResultElementTy;
5932 LHSType = LHSType.getCanonicalType().getUnqualifiedType();
5933 RHSType = RHSType.getCanonicalType().getUnqualifiedType();
5934
5935 if (Context.hasSameType(LHSType, RHSType))
5936 ResultElementTy = LHSType;
5937 else
5938 ResultElementTy =
5939 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
5940
5941 if (ResultElementTy->isEnumeralType()) {
5942 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
5943 << /*isExtVector*/ false << ResultElementTy;
5944 return {};
5945 }
5946 ResultType = Context.getVectorType(
5947 ResultElementTy, CondType->getAs<VectorType>()->getNumElements(),
5948 VectorType::GenericVector);
5949
5950 LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
5951 RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
5952 }
5953
5954 assert(!ResultType.isNull() && ResultType->isVectorType() &&
5955 "Result should have been a vector type");
5956 QualType ResultElementTy = ResultType->getAs<VectorType>()->getElementType();
5957 unsigned ResultElementCount =
5958 ResultType->getAs<VectorType>()->getNumElements();
5959
5960 if (ResultElementCount != CondElementCount) {
5961 Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType
5962 << ResultType;
5963 return {};
5964 }
5965
5966 if (Context.getTypeSize(ResultElementTy) !=
5967 Context.getTypeSize(CondElementTy)) {
5968 Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType
5969 << ResultType;
5970 return {};
5971 }
5972
5973 return ResultType;
5974}
5975
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005976/// Check the operands of ?: under C++ semantics.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005977///
5978/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5979/// extension. In this case, LHS == Cond. (But they're not aliases.)
Erich Keane349636d2019-12-05 06:17:39 -08005980///
5981/// This function also implements GCC's vector extension for conditionals.
5982/// GCC's vector extension permits the use of a?b:c where the type of
5983/// a is that of a integer vector with the same number of elements and
5984/// size as the vectors of b and c. If one of either b or c is a scalar
5985/// it is implicitly converted to match the type of the vector.
5986/// Otherwise the expression is ill-formed. If both b and c are scalars,
5987/// then b and c are checked and converted to the type of a if possible.
5988/// Unlike the OpenCL ?: operator, the expression is evaluated as
5989/// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
Richard Smithf2b084f2012-08-08 06:13:49 +00005990QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5991 ExprResult &RHS, ExprValueKind &VK,
5992 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00005993 SourceLocation QuestionLoc) {
Erich Keane349636d2019-12-05 06:17:39 -08005994 // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface
5995 // pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005996
John McCall7decc9e2010-11-18 06:31:45 +00005997 // Assume r-value.
5998 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005999 OK = OK_Ordinary;
Erich Keane349636d2019-12-05 06:17:39 -08006000 bool IsVectorConditional =
6001 isValidVectorForConditionalCondition(Context, Cond.get()->getType());
6002
6003 // C++11 [expr.cond]p1
6004 // The first expression is contextually converted to bool.
6005 if (!Cond.get()->isTypeDependent()) {
6006 ExprResult CondRes = IsVectorConditional
6007 ? DefaultFunctionArrayLvalueConversion(Cond.get())
6008 : CheckCXXBooleanCondition(Cond.get());
6009 if (CondRes.isInvalid())
6010 return QualType();
6011 Cond = CondRes;
6012 } else {
6013 // To implement C++, the first expression typically doesn't alter the result
6014 // type of the conditional, however the GCC compatible vector extension
6015 // changes the result type to be that of the conditional. Since we cannot
6016 // know if this is a vector extension here, delay the conversion of the
6017 // LHS/RHS below until later.
6018 return Context.DependentTy;
6019 }
6020
John McCall7decc9e2010-11-18 06:31:45 +00006021
Sebastian Redl1a99f442009-04-16 17:51:27 +00006022 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00006023 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00006024 return Context.DependentTy;
6025
Richard Smith45edb702012-08-07 22:06:48 +00006026 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00006027 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00006028 QualType LTy = LHS.get()->getType();
6029 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00006030 bool LVoid = LTy->isVoidType();
6031 bool RVoid = RTy->isVoidType();
6032 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006033 // ... one of the following shall hold:
6034 // -- The second or the third operand (but not both) is a (possibly
6035 // parenthesized) throw-expression; the result is of the type
6036 // and value category of the other.
6037 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
6038 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
Erich Keane349636d2019-12-05 06:17:39 -08006039
6040 // Void expressions aren't legal in the vector-conditional expressions.
6041 if (IsVectorConditional) {
6042 SourceRange DiagLoc =
6043 LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange();
6044 bool IsThrow = LVoid ? LThrow : RThrow;
6045 Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void)
6046 << DiagLoc << IsThrow;
6047 return QualType();
6048 }
6049
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006050 if (LThrow != RThrow) {
6051 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
6052 VK = NonThrow->getValueKind();
6053 // DR (no number yet): the result is a bit-field if the
6054 // non-throw-expression operand is a bit-field.
6055 OK = NonThrow->getObjectKind();
6056 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00006057 }
6058
Sebastian Redl1a99f442009-04-16 17:51:27 +00006059 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00006060 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00006061 if (LVoid && RVoid)
6062 return Context.VoidTy;
6063
6064 // Neither holds, error.
6065 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
6066 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00006067 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00006068 return QualType();
6069 }
6070
6071 // Neither is void.
Erich Keane349636d2019-12-05 06:17:39 -08006072 if (IsVectorConditional)
6073 return CheckGNUVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
Sebastian Redl1a99f442009-04-16 17:51:27 +00006074
Richard Smithf2b084f2012-08-08 06:13:49 +00006075 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00006076 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00006077 // either has (cv) class type [...] an attempt is made to convert each of
6078 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006079 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00006080 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00006081 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00006082 QualType L2RType, R2LType;
6083 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00006084 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00006085 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00006086 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00006087 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006088
Sebastian Redl1a99f442009-04-16 17:51:27 +00006089 // If both can be converted, [...] the program is ill-formed.
6090 if (HaveL2R && HaveR2L) {
6091 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00006092 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00006093 return QualType();
6094 }
6095
6096 // If exactly one conversion is possible, that conversion is applied to
6097 // the chosen operand and the converted operands are used in place of the
6098 // original operands for the remainder of this section.
6099 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00006100 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00006101 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00006102 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00006103 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00006104 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00006105 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00006106 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00006107 }
6108 }
6109
Richard Smithf2b084f2012-08-08 06:13:49 +00006110 // C++11 [expr.cond]p3
6111 // if both are glvalues of the same value category and the same type except
6112 // for cv-qualification, an attempt is made to convert each of those
6113 // operands to the type of the other.
Richard Smith1be59c52016-10-22 01:32:19 +00006114 // FIXME:
6115 // Resolving a defect in P0012R1: we extend this to cover all cases where
6116 // one of the operands is reference-compatible with the other, in order
Richard Smith3ced2392019-12-18 14:01:40 -08006117 // to support conditionals between functions differing in noexcept. This
6118 // will similarly cover difference in array bounds after P0388R4.
Richard Smithf041e9a2020-01-09 15:31:56 -08006119 // FIXME: If LTy and RTy have a composite pointer type, should we convert to
6120 // that instead?
Richard Smithf2b084f2012-08-08 06:13:49 +00006121 ExprValueKind LVK = LHS.get()->getValueKind();
6122 ExprValueKind RVK = RHS.get()->getValueKind();
6123 if (!Context.hasSameType(LTy, RTy) &&
Richard Smithf2b084f2012-08-08 06:13:49 +00006124 LVK == RVK && LVK != VK_RValue) {
Richard Smith1be59c52016-10-22 01:32:19 +00006125 // DerivedToBase was already handled by the class-specific case above.
6126 // FIXME: Should we allow ObjC conversions here?
Richard Smith3ced2392019-12-18 14:01:40 -08006127 const ReferenceConversions AllowedConversions =
Richard Smithf041e9a2020-01-09 15:31:56 -08006128 ReferenceConversions::Qualification |
6129 ReferenceConversions::NestedQualification |
6130 ReferenceConversions::Function;
Richard Smith3ced2392019-12-18 14:01:40 -08006131
6132 ReferenceConversions RefConv;
6133 if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) ==
6134 Ref_Compatible &&
6135 !(RefConv & ~AllowedConversions) &&
Richard Smithb8c0f552016-12-09 18:49:13 +00006136 // [...] subject to the constraint that the reference must bind
6137 // directly [...]
Peter Collingbourne766f1582019-10-19 00:34:54 +00006138 !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006139 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00006140 RTy = RHS.get()->getType();
Richard Smith3ced2392019-12-18 14:01:40 -08006141 } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) ==
6142 Ref_Compatible &&
6143 !(RefConv & ~AllowedConversions) &&
Richard Smithb8c0f552016-12-09 18:49:13 +00006144 !LHS.get()->refersToBitField() &&
6145 !LHS.get()->refersToVectorElement()) {
Richard Smith1be59c52016-10-22 01:32:19 +00006146 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
6147 LTy = LHS.get()->getType();
Richard Smithf2b084f2012-08-08 06:13:49 +00006148 }
6149 }
6150
6151 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00006152 // If the second and third operands are glvalues of the same value
6153 // category and have the same type, the result is of that type and
6154 // value category and it is a bit-field if the second or the third
6155 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00006156 // We only extend this to bitfields, not to the crazy other kinds of
6157 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00006158 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00006159 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00006160 LHS.get()->isOrdinaryOrBitFieldObject() &&
6161 RHS.get()->isOrdinaryOrBitFieldObject()) {
6162 VK = LHS.get()->getValueKind();
6163 if (LHS.get()->getObjectKind() == OK_BitField ||
6164 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00006165 OK = OK_BitField;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006166
6167 // If we have function pointer types, unify them anyway to unify their
6168 // exception specifications, if any.
6169 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
6170 Qualifiers Qs = LTy.getQualifiers();
Richard Smith5e9746f2016-10-21 22:00:42 +00006171 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006172 /*ConvertArgs*/false);
6173 LTy = Context.getQualifiedType(LTy, Qs);
6174
6175 assert(!LTy.isNull() && "failed to find composite pointer type for "
6176 "canonically equivalent function ptr types");
6177 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
6178 }
6179
John McCall7decc9e2010-11-18 06:31:45 +00006180 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00006181 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00006182
Richard Smithf2b084f2012-08-08 06:13:49 +00006183 // C++11 [expr.cond]p5
6184 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00006185 // do not have the same type, and either has (cv) class type, ...
6186 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
6187 // ... overload resolution is used to determine the conversions (if any)
6188 // to be applied to the operands. If the overload resolution fails, the
6189 // program is ill-formed.
6190 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
6191 return QualType();
6192 }
6193
Richard Smithf2b084f2012-08-08 06:13:49 +00006194 // C++11 [expr.cond]p6
6195 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00006196 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006197 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6198 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00006199 if (LHS.isInvalid() || RHS.isInvalid())
6200 return QualType();
6201 LTy = LHS.get()->getType();
6202 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00006203
6204 // After those conversions, one of the following shall hold:
6205 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00006206 // is of that type. If the operands have class type, the result
6207 // is a prvalue temporary of the result type, which is
6208 // copy-initialized from either the second operand or the third
6209 // operand depending on the value of the first operand.
6210 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
6211 if (LTy->isRecordType()) {
6212 // The operands have class type. Make a temporary copy.
6213 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00006214
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006215 ExprResult LHSCopy = PerformCopyInitialization(Entity,
6216 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00006217 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00006218 if (LHSCopy.isInvalid())
6219 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006220
6221 ExprResult RHSCopy = PerformCopyInitialization(Entity,
6222 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00006223 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00006224 if (RHSCopy.isInvalid())
6225 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006226
John Wiegley01296292011-04-08 18:41:53 +00006227 LHS = LHSCopy;
6228 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00006229 }
6230
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006231 // If we have function pointer types, unify them anyway to unify their
6232 // exception specifications, if any.
6233 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
6234 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
6235 assert(!LTy.isNull() && "failed to find composite pointer type for "
6236 "canonically equivalent function ptr types");
6237 }
6238
Sebastian Redl1a99f442009-04-16 17:51:27 +00006239 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00006240 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00006241
Douglas Gregor46188682010-05-18 22:42:18 +00006242 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006243 if (LTy->isVectorType() || RTy->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00006244 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6245 /*AllowBothBool*/true,
6246 /*AllowBoolConversions*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00006247
Sebastian Redl1a99f442009-04-16 17:51:27 +00006248 // -- The second and third operands have arithmetic or enumeration type;
6249 // the usual arithmetic conversions are performed to bring them to a
6250 // common type, and the result is of that type.
6251 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
Richard Smith4b002992019-12-16 15:17:24 -08006252 QualType ResTy =
6253 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
John Wiegley01296292011-04-08 18:41:53 +00006254 if (LHS.isInvalid() || RHS.isInvalid())
6255 return QualType();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006256 if (ResTy.isNull()) {
6257 Diag(QuestionLoc,
6258 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
6259 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6260 return QualType();
6261 }
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006262
6263 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6264 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6265
6266 return ResTy;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006267 }
6268
6269 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00006270 // type and the other is a null pointer constant, or both are null
6271 // pointer constants, at least one of which is non-integral; pointer
6272 // conversions and qualification conversions are performed to bring them
6273 // to their composite pointer type. The result is of the composite
6274 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00006275 // -- The second and third operands have pointer to member type, or one has
6276 // pointer to member type and the other is a null pointer constant;
6277 // pointer to member conversions and qualification conversions are
6278 // performed to bring them to a common type, whose cv-qualification
6279 // shall match the cv-qualification of either the second or the third
6280 // operand. The result is of the common type.
Richard Smith5e9746f2016-10-21 22:00:42 +00006281 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
6282 if (!Composite.isNull())
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006283 return Composite;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006284
Douglas Gregor697a3912010-04-01 22:47:07 +00006285 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00006286 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
6287 if (!Composite.isNull())
6288 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006289
Chandler Carruth9c9127e2011-02-19 00:13:59 +00006290 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00006291 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00006292 return QualType();
6293
Sebastian Redl1a99f442009-04-16 17:51:27 +00006294 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00006295 << LHS.get()->getType() << RHS.get()->getType()
6296 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00006297 return QualType();
6298}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006299
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006300static FunctionProtoType::ExceptionSpecInfo
6301mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
6302 FunctionProtoType::ExceptionSpecInfo ESI2,
6303 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
6304 ExceptionSpecificationType EST1 = ESI1.Type;
6305 ExceptionSpecificationType EST2 = ESI2.Type;
6306
6307 // If either of them can throw anything, that is the result.
6308 if (EST1 == EST_None) return ESI1;
6309 if (EST2 == EST_None) return ESI2;
6310 if (EST1 == EST_MSAny) return ESI1;
6311 if (EST2 == EST_MSAny) return ESI2;
Richard Smitheaf11ad2018-05-03 03:58:32 +00006312 if (EST1 == EST_NoexceptFalse) return ESI1;
6313 if (EST2 == EST_NoexceptFalse) return ESI2;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006314
6315 // If either of them is non-throwing, the result is the other.
Erich Keaned02f4a12019-05-30 17:31:54 +00006316 if (EST1 == EST_NoThrow) return ESI2;
6317 if (EST2 == EST_NoThrow) return ESI1;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006318 if (EST1 == EST_DynamicNone) return ESI2;
6319 if (EST2 == EST_DynamicNone) return ESI1;
6320 if (EST1 == EST_BasicNoexcept) return ESI2;
6321 if (EST2 == EST_BasicNoexcept) return ESI1;
Richard Smitheaf11ad2018-05-03 03:58:32 +00006322 if (EST1 == EST_NoexceptTrue) return ESI2;
6323 if (EST2 == EST_NoexceptTrue) return ESI1;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006324
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006325 // If we're left with value-dependent computed noexcept expressions, we're
6326 // stuck. Before C++17, we can just drop the exception specification entirely,
6327 // since it's not actually part of the canonical type. And this should never
6328 // happen in C++17, because it would mean we were computing the composite
6329 // pointer type of dependent types, which should never happen.
Richard Smitheaf11ad2018-05-03 03:58:32 +00006330 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006331 assert(!S.getLangOpts().CPlusPlus17 &&
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006332 "computing composite pointer type of dependent types");
6333 return FunctionProtoType::ExceptionSpecInfo();
6334 }
6335
6336 // Switch over the possibilities so that people adding new values know to
6337 // update this function.
6338 switch (EST1) {
6339 case EST_None:
6340 case EST_DynamicNone:
6341 case EST_MSAny:
6342 case EST_BasicNoexcept:
Richard Smitheaf11ad2018-05-03 03:58:32 +00006343 case EST_DependentNoexcept:
6344 case EST_NoexceptFalse:
6345 case EST_NoexceptTrue:
Erich Keaned02f4a12019-05-30 17:31:54 +00006346 case EST_NoThrow:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006347 llvm_unreachable("handled above");
6348
6349 case EST_Dynamic: {
6350 // This is the fun case: both exception specifications are dynamic. Form
6351 // the union of the two lists.
6352 assert(EST2 == EST_Dynamic && "other cases should already be handled");
6353 llvm::SmallPtrSet<QualType, 8> Found;
6354 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
6355 for (QualType E : Exceptions)
6356 if (Found.insert(S.Context.getCanonicalType(E)).second)
6357 ExceptionTypeStorage.push_back(E);
6358
6359 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
6360 Result.Exceptions = ExceptionTypeStorage;
6361 return Result;
6362 }
6363
6364 case EST_Unevaluated:
6365 case EST_Uninstantiated:
6366 case EST_Unparsed:
6367 llvm_unreachable("shouldn't see unresolved exception specifications here");
6368 }
6369
6370 llvm_unreachable("invalid ExceptionSpecificationType");
6371}
6372
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006373/// Find a merged pointer type and convert the two expressions to it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006374///
Richard Smith9a6f4d42020-01-09 19:24:44 -08006375/// This finds the composite pointer type for \p E1 and \p E2 according to
6376/// C++2a [expr.type]p3. It converts both expressions to this type and returns
6377/// it. It does not emit diagnostics (FIXME: that's not true if \p ConvertArgs
6378/// is \c true).
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006379///
Douglas Gregor19175ff2010-04-16 23:20:25 +00006380/// \param Loc The location of the operator requiring these two expressions to
6381/// be converted to the composite pointer type.
6382///
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006383/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006384QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00006385 Expr *&E1, Expr *&E2,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006386 bool ConvertArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006387 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006388
6389 // C++1z [expr]p14:
6390 // The composite pointer type of two operands p1 and p2 having types T1
6391 // and T2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006392 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00006393
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006394 // where at least one is a pointer or pointer to member type or
6395 // std::nullptr_t is:
6396 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
6397 T1->isNullPtrType();
6398 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
6399 T2->isNullPtrType();
6400 if (!T1IsPointerLike && !T2IsPointerLike)
Richard Smithf2b084f2012-08-08 06:13:49 +00006401 return QualType();
Richard Smithf2b084f2012-08-08 06:13:49 +00006402
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006403 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
6404 // This can't actually happen, following the standard, but we also use this
6405 // to implement the end of [expr.conv], which hits this case.
6406 //
6407 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6408 if (T1IsPointerLike &&
6409 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006410 if (ConvertArgs)
6411 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
6412 ? CK_NullToMemberPointer
6413 : CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006414 return T1;
6415 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006416 if (T2IsPointerLike &&
6417 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006418 if (ConvertArgs)
6419 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
6420 ? CK_NullToMemberPointer
6421 : CK_NullToPointer).get();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006422 return T2;
6423 }
Mike Stump11289f42009-09-09 15:08:12 +00006424
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006425 // Now both have to be pointers or member pointers.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006426 if (!T1IsPointerLike || !T2IsPointerLike)
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006427 return QualType();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006428 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
6429 "nullptr_t should be a null pointer constant");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006430
Richard Smith9a6f4d42020-01-09 19:24:44 -08006431 struct Step {
6432 enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K;
6433 // Qualifiers to apply under the step kind.
6434 Qualifiers Quals;
6435 /// The class for a pointer-to-member; a constant array type with a bound
6436 /// (if any) for an array.
6437 const Type *ClassOrBound;
6438
6439 Step(Kind K, const Type *ClassOrBound = nullptr)
6440 : K(K), Quals(), ClassOrBound(ClassOrBound) {}
6441 QualType rebuild(ASTContext &Ctx, QualType T) const {
6442 T = Ctx.getQualifiedType(T, Quals);
6443 switch (K) {
6444 case Pointer:
6445 return Ctx.getPointerType(T);
6446 case MemberPointer:
6447 return Ctx.getMemberPointerType(T, ClassOrBound);
6448 case ObjCPointer:
6449 return Ctx.getObjCObjectPointerType(T);
6450 case Array:
6451 if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound))
6452 return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr,
6453 ArrayType::Normal, 0);
6454 else
6455 return Ctx.getIncompleteArrayType(T, ArrayType::Normal, 0);
6456 }
6457 llvm_unreachable("unknown step kind");
6458 }
6459 };
6460
6461 SmallVector<Step, 8> Steps;
6462
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006463 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6464 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6465 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6466 // respectively;
6467 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
Richard Smith9a6f4d42020-01-09 19:24:44 -08006468 // to member of C2 of type cv2 U2" for some non-function type U, where
6469 // C1 is reference-related to C2 or C2 is reference-related to C1, the
6470 // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2,
6471 // respectively;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006472 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6473 // T2;
6474 //
Richard Smith9a6f4d42020-01-09 19:24:44 -08006475 // Dismantle T1 and T2 to simultaneously determine whether they are similar
6476 // and to prepare to form the cv-combined type if so.
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006477 QualType Composite1 = T1;
6478 QualType Composite2 = T2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006479 unsigned NeedConstBefore = 0;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006480 while (true) {
Richard Smith9a6f4d42020-01-09 19:24:44 -08006481 assert(!Composite1.isNull() && !Composite2.isNull());
6482
6483 Qualifiers Q1, Q2;
6484 Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1);
6485 Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2);
6486
6487 // Top-level qualifiers are ignored. Merge at all lower levels.
6488 if (!Steps.empty()) {
6489 // Find the qualifier union: (approximately) the unique minimal set of
6490 // qualifiers that is compatible with both types.
6491 Qualifiers Quals = Qualifiers::fromCVRUMask(Q1.getCVRUQualifiers() |
6492 Q2.getCVRUQualifiers());
6493
6494 // Under one level of pointer or pointer-to-member, we can change to an
6495 // unambiguous compatible address space.
6496 if (Q1.getAddressSpace() == Q2.getAddressSpace()) {
6497 Quals.setAddressSpace(Q1.getAddressSpace());
6498 } else if (Steps.size() == 1) {
6499 bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2);
6500 bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1);
6501 if (MaybeQ1 == MaybeQ2)
6502 return QualType(); // No unique best address space.
6503 Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace()
6504 : Q2.getAddressSpace());
6505 } else {
6506 return QualType();
6507 }
6508
6509 // FIXME: In C, we merge __strong and none to __strong at the top level.
6510 if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr())
6511 Quals.setObjCGCAttr(Q1.getObjCGCAttr());
6512 else
6513 return QualType();
6514
6515 // Mismatched lifetime qualifiers never compatibly include each other.
6516 if (Q1.getObjCLifetime() == Q2.getObjCLifetime())
6517 Quals.setObjCLifetime(Q1.getObjCLifetime());
6518 else
6519 return QualType();
6520
6521 Steps.back().Quals = Quals;
6522 if (Q1 != Quals || Q2 != Quals)
6523 NeedConstBefore = Steps.size() - 1;
6524 }
6525
6526 // FIXME: Can we unify the following with UnwrapSimilarTypes?
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006527 const PointerType *Ptr1, *Ptr2;
6528 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
6529 (Ptr2 = Composite2->getAs<PointerType>())) {
6530 Composite1 = Ptr1->getPointeeType();
6531 Composite2 = Ptr2->getPointeeType();
Richard Smith9a6f4d42020-01-09 19:24:44 -08006532 Steps.emplace_back(Step::Pointer);
6533 continue;
6534 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006535
Richard Smith9a6f4d42020-01-09 19:24:44 -08006536 const ObjCObjectPointerType *ObjPtr1, *ObjPtr2;
6537 if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) &&
6538 (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) {
6539 Composite1 = ObjPtr1->getPointeeType();
6540 Composite2 = ObjPtr2->getPointeeType();
6541 Steps.emplace_back(Step::ObjCPointer);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006542 continue;
6543 }
Mike Stump11289f42009-09-09 15:08:12 +00006544
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006545 const MemberPointerType *MemPtr1, *MemPtr2;
6546 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
6547 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
6548 Composite1 = MemPtr1->getPointeeType();
6549 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006550
Richard Smith9a6f4d42020-01-09 19:24:44 -08006551 // At the top level, we can perform a base-to-derived pointer-to-member
6552 // conversion:
6553 //
6554 // - [...] where C1 is reference-related to C2 or C2 is
6555 // reference-related to C1
6556 //
6557 // (Note that the only kinds of reference-relatedness in scope here are
6558 // "same type or derived from".) At any other level, the class must
6559 // exactly match.
6560 const Type *Class = nullptr;
6561 QualType Cls1(MemPtr1->getClass(), 0);
6562 QualType Cls2(MemPtr2->getClass(), 0);
6563 if (Context.hasSameType(Cls1, Cls2))
6564 Class = MemPtr1->getClass();
6565 else if (Steps.empty())
6566 Class = IsDerivedFrom(Loc, Cls1, Cls2) ? MemPtr1->getClass() :
6567 IsDerivedFrom(Loc, Cls2, Cls1) ? MemPtr2->getClass() : nullptr;
6568 if (!Class)
6569 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006570
Richard Smith9a6f4d42020-01-09 19:24:44 -08006571 Steps.emplace_back(Step::MemberPointer, Class);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006572 continue;
6573 }
Mike Stump11289f42009-09-09 15:08:12 +00006574
Richard Smith9a6f4d42020-01-09 19:24:44 -08006575 // Special case: at the top level, we can decompose an Objective-C pointer
6576 // and a 'cv void *'. Unify the qualifiers.
6577 if (Steps.empty() && ((Composite1->isVoidPointerType() &&
6578 Composite2->isObjCObjectPointerType()) ||
6579 (Composite1->isObjCObjectPointerType() &&
6580 Composite2->isVoidPointerType()))) {
6581 Composite1 = Composite1->getPointeeType();
6582 Composite2 = Composite2->getPointeeType();
6583 Steps.emplace_back(Step::Pointer);
6584 continue;
6585 }
6586
6587 // FIXME: arrays
6588
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006589 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00006590
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006591 // Cannot unwrap any more types.
6592 break;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006593 }
Mike Stump11289f42009-09-09 15:08:12 +00006594
Richard Smith9a6f4d42020-01-09 19:24:44 -08006595 // - if T1 or T2 is "pointer to noexcept function" and the other type is
6596 // "pointer to function", where the function types are otherwise the same,
6597 // "pointer to function";
6598 // - if T1 or T2 is "pointer to member of C1 of type function", the other
6599 // type is "pointer to member of C2 of type noexcept function", and C1
6600 // is reference-related to C2 or C2 is reference-related to C1, where
6601 // the function types are otherwise the same, "pointer to member of C2 of
6602 // type function" or "pointer to member of C1 of type function",
6603 // respectively;
6604 //
6605 // We also support 'noreturn' here, so as a Clang extension we generalize the
6606 // above to:
6607 //
6608 // - [Clang] If T1 and T2 are both of type "pointer to function" or
6609 // "pointer to member function" and the pointee types can be unified
6610 // by a function pointer conversion, that conversion is applied
6611 // before checking the following rules.
6612 //
6613 // We've already unwrapped down to the function types, and we want to merge
6614 // rather than just convert, so do this ourselves rather than calling
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006615 // IsFunctionConversion.
6616 //
6617 // FIXME: In order to match the standard wording as closely as possible, we
6618 // currently only do this under a single level of pointers. Ideally, we would
6619 // allow this in general, and set NeedConstBefore to the relevant depth on
Richard Smith9a6f4d42020-01-09 19:24:44 -08006620 // the side(s) where we changed anything. If we permit that, we should also
6621 // consider this conversion when determining type similarity and model it as
6622 // a qualification conversion.
6623 if (Steps.size() == 1) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006624 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
6625 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
6626 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
6627 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
6628
6629 // The result is noreturn if both operands are.
6630 bool Noreturn =
6631 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
6632 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
6633 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
6634
6635 // The result is nothrow if both operands are.
6636 SmallVector<QualType, 8> ExceptionTypeStorage;
6637 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
6638 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
6639 ExceptionTypeStorage);
6640
6641 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
6642 FPT1->getParamTypes(), EPI1);
6643 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
6644 FPT2->getParamTypes(), EPI2);
6645 }
6646 }
6647 }
6648
Richard Smith9a6f4d42020-01-09 19:24:44 -08006649 // There are some more conversions we can perform under exactly one pointer.
6650 if (Steps.size() == 1 && Steps.front().K == Step::Pointer &&
6651 !Context.hasSameType(Composite1, Composite2)) {
6652 // - if T1 or T2 is "pointer to cv1 void" and the other type is
6653 // "pointer to cv2 T", where T is an object type or void,
6654 // "pointer to cv12 void", where cv12 is the union of cv1 and cv2;
6655 if (Composite1->isVoidType() && Composite2->isObjectType())
6656 Composite2 = Composite1;
6657 else if (Composite2->isVoidType() && Composite1->isObjectType())
6658 Composite1 = Composite2;
6659 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6660 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6661 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and
6662 // T1, respectively;
6663 //
6664 // The "similar type" handling covers all of this except for the "T1 is a
6665 // base class of T2" case in the definition of reference-related.
6666 else if (IsDerivedFrom(Loc, Composite1, Composite2))
6667 Composite1 = Composite2;
6668 else if (IsDerivedFrom(Loc, Composite2, Composite1))
6669 Composite2 = Composite1;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006670 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006671
Richard Smith9a6f4d42020-01-09 19:24:44 -08006672 // At this point, either the inner types are the same or we have failed to
6673 // find a composite pointer type.
6674 if (!Context.hasSameType(Composite1, Composite2))
6675 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006676
Richard Smith9a6f4d42020-01-09 19:24:44 -08006677 // Per C++ [conv.qual]p3, add 'const' to every level before the last
6678 // differing qualifier.
6679 for (unsigned I = 0; I != NeedConstBefore; ++I)
6680 Steps[I].Quals.addConst();
Mike Stump11289f42009-09-09 15:08:12 +00006681
Richard Smith9a6f4d42020-01-09 19:24:44 -08006682 // Rebuild the composite type.
6683 QualType Composite = Composite1;
6684 for (auto &S : llvm::reverse(Steps))
6685 Composite = S.rebuild(Context, Composite);
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006686
Richard Smith9a6f4d42020-01-09 19:24:44 -08006687 if (ConvertArgs) {
6688 // Convert the expressions to the composite pointer type.
6689 InitializedEntity Entity =
6690 InitializedEntity::InitializeTemporary(Composite);
6691 InitializationKind Kind =
6692 InitializationKind::CreateCopy(Loc, SourceLocation());
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006693
Richard Smith9a6f4d42020-01-09 19:24:44 -08006694 InitializationSequence E1ToC(*this, Entity, Kind, E1);
6695 if (!E1ToC)
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006696 return QualType();
Douglas Gregor19175ff2010-04-16 23:20:25 +00006697
Richard Smith9a6f4d42020-01-09 19:24:44 -08006698 InitializationSequence E2ToC(*this, Entity, Kind, E2);
6699 if (!E2ToC)
6700 return QualType();
6701
6702 // FIXME: Let the caller know if these fail to avoid duplicate diagnostics.
6703 ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1);
6704 if (E1Result.isInvalid())
6705 return QualType();
6706 E1 = E1Result.get();
6707
6708 ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2);
6709 if (E2Result.isInvalid())
6710 return QualType();
6711 E2 = E2Result.get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006712 }
6713
Richard Smith9a6f4d42020-01-09 19:24:44 -08006714 return Composite;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006715}
Anders Carlsson85a307d2009-05-17 18:41:29 +00006716
John McCalldadc5752010-08-24 06:29:42 +00006717ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00006718 if (!E)
6719 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006720
John McCall31168b02011-06-15 23:02:42 +00006721 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6722
6723 // If the result is a glvalue, we shouldn't bind it.
6724 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006725 return E;
Mike Stump11289f42009-09-09 15:08:12 +00006726
John McCall31168b02011-06-15 23:02:42 +00006727 // In ARC, calls that return a retainable type can return retained,
6728 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006729 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00006730 E->getType()->isObjCRetainableType()) {
6731
6732 bool ReturnsRetained;
6733
6734 // For actual calls, we compute this by examining the type of the
6735 // called value.
6736 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6737 Expr *Callee = Call->getCallee()->IgnoreParens();
6738 QualType T = Callee->getType();
6739
6740 if (T == Context.BoundMemberTy) {
6741 // Handle pointer-to-members.
6742 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6743 T = BinOp->getRHS()->getType();
6744 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6745 T = Mem->getMemberDecl()->getType();
6746 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006747
John McCall31168b02011-06-15 23:02:42 +00006748 if (const PointerType *Ptr = T->getAs<PointerType>())
6749 T = Ptr->getPointeeType();
6750 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6751 T = Ptr->getPointeeType();
6752 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6753 T = MemPtr->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006754
John McCall31168b02011-06-15 23:02:42 +00006755 const FunctionType *FTy = T->getAs<FunctionType>();
6756 assert(FTy && "call to value not of function type?");
6757 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6758
6759 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6760 // type always produce a +1 object.
6761 } else if (isa<StmtExpr>(E)) {
6762 ReturnsRetained = true;
6763
Ted Kremeneke65b0862012-03-06 20:05:56 +00006764 // We hit this case with the lambda conversion-to-block optimization;
6765 // we don't want any extra casts here.
6766 } else if (isa<CastExpr>(E) &&
6767 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006768 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006769
John McCall31168b02011-06-15 23:02:42 +00006770 // For message sends and property references, we try to find an
6771 // actual method. FIXME: we should infer retention by selector in
6772 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00006773 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00006774 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006775 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6776 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00006777 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6778 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00006779 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006780 // Don't do reclaims if we're using the zero-element array
6781 // constant.
6782 if (ArrayLit->getNumElements() == 0 &&
6783 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6784 return E;
6785
Ted Kremeneke65b0862012-03-06 20:05:56 +00006786 D = ArrayLit->getArrayWithObjectsMethod();
6787 } else if (ObjCDictionaryLiteral *DictLit
6788 = dyn_cast<ObjCDictionaryLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006789 // Don't do reclaims if we're using the zero-element dictionary
6790 // constant.
6791 if (DictLit->getNumElements() == 0 &&
6792 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6793 return E;
6794
Ted Kremeneke65b0862012-03-06 20:05:56 +00006795 D = DictLit->getDictWithObjectsMethod();
6796 }
John McCall31168b02011-06-15 23:02:42 +00006797
6798 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00006799
6800 // Don't do reclaims on performSelector calls; despite their
6801 // return type, the invoked method doesn't necessarily actually
6802 // return an object.
6803 if (!ReturnsRetained &&
6804 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006805 return E;
John McCall31168b02011-06-15 23:02:42 +00006806 }
6807
John McCall16de4d22011-11-14 19:53:16 +00006808 // Don't reclaim an object of Class type.
6809 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006810 return E;
John McCall16de4d22011-11-14 19:53:16 +00006811
Tim Shen4a05bb82016-06-21 20:29:17 +00006812 Cleanup.setExprNeedsCleanups(true);
John McCall4db5c3c2011-07-07 06:58:02 +00006813
John McCall2d637d22011-09-10 06:18:15 +00006814 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6815 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006816 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6817 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00006818 }
6819
David Blaikiebbafb8a2012-03-11 07:00:24 +00006820 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006821 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00006822
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006823 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6824 // a fast path for the common case that the type is directly a RecordType.
6825 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00006826 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006827 while (!RT) {
6828 switch (T->getTypeClass()) {
6829 case Type::Record:
6830 RT = cast<RecordType>(T);
6831 break;
6832 case Type::ConstantArray:
6833 case Type::IncompleteArray:
6834 case Type::VariableArray:
6835 case Type::DependentSizedArray:
6836 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6837 break;
6838 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006839 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006840 }
6841 }
Mike Stump11289f42009-09-09 15:08:12 +00006842
Richard Smithfd555f62012-02-22 02:04:18 +00006843 // That should be enough to guarantee that this type is complete, if we're
6844 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00006845 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00006846 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006847 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006848
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006849 bool IsDecltype = ExprEvalContexts.back().ExprContext ==
6850 ExpressionEvaluationContextRecord::EK_Decltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00006851 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00006852
John McCall31168b02011-06-15 23:02:42 +00006853 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00006854 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00006855 CheckDestructorAccess(E->getExprLoc(), Destructor,
6856 PDiag(diag::err_access_dtor_temp)
6857 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006858 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6859 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00006860
Richard Smithfd555f62012-02-22 02:04:18 +00006861 // If destructor is trivial, we can avoid the extra copy.
6862 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006863 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00006864
John McCall28fc7092011-11-10 05:35:25 +00006865 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006866 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006867 }
Richard Smitheec915d62012-02-18 04:13:32 +00006868
6869 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00006870 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6871
6872 if (IsDecltype)
6873 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6874
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006875 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00006876}
6877
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006878ExprResult
John McCall5d413782010-12-06 08:20:24 +00006879Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006880 if (SubExpr.isInvalid())
6881 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006882
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006883 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006884}
6885
John McCall28fc7092011-11-10 05:35:25 +00006886Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00006887 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00006888
Eli Friedman3bda6b12012-02-02 23:15:15 +00006889 CleanupVarDeclMarking();
6890
John McCall28fc7092011-11-10 05:35:25 +00006891 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6892 assert(ExprCleanupObjects.size() >= FirstCleanup);
Tim Shen4a05bb82016-06-21 20:29:17 +00006893 assert(Cleanup.exprNeedsCleanups() ||
6894 ExprCleanupObjects.size() == FirstCleanup);
6895 if (!Cleanup.exprNeedsCleanups())
John McCall28fc7092011-11-10 05:35:25 +00006896 return SubExpr;
6897
Craig Topper5fc8fc22014-08-27 06:28:36 +00006898 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6899 ExprCleanupObjects.size() - FirstCleanup);
John McCall28fc7092011-11-10 05:35:25 +00006900
Tim Shen4a05bb82016-06-21 20:29:17 +00006901 auto *E = ExprWithCleanups::Create(
6902 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
John McCall28fc7092011-11-10 05:35:25 +00006903 DiscardCleanupsInEvaluationContext();
6904
6905 return E;
6906}
6907
John McCall5d413782010-12-06 08:20:24 +00006908Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00006909 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006910
Eli Friedman3bda6b12012-02-02 23:15:15 +00006911 CleanupVarDeclMarking();
6912
Tim Shen4a05bb82016-06-21 20:29:17 +00006913 if (!Cleanup.exprNeedsCleanups())
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006914 return SubStmt;
6915
6916 // FIXME: In order to attach the temporaries, wrap the statement into
6917 // a StmtExpr; currently this is only used for asm statements.
6918 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6919 // a new AsmStmtWithTemporaries.
Benjamin Kramer07420902017-12-24 16:24:20 +00006920 CompoundStmt *CompStmt = CompoundStmt::Create(
6921 Context, SubStmt, SourceLocation(), SourceLocation());
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006922 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6923 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00006924 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006925}
6926
Richard Smithfd555f62012-02-22 02:04:18 +00006927/// Process the expression contained within a decltype. For such expressions,
6928/// certain semantic checks on temporaries are delayed until this point, and
6929/// are omitted for the 'topmost' call in the decltype expression. If the
6930/// topmost call bound a temporary, strip that temporary off the expression.
6931ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006932 assert(ExprEvalContexts.back().ExprContext ==
6933 ExpressionEvaluationContextRecord::EK_Decltype &&
6934 "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00006935
Akira Hatanaka0a848562019-01-10 20:12:16 +00006936 ExprResult Result = CheckPlaceholderExpr(E);
6937 if (Result.isInvalid())
6938 return ExprError();
6939 E = Result.get();
6940
Richard Smithfd555f62012-02-22 02:04:18 +00006941 // C++11 [expr.call]p11:
6942 // If a function call is a prvalue of object type,
6943 // -- if the function call is either
6944 // -- the operand of a decltype-specifier, or
6945 // -- the right operand of a comma operator that is the operand of a
6946 // decltype-specifier,
6947 // a temporary object is not introduced for the prvalue.
6948
6949 // Recursively rebuild ParenExprs and comma expressions to strip out the
6950 // outermost CXXBindTemporaryExpr, if any.
6951 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6952 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6953 if (SubExpr.isInvalid())
6954 return ExprError();
6955 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006956 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006957 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00006958 }
6959 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6960 if (BO->getOpcode() == BO_Comma) {
6961 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6962 if (RHS.isInvalid())
6963 return ExprError();
6964 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006965 return E;
6966 return new (Context) BinaryOperator(
6967 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
Adam Nemet484aa452017-03-27 19:17:25 +00006968 BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
Richard Smithfd555f62012-02-22 02:04:18 +00006969 }
6970 }
6971
6972 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00006973 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6974 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00006975 if (TopCall)
6976 E = TopCall;
6977 else
Craig Topperc3ec1492014-05-26 06:22:03 +00006978 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00006979
6980 // Disable the special decltype handling now.
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006981 ExprEvalContexts.back().ExprContext =
6982 ExpressionEvaluationContextRecord::EK_Other;
Richard Smithfd555f62012-02-22 02:04:18 +00006983
Richard Smith4a6861a2019-10-09 02:04:54 +00006984 Result = CheckUnevaluatedOperand(E);
6985 if (Result.isInvalid())
6986 return ExprError();
6987 E = Result.get();
6988
Richard Smithf86b0ae2012-07-28 19:54:11 +00006989 // In MS mode, don't perform any extra checking of call return types within a
6990 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00006991 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006992 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00006993
Richard Smithfd555f62012-02-22 02:04:18 +00006994 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006995 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6996 I != N; ++I) {
6997 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006998 if (Call == TopCall)
6999 continue;
7000
David Majnemerced8bdf2015-02-25 17:36:15 +00007001 if (CheckCallReturnType(Call->getCallReturnType(Context),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007002 Call->getBeginLoc(), Call, Call->getDirectCallee()))
Richard Smithfd555f62012-02-22 02:04:18 +00007003 return ExprError();
7004 }
7005
7006 // Now all relevant types are complete, check the destructors are accessible
7007 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00007008 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
7009 I != N; ++I) {
7010 CXXBindTemporaryExpr *Bind =
7011 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00007012 if (Bind == TopBind)
7013 continue;
7014
7015 CXXTemporary *Temp = Bind->getTemporary();
7016
7017 CXXRecordDecl *RD =
7018 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7019 CXXDestructorDecl *Destructor = LookupDestructor(RD);
7020 Temp->setDestructor(Destructor);
7021
Richard Smith7d847b12012-05-11 22:20:10 +00007022 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
7023 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00007024 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00007025 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00007026 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
7027 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00007028
7029 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00007030 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00007031 }
7032
7033 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007034 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00007035}
7036
Richard Smith79c927b2013-11-06 19:31:51 +00007037/// Note a set of 'operator->' functions that were used for a member access.
7038static void noteOperatorArrows(Sema &S,
Craig Topper00bbdcf2014-06-28 23:22:23 +00007039 ArrayRef<FunctionDecl *> OperatorArrows) {
Richard Smith79c927b2013-11-06 19:31:51 +00007040 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
7041 // FIXME: Make this configurable?
7042 unsigned Limit = 9;
7043 if (OperatorArrows.size() > Limit) {
7044 // Produce Limit-1 normal notes and one 'skipping' note.
7045 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
7046 SkipCount = OperatorArrows.size() - (Limit - 1);
7047 }
7048
7049 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
7050 if (I == SkipStart) {
7051 S.Diag(OperatorArrows[I]->getLocation(),
7052 diag::note_operator_arrows_suppressed)
7053 << SkipCount;
7054 I += SkipCount;
7055 } else {
7056 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
7057 << OperatorArrows[I]->getCallResultType();
7058 ++I;
7059 }
7060 }
7061}
7062
Nico Weber964d3322015-02-16 22:35:45 +00007063ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
7064 SourceLocation OpLoc,
7065 tok::TokenKind OpKind,
7066 ParsedType &ObjectType,
7067 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00007068 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00007069 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00007070 if (Result.isInvalid()) return ExprError();
7071 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00007072
John McCall526ab472011-10-25 17:37:35 +00007073 Result = CheckPlaceholderExpr(Base);
7074 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007075 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00007076
John McCallb268a282010-08-23 23:25:46 +00007077 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00007078 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00007079 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00007080 // If we have a pointer to a dependent type and are using the -> operator,
7081 // the object type is the type that the pointer points to. We might still
7082 // have enough information about that type to do something useful.
7083 if (OpKind == tok::arrow)
7084 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
7085 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007086
John McCallba7bf592010-08-24 05:47:05 +00007087 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00007088 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007089 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00007090 }
Mike Stump11289f42009-09-09 15:08:12 +00007091
Douglas Gregorb7bfe792009-09-02 22:59:36 +00007092 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00007093 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00007094 // returned, with the original second operand.
7095 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00007096 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00007097 bool NoArrowOperatorFound = false;
7098 bool FirstIteration = true;
7099 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00007100 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00007101 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00007102 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00007103 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007104
Douglas Gregorb7bfe792009-09-02 22:59:36 +00007105 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00007106 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
7107 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00007108 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00007109 noteOperatorArrows(*this, OperatorArrows);
7110 Diag(OpLoc, diag::note_operator_arrow_depth)
7111 << getLangOpts().ArrowDepth;
7112 return ExprError();
7113 }
7114
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00007115 Result = BuildOverloadedArrowExpr(
7116 S, Base, OpLoc,
7117 // When in a template specialization and on the first loop iteration,
7118 // potentially give the default diagnostic (with the fixit in a
7119 // separate note) instead of having the error reported back to here
7120 // and giving a diagnostic with a fixit attached to the error itself.
7121 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00007122 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00007123 : &NoArrowOperatorFound);
7124 if (Result.isInvalid()) {
7125 if (NoArrowOperatorFound) {
7126 if (FirstIteration) {
7127 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00007128 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00007129 << FixItHint::CreateReplacement(OpLoc, ".");
7130 OpKind = tok::period;
7131 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00007132 }
7133 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
7134 << BaseType << Base->getSourceRange();
7135 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00007136 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007137 Diag(CD->getBeginLoc(),
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00007138 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00007139 }
7140 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00007141 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00007142 }
John McCallb268a282010-08-23 23:25:46 +00007143 Base = Result.get();
7144 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00007145 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00007146 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00007147 CanQualType CBaseType = Context.getCanonicalType(BaseType);
David Blaikie82e95a32014-11-19 07:49:47 +00007148 if (!CTypes.insert(CBaseType).second) {
Richard Smith79c927b2013-11-06 19:31:51 +00007149 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
7150 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00007151 return ExprError();
7152 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00007153 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00007154 }
Mike Stump11289f42009-09-09 15:08:12 +00007155
Richard Smith89009442019-05-09 22:22:48 +00007156 if (OpKind == tok::arrow) {
7157 if (BaseType->isPointerType())
7158 BaseType = BaseType->getPointeeType();
7159 else if (auto *AT = Context.getAsArrayType(BaseType))
7160 BaseType = AT->getElementType();
7161 }
Douglas Gregore4f764f2009-11-20 19:58:21 +00007162 }
Mike Stump11289f42009-09-09 15:08:12 +00007163
Douglas Gregorbf3a8262012-01-12 16:11:24 +00007164 // Objective-C properties allow "." access on Objective-C pointer types,
7165 // so adjust the base type to the object type itself.
7166 if (BaseType->isObjCObjectPointerType())
7167 BaseType = BaseType->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007168
Douglas Gregorbf3a8262012-01-12 16:11:24 +00007169 // C++ [basic.lookup.classref]p2:
7170 // [...] If the type of the object expression is of pointer to scalar
7171 // type, the unqualified-id is looked up in the context of the complete
7172 // postfix-expression.
7173 //
7174 // This also indicates that we could be parsing a pseudo-destructor-name.
7175 // Note that Objective-C class and object types can be pseudo-destructor
John McCall9d145df2015-12-14 19:12:54 +00007176 // expressions or normal member (ivar or property) access expressions, and
7177 // it's legal for the type to be incomplete if this is a pseudo-destructor
7178 // call. We'll do more incomplete-type checks later in the lookup process,
7179 // so just skip this check for ObjC types.
Richard Smith9e77f522019-08-14 22:57:50 +00007180 if (!BaseType->isRecordType()) {
John McCall9d145df2015-12-14 19:12:54 +00007181 ObjectType = ParsedType::make(BaseType);
Douglas Gregorbf3a8262012-01-12 16:11:24 +00007182 MayBePseudoDestructor = true;
John McCall9d145df2015-12-14 19:12:54 +00007183 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00007184 }
Mike Stump11289f42009-09-09 15:08:12 +00007185
Douglas Gregor3024f072012-04-16 07:05:22 +00007186 // The object type must be complete (or dependent), or
7187 // C++11 [expr.prim.general]p3:
7188 // Unlike the object expression in other contexts, *this is not required to
Simon Pilgrim75c26882016-09-30 14:25:09 +00007189 // be of complete type for purposes of class member access (5.2.5) outside
Douglas Gregor3024f072012-04-16 07:05:22 +00007190 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00007191 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00007192 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007193 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00007194 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007195
Douglas Gregor2b6ca462009-09-03 21:38:09 +00007196 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00007197 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00007198 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00007199 // type C (or of pointer to a class type C), the unqualified-id is looked
7200 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00007201 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007202 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00007203}
7204
Simon Pilgrim75c26882016-09-30 14:25:09 +00007205static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00007206 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00007207 if (Base->hasPlaceholderType()) {
7208 ExprResult result = S.CheckPlaceholderExpr(Base);
7209 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007210 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00007211 }
7212 ObjectType = Base->getType();
7213
David Blaikie1d578782011-12-16 16:03:09 +00007214 // C++ [expr.pseudo]p2:
7215 // The left-hand side of the dot operator shall be of scalar type. The
7216 // left-hand side of the arrow operator shall be of pointer to scalar type.
7217 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00007218 // Note that this is rather different from the normal handling for the
7219 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00007220 if (OpKind == tok::arrow) {
7221 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
7222 ObjectType = Ptr->getPointeeType();
7223 } else if (!Base->isTypeDependent()) {
Nico Webera6916892016-06-10 18:53:04 +00007224 // The user wrote "p->" when they probably meant "p."; fix it.
David Blaikie1d578782011-12-16 16:03:09 +00007225 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7226 << ObjectType << true
7227 << FixItHint::CreateReplacement(OpLoc, ".");
7228 if (S.isSFINAEContext())
7229 return true;
7230
7231 OpKind = tok::period;
7232 }
7233 }
7234
7235 return false;
7236}
7237
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007238/// Check if it's ok to try and recover dot pseudo destructor calls on
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00007239/// pointer objects.
7240static bool
7241canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
7242 QualType DestructedType) {
7243 // If this is a record type, check if its destructor is callable.
7244 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
Bruno Ricci4eb701c2019-01-24 13:52:47 +00007245 if (RD->hasDefinition())
7246 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
7247 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00007248 return false;
7249 }
7250
7251 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
7252 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
7253 DestructedType->isVectorType();
7254}
7255
John McCalldadc5752010-08-24 06:29:42 +00007256ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00007257 SourceLocation OpLoc,
7258 tok::TokenKind OpKind,
7259 const CXXScopeSpec &SS,
7260 TypeSourceInfo *ScopeTypeInfo,
7261 SourceLocation CCLoc,
7262 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007263 PseudoDestructorTypeStorage Destructed) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00007264 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007265
Eli Friedman0ce4de42012-01-25 04:35:06 +00007266 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00007267 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7268 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007269
Douglas Gregorc5c57342012-09-10 14:57:06 +00007270 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
7271 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00007272 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00007273 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00007274 else {
Nico Weber58829272012-01-23 05:50:57 +00007275 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
7276 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00007277 return ExprError();
7278 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007279 }
7280
7281 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007282 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007283 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00007284 if (DestructedTypeInfo) {
7285 QualType DestructedType = DestructedTypeInfo->getType();
7286 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00007287 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00007288 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
7289 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00007290 // Detect dot pseudo destructor calls on pointer objects, e.g.:
7291 // Foo *foo;
7292 // foo.~Foo();
7293 if (OpKind == tok::period && ObjectType->isPointerType() &&
7294 Context.hasSameUnqualifiedType(DestructedType,
7295 ObjectType->getPointeeType())) {
7296 auto Diagnostic =
7297 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7298 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007299
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00007300 // Issue a fixit only when the destructor is valid.
7301 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
7302 *this, DestructedType))
7303 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
7304
7305 // Recover by setting the object type to the destructed type and the
7306 // operator to '->'.
7307 ObjectType = DestructedType;
7308 OpKind = tok::arrow;
7309 } else {
7310 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
7311 << ObjectType << DestructedType << Base->getSourceRange()
7312 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
7313
7314 // Recover by setting the destructed type to the object type.
7315 DestructedType = ObjectType;
7316 DestructedTypeInfo =
7317 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
7318 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7319 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007320 } else if (DestructedType.getObjCLifetime() !=
John McCall31168b02011-06-15 23:02:42 +00007321 ObjectType.getObjCLifetime()) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00007322
John McCall31168b02011-06-15 23:02:42 +00007323 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
7324 // Okay: just pretend that the user provided the correctly-qualified
7325 // type.
7326 } else {
7327 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
7328 << ObjectType << DestructedType << Base->getSourceRange()
7329 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
7330 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007331
John McCall31168b02011-06-15 23:02:42 +00007332 // Recover by setting the destructed type to the object type.
7333 DestructedType = ObjectType;
7334 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
7335 DestructedTypeStart);
7336 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7337 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00007338 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007339 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007340
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007341 // C++ [expr.pseudo]p2:
7342 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
7343 // form
7344 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007345 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007346 //
7347 // shall designate the same scalar type.
7348 if (ScopeTypeInfo) {
7349 QualType ScopeType = ScopeTypeInfo->getType();
7350 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00007351 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007352
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00007353 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007354 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00007355 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00007356 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007357
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007358 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00007359 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007360 }
7361 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007362
John McCallb268a282010-08-23 23:25:46 +00007363 Expr *Result
7364 = new (Context) CXXPseudoDestructorExpr(Context, Base,
7365 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00007366 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00007367 ScopeTypeInfo,
7368 CCLoc,
7369 TildeLoc,
7370 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007371
David Majnemerced8bdf2015-02-25 17:36:15 +00007372 return Result;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007373}
7374
John McCalldadc5752010-08-24 06:29:42 +00007375ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00007376 SourceLocation OpLoc,
7377 tok::TokenKind OpKind,
7378 CXXScopeSpec &SS,
7379 UnqualifiedId &FirstTypeName,
7380 SourceLocation CCLoc,
7381 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007382 UnqualifiedId &SecondTypeName) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00007383 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7384 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007385 "Invalid first type name in pseudo-destructor");
Faisal Vali2ab8c152017-12-30 04:15:27 +00007386 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7387 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007388 "Invalid second type name in pseudo-destructor");
7389
Eli Friedman0ce4de42012-01-25 04:35:06 +00007390 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00007391 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7392 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00007393
7394 // Compute the object type that we should use for name lookup purposes. Only
7395 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00007396 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00007397 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00007398 if (ObjectType->isRecordType())
7399 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00007400 else if (ObjectType->isDependentType())
7401 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00007402 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007403
7404 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007405 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007406 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00007407 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00007408 PseudoDestructorTypeStorage Destructed;
Faisal Vali2ab8c152017-12-30 04:15:27 +00007409 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007410 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00007411 SecondTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00007412 S, &SS, true, false, ObjectTypePtrForLookup,
7413 /*IsCtorOrDtorName*/true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007414 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00007415 ((SS.isSet() && !computeDeclContext(SS, false)) ||
7416 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007417 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00007418 // couldn't find anything useful in scope. Just store the identifier and
7419 // it's location, and we'll perform (qualified) name lookup again at
7420 // template instantiation time.
7421 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
7422 SecondTypeName.StartLocation);
7423 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007424 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007425 diag::err_pseudo_dtor_destructor_non_type)
7426 << SecondTypeName.Identifier << ObjectType;
7427 if (isSFINAEContext())
7428 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007429
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007430 // Recover by assuming we had the right type all along.
7431 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007432 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007433 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007434 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007435 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007436 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007437 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007438 TemplateId->NumArgs);
Richard Smithb23c5e82019-05-09 03:31:27 +00007439 TypeResult T = ActOnTemplateIdType(S,
Richard Smitha42fd842020-01-17 15:42:11 -08007440 SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007441 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00007442 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00007443 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007444 TemplateId->TemplateNameLoc,
7445 TemplateId->LAngleLoc,
7446 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00007447 TemplateId->RAngleLoc,
7448 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007449 if (T.isInvalid() || !T.get()) {
7450 // Recover by assuming we had the right type all along.
7451 DestructedType = ObjectType;
7452 } else
7453 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007454 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007455
7456 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007457 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00007458 if (!DestructedType.isNull()) {
7459 if (!DestructedTypeInfo)
7460 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007461 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00007462 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7463 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007464
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007465 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00007466 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007467 QualType ScopeType;
Faisal Vali2ab8c152017-12-30 04:15:27 +00007468 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007469 FirstTypeName.Identifier) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00007470 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007471 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00007472 FirstTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00007473 S, &SS, true, false, ObjectTypePtrForLookup,
7474 /*IsCtorOrDtorName*/true);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007475 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007476 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007477 diag::err_pseudo_dtor_destructor_non_type)
7478 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007479
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007480 if (isSFINAEContext())
7481 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007482
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007483 // Just drop this type. It's unnecessary anyway.
7484 ScopeType = QualType();
7485 } else
7486 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007487 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007488 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007489 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007490 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007491 TemplateId->NumArgs);
Richard Smithb23c5e82019-05-09 03:31:27 +00007492 TypeResult T = ActOnTemplateIdType(S,
Richard Smitha42fd842020-01-17 15:42:11 -08007493 SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007494 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00007495 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00007496 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007497 TemplateId->TemplateNameLoc,
7498 TemplateId->LAngleLoc,
7499 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00007500 TemplateId->RAngleLoc,
7501 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007502 if (T.isInvalid() || !T.get()) {
7503 // Recover by dropping this type.
7504 ScopeType = QualType();
7505 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007506 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007507 }
7508 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007509
Douglas Gregor90ad9222010-02-24 23:02:30 +00007510 if (!ScopeType.isNull() && !ScopeTypeInfo)
7511 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
7512 FirstTypeName.StartLocation);
7513
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007514
John McCallb268a282010-08-23 23:25:46 +00007515 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00007516 ScopeTypeInfo, CCLoc, TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007517 Destructed);
Douglas Gregore610ada2010-02-24 18:44:31 +00007518}
7519
David Blaikie1d578782011-12-16 16:03:09 +00007520ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7521 SourceLocation OpLoc,
7522 tok::TokenKind OpKind,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007523 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007524 const DeclSpec& DS) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00007525 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00007526 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7527 return ExprError();
7528
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00007529 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
7530 false);
David Blaikie1d578782011-12-16 16:03:09 +00007531
7532 TypeLocBuilder TLB;
7533 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
7534 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
7535 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
7536 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
7537
7538 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00007539 nullptr, SourceLocation(), TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007540 Destructed);
David Blaikie1d578782011-12-16 16:03:09 +00007541}
7542
John Wiegley01296292011-04-08 18:41:53 +00007543ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00007544 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007545 bool HadMultipleCandidates) {
Richard Smith7ed5fb22018-07-27 17:13:18 +00007546 // Convert the expression to match the conversion function's implicit object
7547 // parameter.
7548 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
7549 FoundDecl, Method);
7550 if (Exp.isInvalid())
7551 return true;
7552
Eli Friedman98b01ed2012-03-01 04:01:32 +00007553 if (Method->getParent()->isLambda() &&
7554 Method->getConversionType()->isBlockPointerType()) {
Jan Korouse72321f2019-07-23 16:54:11 +00007555 // This is a lambda conversion to block pointer; check if the argument
Richard Smith7ed5fb22018-07-27 17:13:18 +00007556 // was a LambdaExpr.
Eli Friedman98b01ed2012-03-01 04:01:32 +00007557 Expr *SubE = E;
7558 CastExpr *CE = dyn_cast<CastExpr>(SubE);
7559 if (CE && CE->getCastKind() == CK_NoOp)
7560 SubE = CE->getSubExpr();
7561 SubE = SubE->IgnoreParens();
7562 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
7563 SubE = BE->getSubExpr();
7564 if (isa<LambdaExpr>(SubE)) {
7565 // For the conversion to block pointer on a lambda expression, we
7566 // construct a special BlockLiteral instead; this doesn't really make
7567 // a difference in ARC, but outside of ARC the resulting block literal
7568 // follows the normal lifetime rules for block literals instead of being
7569 // autoreleased.
7570 DiagnosticErrorTrap Trap(Diags);
Faisal Valid143a0c2017-04-01 21:30:49 +00007571 PushExpressionEvaluationContext(
7572 ExpressionEvaluationContext::PotentiallyEvaluated);
Richard Smith7ed5fb22018-07-27 17:13:18 +00007573 ExprResult BlockExp = BuildBlockForLambdaConversion(
7574 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
Akira Hatanakac482acd2016-05-04 18:07:20 +00007575 PopExpressionEvaluationContext();
7576
Richard Smith7ed5fb22018-07-27 17:13:18 +00007577 if (BlockExp.isInvalid())
7578 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
7579 return BlockExp;
Eli Friedman98b01ed2012-03-01 04:01:32 +00007580 }
7581 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00007582
Richard Smith84be9982019-06-06 23:24:18 +00007583 MemberExpr *ME =
7584 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
7585 NestedNameSpecifierLoc(), SourceLocation(), Method,
7586 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
7587 HadMultipleCandidates, DeclarationNameInfo(),
7588 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007589
Alp Toker314cc812014-01-25 16:55:45 +00007590 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00007591 ExprValueKind VK = Expr::getValueKindForType(ResultType);
7592 ResultType = ResultType.getNonLValueExprType(Context);
7593
Bruno Riccic5885cf2018-12-21 15:20:32 +00007594 CXXMemberCallExpr *CE = CXXMemberCallExpr::Create(
7595 Context, ME, /*Args=*/{}, ResultType, VK, Exp.get()->getEndLoc());
George Burgess IVce6284b2017-01-28 02:19:40 +00007596
7597 if (CheckFunctionCall(Method, CE,
7598 Method->getType()->castAs<FunctionProtoType>()))
7599 return ExprError();
7600
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007601 return CE;
7602}
7603
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007604ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
7605 SourceLocation RParen) {
Aaron Ballmanedc80842015-04-27 22:31:12 +00007606 // If the operand is an unresolved lookup expression, the expression is ill-
7607 // formed per [over.over]p1, because overloaded function names cannot be used
7608 // without arguments except in explicit contexts.
7609 ExprResult R = CheckPlaceholderExpr(Operand);
7610 if (R.isInvalid())
7611 return R;
7612
Richard Smith4a6861a2019-10-09 02:04:54 +00007613 R = CheckUnevaluatedOperand(R.get());
7614 if (R.isInvalid())
7615 return ExprError();
7616
Aaron Ballmanedc80842015-04-27 22:31:12 +00007617 Operand = R.get();
7618
Richard Smith51ec0cf2017-02-21 01:17:38 +00007619 if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00007620 // The expression operand for noexcept is in an unevaluated expression
7621 // context, so side effects could result in unintended consequences.
7622 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7623 }
7624
Richard Smithf623c962012-04-17 00:58:00 +00007625 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007626 return new (Context)
7627 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007628}
7629
7630ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
7631 Expr *Operand, SourceLocation RParen) {
7632 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00007633}
7634
Eli Friedmanf798f652012-05-24 22:04:19 +00007635static bool IsSpecialDiscardedValue(Expr *E) {
7636 // In C++11, discarded-value expressions of a certain form are special,
7637 // according to [expr]p10:
7638 // The lvalue-to-rvalue conversion (4.1) is applied only if the
7639 // expression is an lvalue of volatile-qualified type and it has
7640 // one of the following forms:
7641 E = E->IgnoreParens();
7642
Eli Friedmanc49c2262012-05-24 22:36:31 +00007643 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007644 if (isa<DeclRefExpr>(E))
7645 return true;
7646
Eli Friedmanc49c2262012-05-24 22:36:31 +00007647 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007648 if (isa<ArraySubscriptExpr>(E))
7649 return true;
7650
Eli Friedmanc49c2262012-05-24 22:36:31 +00007651 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007652 if (isa<MemberExpr>(E))
7653 return true;
7654
Eli Friedmanc49c2262012-05-24 22:36:31 +00007655 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007656 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
7657 if (UO->getOpcode() == UO_Deref)
7658 return true;
7659
7660 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00007661 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007662 if (BO->isPtrMemOp())
7663 return true;
7664
Eli Friedmanc49c2262012-05-24 22:36:31 +00007665 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00007666 if (BO->getOpcode() == BO_Comma)
7667 return IsSpecialDiscardedValue(BO->getRHS());
7668 }
7669
Eli Friedmanc49c2262012-05-24 22:36:31 +00007670 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00007671 // operands are one of the above, or
7672 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
7673 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
7674 IsSpecialDiscardedValue(CO->getFalseExpr());
7675 // The related edge case of "*x ?: *x".
7676 if (BinaryConditionalOperator *BCO =
7677 dyn_cast<BinaryConditionalOperator>(E)) {
7678 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
7679 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
7680 IsSpecialDiscardedValue(BCO->getFalseExpr());
7681 }
7682
7683 // Objective-C++ extensions to the rule.
7684 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
7685 return true;
7686
7687 return false;
7688}
7689
John McCall34376a62010-12-04 03:47:34 +00007690/// Perform the conversions required for an expression used in a
7691/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00007692ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00007693 if (E->hasPlaceholderType()) {
7694 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007695 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007696 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00007697 }
7698
John McCallfee942d2010-12-02 02:07:15 +00007699 // C99 6.3.2.1:
7700 // [Except in specific positions,] an lvalue that does not have
7701 // array type is converted to the value stored in the
7702 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00007703 if (E->isRValue()) {
7704 // In C, function designators (i.e. expressions of function type)
7705 // are r-values, but we still want to do function-to-pointer decay
7706 // on them. This is both technically correct and convenient for
7707 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007708 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00007709 return DefaultFunctionArrayConversion(E);
7710
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007711 return E;
John McCalld68b2d02011-06-27 21:24:11 +00007712 }
John McCallfee942d2010-12-02 02:07:15 +00007713
Eli Friedmanf798f652012-05-24 22:04:19 +00007714 if (getLangOpts().CPlusPlus) {
7715 // The C++11 standard defines the notion of a discarded-value expression;
7716 // normally, we don't need to do anything to handle it, but if it is a
7717 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7718 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007719 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Richard Smith4a6861a2019-10-09 02:04:54 +00007720 E->getType().isVolatileQualified()) {
7721 if (IsSpecialDiscardedValue(E)) {
7722 ExprResult Res = DefaultLvalueConversion(E);
7723 if (Res.isInvalid())
7724 return E;
7725 E = Res.get();
7726 } else {
7727 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
7728 // it occurs as a discarded-value expression.
7729 CheckUnusedVolatileAssignment(E);
7730 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007731 }
Richard Smith122f88d2016-12-06 23:52:28 +00007732
7733 // C++1z:
7734 // If the expression is a prvalue after this optional conversion, the
7735 // temporary materialization conversion is applied.
7736 //
7737 // We skip this step: IR generation is able to synthesize the storage for
7738 // itself in the aggregate case, and adding the extra node to the AST is
7739 // just clutter.
7740 // FIXME: We don't emit lifetime markers for the temporaries due to this.
7741 // FIXME: Do any other AST consumers care about this?
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007742 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00007743 }
John McCall34376a62010-12-04 03:47:34 +00007744
7745 // GCC seems to also exclude expressions of incomplete enum type.
7746 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
7747 if (!T->getDecl()->isComplete()) {
7748 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007749 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007750 return E;
John McCall34376a62010-12-04 03:47:34 +00007751 }
7752 }
7753
John Wiegley01296292011-04-08 18:41:53 +00007754 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
7755 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007756 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007757 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00007758
John McCallca61b652010-12-04 12:29:11 +00007759 if (!E->getType()->isVoidType())
7760 RequireCompleteType(E->getExprLoc(), E->getType(),
7761 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007762 return E;
John McCall34376a62010-12-04 03:47:34 +00007763}
7764
Richard Smith4a6861a2019-10-09 02:04:54 +00007765ExprResult Sema::CheckUnevaluatedOperand(Expr *E) {
7766 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
7767 // it occurs as an unevaluated operand.
7768 CheckUnusedVolatileAssignment(E);
7769
7770 return E;
7771}
7772
Faisal Valia17d19f2013-11-07 05:17:06 +00007773// If we can unambiguously determine whether Var can never be used
7774// in a constant expression, return true.
7775// - if the variable and its initializer are non-dependent, then
7776// we can unambiguously check if the variable is a constant expression.
7777// - if the initializer is not value dependent - we can determine whether
7778// it can be used to initialize a constant expression. If Init can not
Simon Pilgrim75c26882016-09-30 14:25:09 +00007779// be used to initialize a constant expression we conclude that Var can
Faisal Valia17d19f2013-11-07 05:17:06 +00007780// never be a constant expression.
7781// - FXIME: if the initializer is dependent, we can still do some analysis and
7782// identify certain cases unambiguously as non-const by using a Visitor:
7783// - such as those that involve odr-use of a ParmVarDecl, involve a new
7784// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
Simon Pilgrim75c26882016-09-30 14:25:09 +00007785static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
Faisal Valia17d19f2013-11-07 05:17:06 +00007786 ASTContext &Context) {
7787 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007788 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007789
7790 // If there is no initializer - this can not be a constant expression.
7791 if (!Var->getAnyInitializer(DefVD)) return true;
7792 assert(DefVD);
7793 if (DefVD->isWeak()) return false;
7794 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00007795
Faisal Valia17d19f2013-11-07 05:17:06 +00007796 Expr *Init = cast<Expr>(Eval->Value);
7797
7798 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00007799 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7800 // of value-dependent expressions, and use it here to determine whether the
7801 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007802 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00007803 }
7804
Richard Smith715f7a12019-06-11 17:50:32 +00007805 return !Var->isUsableInConstantExpressions(Context);
Faisal Valia17d19f2013-11-07 05:17:06 +00007806}
7807
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007808/// Check if the current lambda has any potential captures
Simon Pilgrim75c26882016-09-30 14:25:09 +00007809/// that must be captured by any of its enclosing lambdas that are ready to
7810/// capture. If there is a lambda that can capture a nested
7811/// potential-capture, go ahead and do so. Also, check to see if any
7812/// variables are uncaptureable or do not involve an odr-use so do not
Faisal Valiab3d6462013-12-07 20:22:44 +00007813/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007814
Faisal Valiab3d6462013-12-07 20:22:44 +00007815static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7816 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7817
Simon Pilgrim75c26882016-09-30 14:25:09 +00007818 assert(!S.isUnevaluatedContext());
7819 assert(S.CurContext->isDependentContext());
Alexey Bataev31939e32016-11-11 12:36:20 +00007820#ifndef NDEBUG
7821 DeclContext *DC = S.CurContext;
7822 while (DC && isa<CapturedDecl>(DC))
7823 DC = DC->getParent();
7824 assert(
7825 CurrentLSI->CallOperator == DC &&
Faisal Valiab3d6462013-12-07 20:22:44 +00007826 "The current call operator must be synchronized with Sema's CurContext");
Alexey Bataev31939e32016-11-11 12:36:20 +00007827#endif // NDEBUG
Faisal Valiab3d6462013-12-07 20:22:44 +00007828
7829 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7830
Faisal Valiab3d6462013-12-07 20:22:44 +00007831 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00007832 // lambda (within a generic outer lambda), must be captured by an
7833 // outer lambda that is enclosed within a non-dependent context.
Richard Smith7bf8f6f2019-06-04 17:17:20 +00007834 CurrentLSI->visitPotentialCaptures([&] (VarDecl *Var, Expr *VarExpr) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007835 // If the variable is clearly identified as non-odr-used and the full
Simon Pilgrim75c26882016-09-30 14:25:09 +00007836 // expression is not instantiation dependent, only then do we not
Faisal Valiab3d6462013-12-07 20:22:44 +00007837 // need to check enclosing lambda's for speculative captures.
7838 // For e.g.:
7839 // Even though 'x' is not odr-used, it should be captured.
7840 // int test() {
7841 // const int x = 10;
7842 // auto L = [=](auto a) {
7843 // (void) +x + a;
7844 // };
7845 // }
7846 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00007847 !IsFullExprInstantiationDependent)
Richard Smith7bf8f6f2019-06-04 17:17:20 +00007848 return;
Faisal Valiab3d6462013-12-07 20:22:44 +00007849
7850 // If we have a capture-capable lambda for the variable, go ahead and
7851 // capture the variable in that lambda (and all its enclosing lambdas).
7852 if (const Optional<unsigned> Index =
7853 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Richard Smith94ef6862019-05-28 23:09:42 +00007854 S.FunctionScopes, Var, S))
7855 S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(),
7856 Index.getValue());
Simon Pilgrim75c26882016-09-30 14:25:09 +00007857 const bool IsVarNeverAConstantExpression =
Faisal Valia17d19f2013-11-07 05:17:06 +00007858 VariableCanNeverBeAConstantExpression(Var, S.Context);
7859 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7860 // This full expression is not instantiation dependent or the variable
Simon Pilgrim75c26882016-09-30 14:25:09 +00007861 // can not be used in a constant expression - which means
7862 // this variable must be odr-used here, so diagnose a
Faisal Valia17d19f2013-11-07 05:17:06 +00007863 // capture violation early, if the variable is un-captureable.
7864 // This is purely for diagnosing errors early. Otherwise, this
7865 // error would get diagnosed when the lambda becomes capture ready.
7866 QualType CaptureType, DeclRefType;
7867 SourceLocation ExprLoc = VarExpr->getExprLoc();
7868 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007869 /*EllipsisLoc*/ SourceLocation(),
7870 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007871 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00007872 // We will never be able to capture this variable, and we need
7873 // to be able to in any and all instantiations, so diagnose it.
7874 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007875 /*EllipsisLoc*/ SourceLocation(),
7876 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007877 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007878 }
7879 }
Richard Smith7bf8f6f2019-06-04 17:17:20 +00007880 });
Faisal Valia17d19f2013-11-07 05:17:06 +00007881
Faisal Valiab3d6462013-12-07 20:22:44 +00007882 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007883 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007884 // If we have a capture-capable lambda for 'this', go ahead and capture
7885 // 'this' in that lambda (and all its enclosing lambdas).
7886 if (const Optional<unsigned> Index =
7887 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Reid Kleckner87a31802018-03-12 21:43:02 +00007888 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007889 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7890 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7891 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7892 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00007893 }
7894 }
Faisal Valiab3d6462013-12-07 20:22:44 +00007895
7896 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007897 CurrentLSI->clearPotentialCaptures();
7898}
7899
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007900static ExprResult attemptRecovery(Sema &SemaRef,
7901 const TypoCorrectionConsumer &Consumer,
Benjamin Kramer7320b992016-06-15 14:20:56 +00007902 const TypoCorrection &TC) {
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007903 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7904 Consumer.getLookupResult().getLookupKind());
7905 const CXXScopeSpec *SS = Consumer.getSS();
7906 CXXScopeSpec NewSS;
7907
7908 // Use an approprate CXXScopeSpec for building the expr.
7909 if (auto *NNS = TC.getCorrectionSpecifier())
7910 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7911 else if (SS && !TC.WillReplaceSpecifier())
7912 NewSS = *SS;
7913
Richard Smithde6d6c42015-12-29 19:43:10 +00007914 if (auto *ND = TC.getFoundDecl()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007915 R.setLookupName(ND->getDeclName());
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007916 R.addDecl(ND);
7917 if (ND->isCXXClassMember()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007918 // Figure out the correct naming class to add to the LookupResult.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007919 CXXRecordDecl *Record = nullptr;
7920 if (auto *NNS = TC.getCorrectionSpecifier())
7921 Record = NNS->getAsType()->getAsCXXRecordDecl();
7922 if (!Record)
Olivier Goffarted13fab2015-01-09 09:37:26 +00007923 Record =
7924 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7925 if (Record)
7926 R.setNamingClass(Record);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007927
7928 // Detect and handle the case where the decl might be an implicit
7929 // member.
7930 bool MightBeImplicitMember;
7931 if (!Consumer.isAddressOfOperand())
7932 MightBeImplicitMember = true;
7933 else if (!NewSS.isEmpty())
7934 MightBeImplicitMember = false;
7935 else if (R.isOverloadedResult())
7936 MightBeImplicitMember = false;
7937 else if (R.isUnresolvableResult())
7938 MightBeImplicitMember = true;
7939 else
7940 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7941 isa<IndirectFieldDecl>(ND) ||
7942 isa<MSPropertyDecl>(ND);
7943
7944 if (MightBeImplicitMember)
7945 return SemaRef.BuildPossibleImplicitMemberExpr(
7946 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00007947 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007948 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7949 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7950 Ivar->getIdentifier());
7951 }
7952 }
7953
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00007954 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7955 /*AcceptInvalidDecl*/ true);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007956}
7957
Kaelyn Takata6c759512014-10-27 18:07:37 +00007958namespace {
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007959class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7960 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7961
7962public:
7963 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7964 : TypoExprs(TypoExprs) {}
7965 bool VisitTypoExpr(TypoExpr *TE) {
7966 TypoExprs.insert(TE);
7967 return true;
7968 }
7969};
7970
Kaelyn Takata6c759512014-10-27 18:07:37 +00007971class TransformTypos : public TreeTransform<TransformTypos> {
7972 typedef TreeTransform<TransformTypos> BaseTransform;
7973
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007974 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7975 // process of being initialized.
Kaelyn Takata49d84322014-11-11 23:26:56 +00007976 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007977 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007978 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007979 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007980
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007981 /// Emit diagnostics for all of the TypoExprs encountered.
David Goldmanfd4d7772019-08-20 19:03:15 +00007982 ///
Kaelyn Takata6c759512014-10-27 18:07:37 +00007983 /// If the TypoExprs were successfully corrected, then the diagnostics should
7984 /// suggest the corrections. Otherwise the diagnostics will not suggest
7985 /// anything (having been passed an empty TypoCorrection).
David Goldmanfd4d7772019-08-20 19:03:15 +00007986 ///
7987 /// If we've failed to correct due to ambiguous corrections, we need to
7988 /// be sure to pass empty corrections and replacements. Otherwise it's
7989 /// possible that the Consumer has a TypoCorrection that failed to ambiguity
7990 /// and we don't want to report those diagnostics.
7991 void EmitAllDiagnostics(bool IsAmbiguous) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00007992 for (TypoExpr *TE : TypoExprs) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00007993 auto &State = SemaRef.getTypoExprState(TE);
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007994 if (State.DiagHandler) {
David Goldmanfd4d7772019-08-20 19:03:15 +00007995 TypoCorrection TC = IsAmbiguous
7996 ? TypoCorrection() : State.Consumer->getCurrentCorrection();
7997 ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE];
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007998
7999 // Extract the NamedDecl from the transformed TypoExpr and add it to the
8000 // TypoCorrection, replacing the existing decls. This ensures the right
8001 // NamedDecl is used in diagnostics e.g. in the case where overload
8002 // resolution was used to select one from several possible decls that
8003 // had been stored in the TypoCorrection.
8004 if (auto *ND = getDeclFromExpr(
8005 Replacement.isInvalid() ? nullptr : Replacement.get()))
8006 TC.setCorrectionDecl(ND);
8007
8008 State.DiagHandler(TC);
8009 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00008010 SemaRef.clearDelayedTypo(TE);
8011 }
8012 }
8013
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008014 /// If corrections for the first TypoExpr have been exhausted for a
Kaelyn Takata6c759512014-10-27 18:07:37 +00008015 /// given combination of the other TypoExprs, retry those corrections against
8016 /// the next combination of substitutions for the other TypoExprs by advancing
8017 /// to the next potential correction of the second TypoExpr. For the second
8018 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
8019 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
8020 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
8021 /// TransformCache). Returns true if there is still any untried combinations
8022 /// of corrections.
8023 bool CheckAndAdvanceTypoExprCorrectionStreams() {
8024 for (auto TE : TypoExprs) {
8025 auto &State = SemaRef.getTypoExprState(TE);
8026 TransformCache.erase(TE);
8027 if (!State.Consumer->finished())
8028 return true;
8029 State.Consumer->resetCorrectionStream();
8030 }
8031 return false;
8032 }
8033
Kaelyn Takatafe408a72014-10-27 18:07:46 +00008034 NamedDecl *getDeclFromExpr(Expr *E) {
8035 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
8036 E = OverloadResolution[OE];
8037
8038 if (!E)
8039 return nullptr;
8040 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00008041 return DRE->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00008042 if (auto *ME = dyn_cast<MemberExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00008043 return ME->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00008044 // FIXME: Add any other expr types that could be be seen by the delayed typo
8045 // correction TreeTransform for which the corresponding TypoCorrection could
Nick Lewycky39f9dbc2014-12-16 21:48:39 +00008046 // contain multiple decls.
Kaelyn Takatafe408a72014-10-27 18:07:46 +00008047 return nullptr;
8048 }
8049
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00008050 ExprResult TryTransform(Expr *E) {
8051 Sema::SFINAETrap Trap(SemaRef);
8052 ExprResult Res = TransformExpr(E);
8053 if (Trap.hasErrorOccurred() || Res.isInvalid())
8054 return ExprError();
8055
8056 return ExprFilter(Res.get());
8057 }
8058
David Goldmanfd4d7772019-08-20 19:03:15 +00008059 // Since correcting typos may intoduce new TypoExprs, this function
8060 // checks for new TypoExprs and recurses if it finds any. Note that it will
8061 // only succeed if it is able to correct all typos in the given expression.
8062 ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) {
8063 if (Res.isInvalid()) {
8064 return Res;
8065 }
8066 // Check to see if any new TypoExprs were created. If so, we need to recurse
8067 // to check their validity.
8068 Expr *FixedExpr = Res.get();
8069
8070 auto SavedTypoExprs = std::move(TypoExprs);
8071 auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs);
8072 TypoExprs.clear();
8073 AmbiguousTypoExprs.clear();
8074
8075 FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr);
8076 if (!TypoExprs.empty()) {
8077 // Recurse to handle newly created TypoExprs. If we're not able to
8078 // handle them, discard these TypoExprs.
8079 ExprResult RecurResult =
8080 RecursiveTransformLoop(FixedExpr, IsAmbiguous);
8081 if (RecurResult.isInvalid()) {
8082 Res = ExprError();
8083 // Recursive corrections didn't work, wipe them away and don't add
8084 // them to the TypoExprs set. Remove them from Sema's TypoExpr list
8085 // since we don't want to clear them twice. Note: it's possible the
8086 // TypoExprs were created recursively and thus won't be in our
8087 // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`.
8088 auto &SemaTypoExprs = SemaRef.TypoExprs;
8089 for (auto TE : TypoExprs) {
8090 TransformCache.erase(TE);
8091 SemaRef.clearDelayedTypo(TE);
8092
8093 auto SI = find(SemaTypoExprs, TE);
8094 if (SI != SemaTypoExprs.end()) {
8095 SemaTypoExprs.erase(SI);
8096 }
8097 }
8098 } else {
8099 // TypoExpr is valid: add newly created TypoExprs since we were
8100 // able to correct them.
8101 Res = RecurResult;
8102 SavedTypoExprs.set_union(TypoExprs);
8103 }
8104 }
8105
8106 TypoExprs = std::move(SavedTypoExprs);
8107 AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs);
8108
8109 return Res;
8110 }
8111
8112 // Try to transform the given expression, looping through the correction
8113 // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`.
8114 //
8115 // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to
8116 // true and this method immediately will return an `ExprError`.
8117 ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) {
8118 ExprResult Res;
8119 auto SavedTypoExprs = std::move(SemaRef.TypoExprs);
8120 SemaRef.TypoExprs.clear();
8121
8122 while (true) {
8123 Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8124
8125 // Recursion encountered an ambiguous correction. This means that our
8126 // correction itself is ambiguous, so stop now.
8127 if (IsAmbiguous)
8128 break;
8129
8130 // If the transform is still valid after checking for any new typos,
8131 // it's good to go.
8132 if (!Res.isInvalid())
8133 break;
8134
8135 // The transform was invalid, see if we have any TypoExprs with untried
8136 // correction candidates.
8137 if (!CheckAndAdvanceTypoExprCorrectionStreams())
8138 break;
8139 }
8140
8141 // If we found a valid result, double check to make sure it's not ambiguous.
8142 if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) {
David Goldman7a2b7042019-10-25 13:15:25 -04008143 auto SavedTransformCache =
8144 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache);
8145
David Goldmanfd4d7772019-08-20 19:03:15 +00008146 // Ensure none of the TypoExprs have multiple typo correction candidates
8147 // with the same edit length that pass all the checks and filters.
8148 while (!AmbiguousTypoExprs.empty()) {
8149 auto TE = AmbiguousTypoExprs.back();
8150
8151 // TryTransform itself can create new Typos, adding them to the TypoExpr map
8152 // and invalidating our TypoExprState, so always fetch it instead of storing.
8153 SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition();
8154
8155 TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection();
8156 TypoCorrection Next;
8157 do {
David Goldman6d186502019-09-13 14:43:24 +00008158 // Fetch the next correction by erasing the typo from the cache and calling
8159 // `TryTransform` which will iterate through corrections in
8160 // `TransformTypoExpr`.
8161 TransformCache.erase(TE);
David Goldmanfd4d7772019-08-20 19:03:15 +00008162 ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8163
8164 if (!AmbigRes.isInvalid() || IsAmbiguous) {
8165 SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream();
8166 SavedTransformCache.erase(TE);
8167 Res = ExprError();
8168 IsAmbiguous = true;
8169 break;
8170 }
8171 } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) &&
8172 Next.getEditDistance(false) == TC.getEditDistance(false));
8173
8174 if (IsAmbiguous)
8175 break;
8176
8177 AmbiguousTypoExprs.remove(TE);
8178 SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition();
8179 }
8180 TransformCache = std::move(SavedTransformCache);
8181 }
8182
8183 // Wipe away any newly created TypoExprs that we don't know about. Since we
8184 // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only
8185 // possible if a `TypoExpr` is created during a transformation but then
8186 // fails before we can discover it.
8187 auto &SemaTypoExprs = SemaRef.TypoExprs;
8188 for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) {
8189 auto TE = *Iterator;
8190 auto FI = find(TypoExprs, TE);
8191 if (FI != TypoExprs.end()) {
8192 Iterator++;
8193 continue;
8194 }
8195 SemaRef.clearDelayedTypo(TE);
8196 Iterator = SemaTypoExprs.erase(Iterator);
8197 }
8198 SemaRef.TypoExprs = std::move(SavedTypoExprs);
8199
8200 return Res;
8201 }
8202
Kaelyn Takata6c759512014-10-27 18:07:37 +00008203public:
Kaelyn Takatab8499f02015-05-05 19:17:03 +00008204 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
8205 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
Kaelyn Takata6c759512014-10-27 18:07:37 +00008206
Kaelyn Takatafe408a72014-10-27 18:07:46 +00008207 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
8208 MultiExprArg Args,
8209 SourceLocation RParenLoc,
8210 Expr *ExecConfig = nullptr) {
8211 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
8212 RParenLoc, ExecConfig);
8213 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
Reid Klecknera9e65ba2014-12-13 01:11:23 +00008214 if (Result.isUsable()) {
Reid Klecknera7fe33e2014-12-13 00:53:10 +00008215 Expr *ResultCall = Result.get();
8216 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
8217 ResultCall = BE->getSubExpr();
8218 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
8219 OverloadResolution[OE] = CE->getCallee();
8220 }
Kaelyn Takatafe408a72014-10-27 18:07:46 +00008221 }
8222 return Result;
8223 }
8224
Kaelyn Takata6c759512014-10-27 18:07:37 +00008225 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
8226
Saleem Abdulrasoola1742412015-10-31 00:39:15 +00008227 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
8228
Kaelyn Takata6c759512014-10-27 18:07:37 +00008229 ExprResult Transform(Expr *E) {
David Goldmanfd4d7772019-08-20 19:03:15 +00008230 bool IsAmbiguous = false;
8231 ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous);
Kaelyn Takata49d84322014-11-11 23:26:56 +00008232
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00008233 if (!Res.isUsable())
Kaelyn Takata57e07c92014-11-20 22:06:44 +00008234 FindTypoExprs(TypoExprs).TraverseStmt(E);
8235
David Goldmanfd4d7772019-08-20 19:03:15 +00008236 EmitAllDiagnostics(IsAmbiguous);
Kaelyn Takata6c759512014-10-27 18:07:37 +00008237
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00008238 return Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00008239 }
8240
8241 ExprResult TransformTypoExpr(TypoExpr *E) {
8242 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
8243 // cached transformation result if there is one and the TypoExpr isn't the
8244 // first one that was encountered.
8245 auto &CacheEntry = TransformCache[E];
8246 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
8247 return CacheEntry;
8248 }
8249
8250 auto &State = SemaRef.getTypoExprState(E);
8251 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
8252
8253 // For the first TypoExpr and an uncached TypoExpr, find the next likely
8254 // typo correction and return it.
8255 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00008256 if (InitDecl && TC.getFoundDecl() == InitDecl)
Kaelyn Takatab8499f02015-05-05 19:17:03 +00008257 continue;
Richard Smith1cf45412017-01-04 23:14:16 +00008258 // FIXME: If we would typo-correct to an invalid declaration, it's
8259 // probably best to just suppress all errors from this typo correction.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00008260 ExprResult NE = State.RecoveryHandler ?
8261 State.RecoveryHandler(SemaRef, E, TC) :
8262 attemptRecovery(SemaRef, *State.Consumer, TC);
8263 if (!NE.isInvalid()) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00008264 // Check whether there may be a second viable correction with the same
8265 // edit distance; if so, remember this TypoExpr may have an ambiguous
8266 // correction so it can be more thoroughly vetted later.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00008267 TypoCorrection Next;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00008268 if ((Next = State.Consumer->peekNextCorrection()) &&
8269 Next.getEditDistance(false) == TC.getEditDistance(false)) {
8270 AmbiguousTypoExprs.insert(E);
8271 } else {
8272 AmbiguousTypoExprs.remove(E);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00008273 }
8274 assert(!NE.isUnset() &&
8275 "Typo was transformed into a valid-but-null ExprResult");
Kaelyn Takata6c759512014-10-27 18:07:37 +00008276 return CacheEntry = NE;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00008277 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00008278 }
8279 return CacheEntry = ExprError();
8280 }
8281};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008282}
Faisal Valia17d19f2013-11-07 05:17:06 +00008283
Kaelyn Takatab8499f02015-05-05 19:17:03 +00008284ExprResult
8285Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
8286 llvm::function_ref<ExprResult(Expr *)> Filter) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00008287 // If the current evaluation context indicates there are uncorrected typos
8288 // and the current expression isn't guaranteed to not have typos, try to
8289 // resolve any TypoExpr nodes that might be in the expression.
Kaelyn Takatac71dda22014-12-02 22:05:35 +00008290 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
Kaelyn Takata49d84322014-11-11 23:26:56 +00008291 (E->isTypeDependent() || E->isValueDependent() ||
8292 E->isInstantiationDependent())) {
8293 auto TyposResolved = DelayedTypos.size();
Kaelyn Takatab8499f02015-05-05 19:17:03 +00008294 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00008295 TyposResolved -= DelayedTypos.size();
Nick Lewycky4d59b772014-12-16 22:02:06 +00008296 if (Result.isInvalid() || Result.get() != E) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00008297 ExprEvalContexts.back().NumTypos -= TyposResolved;
8298 return Result;
8299 }
Nick Lewycky4d59b772014-12-16 22:02:06 +00008300 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
Kaelyn Takata49d84322014-11-11 23:26:56 +00008301 }
8302 return E;
8303}
8304
Richard Smith945f8d32013-01-14 22:39:08 +00008305ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008306 bool DiscardedValue,
Richard Smithb3d203f2018-10-19 19:01:34 +00008307 bool IsConstexpr) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008308 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00008309
8310 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00008311 return ExprError();
Simon Pilgrim75c26882016-09-30 14:25:09 +00008312
Richard Smithb3d203f2018-10-19 19:01:34 +00008313 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00008314 return ExprError();
8315
Richard Smith945f8d32013-01-14 22:39:08 +00008316 if (DiscardedValue) {
Richard Smithb3d203f2018-10-19 19:01:34 +00008317 // Top-level expressions default to 'id' when we're in a debugger.
8318 if (getLangOpts().DebuggerCastResultToId &&
8319 FullExpr.get()->getType() == Context.UnknownAnyTy) {
8320 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
8321 if (FullExpr.isInvalid())
8322 return ExprError();
8323 }
8324
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008325 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00008326 if (FullExpr.isInvalid())
8327 return ExprError();
8328
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008329 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00008330 if (FullExpr.isInvalid())
8331 return ExprError();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00008332
8333 DiagnoseUnusedExprResult(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00008334 }
John Wiegley01296292011-04-08 18:41:53 +00008335
Kaelyn Takata49d84322014-11-11 23:26:56 +00008336 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
8337 if (FullExpr.isInvalid())
8338 return ExprError();
Kaelyn Takata6c759512014-10-27 18:07:37 +00008339
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008340 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00008341
Simon Pilgrim75c26882016-09-30 14:25:09 +00008342 // At the end of this full expression (which could be a deeply nested
8343 // lambda), if there is a potential capture within the nested lambda,
Faisal Vali218e94b2013-11-12 03:56:08 +00008344 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00008345 // Consider the following code:
8346 // void f(int, int);
8347 // void f(const int&, double);
Simon Pilgrim75c26882016-09-30 14:25:09 +00008348 // void foo() {
Faisal Valia17d19f2013-11-07 05:17:06 +00008349 // const int x = 10, y = 20;
8350 // auto L = [=](auto a) {
8351 // auto M = [=](auto b) {
8352 // f(x, b); <-- requires x to be captured by L and M
8353 // f(y, a); <-- requires y to be captured by L, but not all Ms
8354 // };
8355 // };
8356 // }
8357
Simon Pilgrim75c26882016-09-30 14:25:09 +00008358 // FIXME: Also consider what happens for something like this that involves
8359 // the gnu-extension statement-expressions or even lambda-init-captures:
Faisal Valia17d19f2013-11-07 05:17:06 +00008360 // void f() {
8361 // const int n = 0;
8362 // auto L = [&](auto a) {
8363 // +n + ({ 0; a; });
8364 // };
8365 // }
Simon Pilgrim75c26882016-09-30 14:25:09 +00008366 //
8367 // Here, we see +n, and then the full-expression 0; ends, so we don't
8368 // capture n (and instead remove it from our list of potential captures),
8369 // and then the full-expression +n + ({ 0; }); ends, but it's too late
Faisal Vali218e94b2013-11-12 03:56:08 +00008370 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00008371
Alexey Bataev31939e32016-11-11 12:36:20 +00008372 LambdaScopeInfo *const CurrentLSI =
8373 getCurLambda(/*IgnoreCapturedRegions=*/true);
Simon Pilgrim75c26882016-09-30 14:25:09 +00008374 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
Faisal Vali8bc2bc72013-11-12 03:48:27 +00008375 // even if CurContext is not a lambda call operator. Refer to that Bug Report
Simon Pilgrim75c26882016-09-30 14:25:09 +00008376 // for an example of the code that might cause this asynchrony.
Faisal Vali8bc2bc72013-11-12 03:48:27 +00008377 // By ensuring we are in the context of a lambda's call operator
8378 // we can fix the bug (we only need to check whether we need to capture
Simon Pilgrim75c26882016-09-30 14:25:09 +00008379 // if we are within a lambda's body); but per the comments in that
Faisal Vali8bc2bc72013-11-12 03:48:27 +00008380 // PR, a proper fix would entail :
8381 // "Alternative suggestion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00008382 // - Add to Sema an integer holding the smallest (outermost) scope
8383 // index that we are *lexically* within, and save/restore/set to
8384 // FunctionScopes.size() in InstantiatingTemplate's
Faisal Vali8bc2bc72013-11-12 03:48:27 +00008385 // constructor/destructor.
Simon Pilgrim75c26882016-09-30 14:25:09 +00008386 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00008387 // stop at the outermost enclosing lexical scope."
Alexey Bataev31939e32016-11-11 12:36:20 +00008388 DeclContext *DC = CurContext;
8389 while (DC && isa<CapturedDecl>(DC))
8390 DC = DC->getParent();
8391 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
Faisal Valiab3d6462013-12-07 20:22:44 +00008392 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00008393 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00008394 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
8395 *this);
John McCall5d413782010-12-06 08:20:24 +00008396 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00008397}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00008398
8399StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
8400 if (!FullStmt) return StmtError();
8401
John McCall5d413782010-12-06 08:20:24 +00008402 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00008403}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00008404
Simon Pilgrim75c26882016-09-30 14:25:09 +00008405Sema::IfExistsResult
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00008406Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
8407 CXXScopeSpec &SS,
8408 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00008409 DeclarationName TargetName = TargetNameInfo.getName();
8410 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00008411 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00008412
Douglas Gregor43edb322011-10-24 22:31:10 +00008413 // If the name itself is dependent, then the result is dependent.
8414 if (TargetName.isDependentName())
8415 return IER_Dependent;
Simon Pilgrim75c26882016-09-30 14:25:09 +00008416
Francois Pichet4a7de3e2011-05-06 20:48:22 +00008417 // Do the redeclaration lookup in the current scope.
8418 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
8419 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00008420 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00008421 R.suppressDiagnostics();
Simon Pilgrim75c26882016-09-30 14:25:09 +00008422
Douglas Gregor43edb322011-10-24 22:31:10 +00008423 switch (R.getResultKind()) {
8424 case LookupResult::Found:
8425 case LookupResult::FoundOverloaded:
8426 case LookupResult::FoundUnresolvedValue:
8427 case LookupResult::Ambiguous:
8428 return IER_Exists;
Simon Pilgrim75c26882016-09-30 14:25:09 +00008429
Douglas Gregor43edb322011-10-24 22:31:10 +00008430 case LookupResult::NotFound:
8431 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00008432
Douglas Gregor43edb322011-10-24 22:31:10 +00008433 case LookupResult::NotFoundInCurrentInstantiation:
8434 return IER_Dependent;
8435 }
David Blaikie8a40f702012-01-17 06:56:22 +00008436
8437 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00008438}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00008439
Simon Pilgrim75c26882016-09-30 14:25:09 +00008440Sema::IfExistsResult
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00008441Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
8442 bool IsIfExists, CXXScopeSpec &SS,
8443 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00008444 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Simon Pilgrim75c26882016-09-30 14:25:09 +00008445
Richard Smith151c4562016-12-20 21:35:28 +00008446 // Check for an unexpanded parameter pack.
8447 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
8448 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
8449 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00008450 return IER_Error;
Simon Pilgrim75c26882016-09-30 14:25:09 +00008451
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00008452 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
8453}
Saar Raza0f50d72020-01-18 09:11:43 +02008454
8455concepts::Requirement *Sema::ActOnSimpleRequirement(Expr *E) {
8456 return BuildExprRequirement(E, /*IsSimple=*/true,
8457 /*NoexceptLoc=*/SourceLocation(),
8458 /*ReturnTypeRequirement=*/{});
8459}
8460
8461concepts::Requirement *
8462Sema::ActOnTypeRequirement(SourceLocation TypenameKWLoc, CXXScopeSpec &SS,
8463 SourceLocation NameLoc, IdentifierInfo *TypeName,
8464 TemplateIdAnnotation *TemplateId) {
8465 assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) &&
8466 "Exactly one of TypeName and TemplateId must be specified.");
8467 TypeSourceInfo *TSI = nullptr;
8468 if (TypeName) {
8469 QualType T = CheckTypenameType(ETK_Typename, TypenameKWLoc,
8470 SS.getWithLocInContext(Context), *TypeName,
8471 NameLoc, &TSI, /*DeducedTypeContext=*/false);
8472 if (T.isNull())
8473 return nullptr;
8474 } else {
8475 ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(),
8476 TemplateId->NumArgs);
8477 TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS,
8478 TemplateId->TemplateKWLoc,
8479 TemplateId->Template, TemplateId->Name,
8480 TemplateId->TemplateNameLoc,
8481 TemplateId->LAngleLoc, ArgsPtr,
8482 TemplateId->RAngleLoc);
8483 if (T.isInvalid())
8484 return nullptr;
8485 if (GetTypeFromParser(T.get(), &TSI).isNull())
8486 return nullptr;
8487 }
8488 return BuildTypeRequirement(TSI);
8489}
8490
8491concepts::Requirement *
8492Sema::ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc) {
8493 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc,
8494 /*ReturnTypeRequirement=*/{});
8495}
8496
8497concepts::Requirement *
8498Sema::ActOnCompoundRequirement(
8499 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8500 TemplateIdAnnotation *TypeConstraint, unsigned Depth) {
8501 // C++2a [expr.prim.req.compound] p1.3.3
8502 // [..] the expression is deduced against an invented function template
8503 // F [...] F is a void function template with a single type template
8504 // parameter T declared with the constrained-parameter. Form a new
8505 // cv-qualifier-seq cv by taking the union of const and volatile specifiers
8506 // around the constrained-parameter. F has a single parameter whose
8507 // type-specifier is cv T followed by the abstract-declarator. [...]
8508 //
8509 // The cv part is done in the calling function - we get the concept with
8510 // arguments and the abstract declarator with the correct CV qualification and
8511 // have to synthesize T and the single parameter of F.
8512 auto &II = Context.Idents.get("expr-type");
8513 auto *TParam = TemplateTypeParmDecl::Create(Context, CurContext,
8514 SourceLocation(),
8515 SourceLocation(), Depth,
8516 /*Index=*/0, &II,
8517 /*Typename=*/true,
8518 /*ParameterPack=*/false,
8519 /*HasTypeConstraint=*/true);
8520
8521 if (ActOnTypeConstraint(SS, TypeConstraint, TParam,
8522 /*EllpsisLoc=*/SourceLocation()))
8523 // Just produce a requirement with no type requirements.
8524 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {});
8525
8526 auto *TPL = TemplateParameterList::Create(Context, SourceLocation(),
8527 SourceLocation(),
8528 ArrayRef<NamedDecl *>(TParam),
8529 SourceLocation(),
8530 /*RequiresClause=*/nullptr);
8531 return BuildExprRequirement(
8532 E, /*IsSimple=*/false, NoexceptLoc,
8533 concepts::ExprRequirement::ReturnTypeRequirement(TPL));
8534}
8535
8536concepts::ExprRequirement *
8537Sema::BuildExprRequirement(
8538 Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
8539 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {
8540 auto Status = concepts::ExprRequirement::SS_Satisfied;
8541 ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr;
8542 if (E->isInstantiationDependent() || ReturnTypeRequirement.isDependent())
8543 Status = concepts::ExprRequirement::SS_Dependent;
8544 else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can)
8545 Status = concepts::ExprRequirement::SS_NoexceptNotMet;
8546 else if (ReturnTypeRequirement.isSubstitutionFailure())
8547 Status = concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure;
8548 else if (ReturnTypeRequirement.isTypeConstraint()) {
8549 // C++2a [expr.prim.req]p1.3.3
8550 // The immediately-declared constraint ([temp]) of decltype((E)) shall
8551 // be satisfied.
8552 TemplateParameterList *TPL =
8553 ReturnTypeRequirement.getTypeConstraintTemplateParameterList();
8554 QualType MatchedType =
8555 BuildDecltypeType(E, E->getBeginLoc()).getCanonicalType();
8556 llvm::SmallVector<TemplateArgument, 1> Args;
8557 Args.push_back(TemplateArgument(MatchedType));
8558 TemplateArgumentList TAL(TemplateArgumentList::OnStack, Args);
8559 MultiLevelTemplateArgumentList MLTAL(TAL);
8560 for (unsigned I = 0; I < TPL->getDepth(); ++I)
8561 MLTAL.addOuterRetainedLevel();
8562 Expr *IDC =
8563 cast<TemplateTypeParmDecl>(TPL->getParam(0))->getTypeConstraint()
8564 ->getImmediatelyDeclaredConstraint();
8565 ExprResult Constraint = SubstExpr(IDC, MLTAL);
8566 assert(!Constraint.isInvalid() &&
8567 "Substitution cannot fail as it is simply putting a type template "
8568 "argument into a concept specialization expression's parameter.");
8569
8570 SubstitutedConstraintExpr =
8571 cast<ConceptSpecializationExpr>(Constraint.get());
8572 if (!SubstitutedConstraintExpr->isSatisfied())
8573 Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied;
8574 }
8575 return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc,
8576 ReturnTypeRequirement, Status,
8577 SubstitutedConstraintExpr);
8578}
8579
8580concepts::ExprRequirement *
8581Sema::BuildExprRequirement(
8582 concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic,
8583 bool IsSimple, SourceLocation NoexceptLoc,
8584 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {
8585 return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic,
8586 IsSimple, NoexceptLoc,
8587 ReturnTypeRequirement);
8588}
8589
8590concepts::TypeRequirement *
8591Sema::BuildTypeRequirement(TypeSourceInfo *Type) {
8592 return new (Context) concepts::TypeRequirement(Type);
8593}
8594
8595concepts::TypeRequirement *
8596Sema::BuildTypeRequirement(
8597 concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
8598 return new (Context) concepts::TypeRequirement(SubstDiag);
8599}
8600
8601concepts::Requirement *Sema::ActOnNestedRequirement(Expr *Constraint) {
8602 return BuildNestedRequirement(Constraint);
8603}
8604
8605concepts::NestedRequirement *
8606Sema::BuildNestedRequirement(Expr *Constraint) {
8607 ConstraintSatisfaction Satisfaction;
8608 if (!Constraint->isInstantiationDependent() &&
Saar Raz713562f2020-01-25 22:54:27 +02008609 CheckConstraintSatisfaction(nullptr, {Constraint}, /*TemplateArgs=*/{},
8610 Constraint->getSourceRange(), Satisfaction))
Saar Raza0f50d72020-01-18 09:11:43 +02008611 return nullptr;
8612 return new (Context) concepts::NestedRequirement(Context, Constraint,
8613 Satisfaction);
8614}
8615
8616concepts::NestedRequirement *
8617Sema::BuildNestedRequirement(
8618 concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
8619 return new (Context) concepts::NestedRequirement(SubstDiag);
8620}
8621
8622RequiresExprBodyDecl *
8623Sema::ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
8624 ArrayRef<ParmVarDecl *> LocalParameters,
8625 Scope *BodyScope) {
8626 assert(BodyScope);
8627
8628 RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(Context, CurContext,
8629 RequiresKWLoc);
8630
8631 PushDeclContext(BodyScope, Body);
8632
8633 for (ParmVarDecl *Param : LocalParameters) {
8634 if (Param->hasDefaultArg())
8635 // C++2a [expr.prim.req] p4
8636 // [...] A local parameter of a requires-expression shall not have a
8637 // default argument. [...]
8638 Diag(Param->getDefaultArgRange().getBegin(),
8639 diag::err_requires_expr_local_parameter_default_argument);
8640 // Ignore default argument and move on
8641
8642 Param->setDeclContext(Body);
8643 // If this has an identifier, add it to the scope stack.
8644 if (Param->getIdentifier()) {
8645 CheckShadow(BodyScope, Param);
8646 PushOnScopeChains(Param, BodyScope);
8647 }
8648 }
8649 return Body;
8650}
8651
8652void Sema::ActOnFinishRequiresExpr() {
8653 assert(CurContext && "DeclContext imbalance!");
8654 CurContext = CurContext->getLexicalParent();
8655 assert(CurContext && "Popped translation unit!");
8656}
8657
8658ExprResult
8659Sema::ActOnRequiresExpr(SourceLocation RequiresKWLoc,
8660 RequiresExprBodyDecl *Body,
8661 ArrayRef<ParmVarDecl *> LocalParameters,
8662 ArrayRef<concepts::Requirement *> Requirements,
8663 SourceLocation ClosingBraceLoc) {
8664 return RequiresExpr::Create(Context, RequiresKWLoc, Body, LocalParameters,
8665 Requirements, ClosingBraceLoc);
8666}