blob: 6dd7aabaa1f01a06eeafb4f9d456bebc6b9465aa [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall2a7fb272010-08-25 05:32:35 +000015#include "clang/Sema/DeclSpec.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/ParsedTemplate.h"
John McCall469a1eb2011-02-02 13:00:07 +000019#include "clang/Sema/ScopeInfo.h"
John McCall2a7fb272010-08-25 05:32:35 +000020#include "clang/Sema/TemplateDeduction.h"
Steve Naroff210679c2007-08-25 14:02:58 +000021#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000024#include "clang/AST/ExprCXX.h"
Fariborz Jahaniand4266622010-06-16 18:56:04 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregorb57fb492010-02-24 22:38:50 +000026#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000027#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000028#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000029#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000030#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000032using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000033
John McCallb3d87482010-08-24 05:47:05 +000034ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000035 IdentifierInfo &II,
John McCallb3d87482010-08-24 05:47:05 +000036 SourceLocation NameLoc,
37 Scope *S, CXXScopeSpec &SS,
38 ParsedType ObjectTypePtr,
39 bool EnteringContext) {
Douglas Gregor124b8782010-02-16 19:09:40 +000040 // Determine where to perform name lookup.
41
42 // FIXME: This area of the standard is very messy, and the current
43 // wording is rather unclear about which scopes we search for the
44 // destructor name; see core issues 399 and 555. Issue 399 in
45 // particular shows where the current description of destructor name
46 // lookup is completely out of line with existing practice, e.g.,
47 // this appears to be ill-formed:
48 //
49 // namespace N {
50 // template <typename T> struct S {
51 // ~S();
52 // };
53 // }
54 //
55 // void f(N::S<int>* s) {
56 // s->N::S<int>::~S();
57 // }
58 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000059 // See also PR6358 and PR6359.
Sebastian Redlc0fee502010-07-07 23:17:38 +000060 // For this reason, we're currently only doing the C++03 version of this
61 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregor124b8782010-02-16 19:09:40 +000062 QualType SearchType;
63 DeclContext *LookupCtx = 0;
64 bool isDependent = false;
65 bool LookInScope = false;
66
67 // If we have an object type, it's because we are in a
68 // pseudo-destructor-expression or a member access expression, and
69 // we know what type we're looking for.
70 if (ObjectTypePtr)
71 SearchType = GetTypeFromParser(ObjectTypePtr);
72
73 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000074 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000075
Douglas Gregor93649fd2010-02-23 00:15:22 +000076 bool AlreadySearched = false;
77 bool LookAtPrefix = true;
Sebastian Redlc0fee502010-07-07 23:17:38 +000078 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000079 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redlc0fee502010-07-07 23:17:38 +000080 // the type-names are looked up as types in the scope designated by the
81 // nested-name-specifier. In a qualified-id of the form:
NAKAMURA Takumi00995302011-01-27 07:09:49 +000082 //
83 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redlc0fee502010-07-07 23:17:38 +000084 //
85 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth5e895a82010-02-21 10:19:54 +000086 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +000087 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +000088 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregor124b8782010-02-16 19:09:40 +000089 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000090 // the class-names are looked up as types in the scope designated by
Sebastian Redlc0fee502010-07-07 23:17:38 +000091 // the nested-name-specifier.
Douglas Gregor124b8782010-02-16 19:09:40 +000092 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000093 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000094 // code below is permitted to look at the prefix of the
Sebastian Redlc0fee502010-07-07 23:17:38 +000095 // nested-name-specifier.
96 DeclContext *DC = computeDeclContext(SS, EnteringContext);
97 if (DC && DC->isFileContext()) {
98 AlreadySearched = true;
99 LookupCtx = DC;
100 isDependent = false;
101 } else if (DC && isa<CXXRecordDecl>(DC))
102 LookAtPrefix = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000103
Sebastian Redlc0fee502010-07-07 23:17:38 +0000104 // The second case from the C++03 rules quoted further above.
Douglas Gregor93649fd2010-02-23 00:15:22 +0000105 NestedNameSpecifier *Prefix = 0;
106 if (AlreadySearched) {
107 // Nothing left to do.
108 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
109 CXXScopeSpec PrefixSS;
Douglas Gregor7e384942011-02-25 16:07:42 +0000110 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor93649fd2010-02-23 00:15:22 +0000111 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
112 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000113 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000114 LookupCtx = computeDeclContext(SearchType);
115 isDependent = SearchType->isDependentType();
116 } else {
117 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000118 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000119 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000120
Douglas Gregoredc90502010-02-25 04:46:04 +0000121 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000122 } else if (ObjectTypePtr) {
123 // C++ [basic.lookup.classref]p3:
124 // If the unqualified-id is ~type-name, the type-name is looked up
125 // in the context of the entire postfix-expression. If the type T
126 // of the object expression is of a class type C, the type-name is
127 // also looked up in the scope of class C. At least one of the
128 // lookups shall find a name that refers to (possibly
129 // cv-qualified) T.
130 LookupCtx = computeDeclContext(SearchType);
131 isDependent = SearchType->isDependentType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000132 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregor124b8782010-02-16 19:09:40 +0000133 "Caller should have completed object type");
134
135 LookInScope = true;
136 } else {
137 // Perform lookup into the current scope (only).
138 LookInScope = true;
139 }
140
141 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
142 for (unsigned Step = 0; Step != 2; ++Step) {
143 // Look for the name first in the computed lookup context (if we
144 // have one) and, if that fails to find a match, in the sope (if
145 // we're allowed to look there).
146 Found.clear();
147 if (Step == 0 && LookupCtx)
148 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000149 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000150 LookupName(Found, S);
151 else
152 continue;
153
154 // FIXME: Should we be suppressing ambiguities here?
155 if (Found.isAmbiguous())
John McCallb3d87482010-08-24 05:47:05 +0000156 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000157
158 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
159 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000160
161 if (SearchType.isNull() || SearchType->isDependentType() ||
162 Context.hasSameUnqualifiedType(T, SearchType)) {
163 // We found our type!
164
John McCallb3d87482010-08-24 05:47:05 +0000165 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000166 }
167 }
168
169 // If the name that we found is a class template name, and it is
170 // the same name as the template name in the last part of the
171 // nested-name-specifier (if present) or the object type, then
172 // this is the destructor for that class.
173 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000174 // issue 399, for which there isn't even an obvious direction.
Douglas Gregor124b8782010-02-16 19:09:40 +0000175 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
176 QualType MemberOfType;
177 if (SS.isSet()) {
178 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
179 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000180 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
181 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000182 }
183 }
184 if (MemberOfType.isNull())
185 MemberOfType = SearchType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000186
Douglas Gregor124b8782010-02-16 19:09:40 +0000187 if (MemberOfType.isNull())
188 continue;
189
190 // We're referring into a class template specialization. If the
191 // class template we found is the same as the template being
192 // specialized, we found what we are looking for.
193 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
194 if (ClassTemplateSpecializationDecl *Spec
195 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
196 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
197 Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000198 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000199 }
200
201 continue;
202 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000203
Douglas Gregor124b8782010-02-16 19:09:40 +0000204 // We're referring to an unresolved class template
205 // specialization. Determine whether we class template we found
206 // is the same as the template being specialized or, if we don't
207 // know which template is being specialized, that it at least
208 // has the same name.
209 if (const TemplateSpecializationType *SpecType
210 = MemberOfType->getAs<TemplateSpecializationType>()) {
211 TemplateName SpecName = SpecType->getTemplateName();
212
213 // The class template we found is the same template being
214 // specialized.
215 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
216 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000217 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000218
219 continue;
220 }
221
222 // The class template we found has the same name as the
223 // (dependent) template name being specialized.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000224 if (DependentTemplateName *DepTemplate
Douglas Gregor124b8782010-02-16 19:09:40 +0000225 = SpecName.getAsDependentTemplateName()) {
226 if (DepTemplate->isIdentifier() &&
227 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallb3d87482010-08-24 05:47:05 +0000228 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000229
230 continue;
231 }
232 }
233 }
234 }
235
236 if (isDependent) {
237 // We didn't find our type, but that's okay: it's dependent
238 // anyway.
239 NestedNameSpecifier *NNS = 0;
240 SourceRange Range;
241 if (SS.isSet()) {
242 NNS = (NestedNameSpecifier *)SS.getScopeRep();
243 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
244 } else {
245 NNS = NestedNameSpecifier::Create(Context, &II);
246 Range = SourceRange(NameLoc);
247 }
248
John McCallb3d87482010-08-24 05:47:05 +0000249 QualType T = CheckTypenameType(ETK_None, NNS, II,
250 SourceLocation(),
251 Range, NameLoc);
252 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000253 }
254
255 if (ObjectTypePtr)
256 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000257 << &II;
Douglas Gregor124b8782010-02-16 19:09:40 +0000258 else
259 Diag(NameLoc, diag::err_destructor_class_name);
260
John McCallb3d87482010-08-24 05:47:05 +0000261 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000262}
263
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000264/// \brief Build a C++ typeid expression with a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000265ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000266 SourceLocation TypeidLoc,
267 TypeSourceInfo *Operand,
268 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000269 // C++ [expr.typeid]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000270 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000271 // that is the operand of typeid are always ignored.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000272 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000273 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000274 Qualifiers Quals;
275 QualType T
276 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
277 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000278 if (T->getAs<RecordType>() &&
279 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
280 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000281
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000282 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
283 Operand,
284 SourceRange(TypeidLoc, RParenLoc)));
285}
286
287/// \brief Build a C++ typeid expression with an expression operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000288ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000289 SourceLocation TypeidLoc,
290 Expr *E,
291 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000292 bool isUnevaluatedOperand = true;
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000293 if (E && !E->isTypeDependent()) {
294 QualType T = E->getType();
295 if (const RecordType *RecordT = T->getAs<RecordType>()) {
296 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
297 // C++ [expr.typeid]p3:
298 // [...] If the type of the expression is a class type, the class
299 // shall be completely-defined.
300 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
301 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000302
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000303 // C++ [expr.typeid]p3:
Sebastian Redl906082e2010-07-20 04:20:21 +0000304 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000305 // polymorphic class type [...] [the] expression is an unevaluated
306 // operand. [...]
Sebastian Redl906082e2010-07-20 04:20:21 +0000307 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000308 isUnevaluatedOperand = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000309
310 // We require a vtable to query the type at run time.
311 MarkVTableUsed(TypeidLoc, RecordD);
312 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000313 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000314
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000315 // C++ [expr.typeid]p4:
316 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000317 // cv-qualified type, the result of the typeid expression refers to a
318 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000319 // type.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000320 Qualifiers Quals;
321 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
322 if (!Context.hasSameType(T, UnqualT)) {
323 T = UnqualT;
John McCall2de56d12010-08-25 11:45:40 +0000324 ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000325 }
326 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000327
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000328 // If this is an unevaluated operand, clear out the set of
329 // declaration references we have been computing and eliminate any
330 // temporaries introduced in its computation.
331 if (isUnevaluatedOperand)
332 ExprEvalContexts.back().Context = Unevaluated;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000333
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000334 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCall9ae2f072010-08-23 23:25:46 +0000335 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000336 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000337}
338
339/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCall60d7b3a2010-08-24 06:29:42 +0000340ExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000341Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
342 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000343 // Find the std::type_info type.
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000344 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000345 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000346
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000347 if (!CXXTypeInfoDecl) {
348 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
349 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
350 LookupQualifiedName(R, getStdNamespace());
351 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
352 if (!CXXTypeInfoDecl)
353 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
354 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000355
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000356 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000357
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000358 if (isType) {
359 // The operand is a type; handle it as such.
360 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +0000361 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
362 &TInfo);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000363 if (T.isNull())
364 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000365
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000366 if (!TInfo)
367 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000368
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000369 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000370 }
Mike Stump1eb44332009-09-09 15:08:12 +0000371
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000372 // The operand is an expression.
John McCall9ae2f072010-08-23 23:25:46 +0000373 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000374}
375
Francois Pichet6915c522010-12-27 01:32:00 +0000376/// Retrieve the UuidAttr associated with QT.
377static UuidAttr *GetUuidAttrOfType(QualType QT) {
378 // Optionally remove one level of pointer, reference or array indirection.
John McCallf4c73712011-01-19 06:33:43 +0000379 const Type *Ty = QT.getTypePtr();;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000380 if (QT->isPointerType() || QT->isReferenceType())
381 Ty = QT->getPointeeType().getTypePtr();
382 else if (QT->isArrayType())
383 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
384
Francois Pichet6915c522010-12-27 01:32:00 +0000385 // Loop all class definition and declaration looking for an uuid attribute.
386 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
387 while (RD) {
388 if (UuidAttr *Uuid = RD->getAttr<UuidAttr>())
389 return Uuid;
390 RD = RD->getPreviousDeclaration();
391 }
392 return 0;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000393}
394
Francois Pichet01b7c302010-09-08 12:20:18 +0000395/// \brief Build a Microsoft __uuidof expression with a type operand.
396ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
397 SourceLocation TypeidLoc,
398 TypeSourceInfo *Operand,
399 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000400 if (!Operand->getType()->isDependentType()) {
401 if (!GetUuidAttrOfType(Operand->getType()))
402 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
403 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000404
Francois Pichet01b7c302010-09-08 12:20:18 +0000405 // FIXME: add __uuidof semantic analysis for type operand.
406 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
407 Operand,
408 SourceRange(TypeidLoc, RParenLoc)));
409}
410
411/// \brief Build a Microsoft __uuidof expression with an expression operand.
412ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
413 SourceLocation TypeidLoc,
414 Expr *E,
415 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000416 if (!E->getType()->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000417 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichet6915c522010-12-27 01:32:00 +0000418 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
419 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
420 }
421 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet01b7c302010-09-08 12:20:18 +0000422 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
423 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000424 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet01b7c302010-09-08 12:20:18 +0000425}
426
427/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
428ExprResult
429Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
430 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000431 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet01b7c302010-09-08 12:20:18 +0000432 if (!MSVCGuidDecl) {
433 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
434 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
435 LookupQualifiedName(R, Context.getTranslationUnitDecl());
436 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
437 if (!MSVCGuidDecl)
438 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000439 }
440
Francois Pichet01b7c302010-09-08 12:20:18 +0000441 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000442
Francois Pichet01b7c302010-09-08 12:20:18 +0000443 if (isType) {
444 // The operand is a type; handle it as such.
445 TypeSourceInfo *TInfo = 0;
446 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
447 &TInfo);
448 if (T.isNull())
449 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000450
Francois Pichet01b7c302010-09-08 12:20:18 +0000451 if (!TInfo)
452 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
453
454 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
455 }
456
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000457 // The operand is an expression.
Francois Pichet01b7c302010-09-08 12:20:18 +0000458 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
459}
460
Steve Naroff1b273c42007-09-16 14:56:35 +0000461/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCall60d7b3a2010-08-24 06:29:42 +0000462ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000463Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000464 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000465 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000466 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
467 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000468}
Chris Lattner50dd2892008-02-26 00:51:44 +0000469
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000470/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCall60d7b3a2010-08-24 06:29:42 +0000471ExprResult
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000472Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
473 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
474}
475
Chris Lattner50dd2892008-02-26 00:51:44 +0000476/// ActOnCXXThrow - Parse throw expressions.
John McCall60d7b3a2010-08-24 06:29:42 +0000477ExprResult
John McCall9ae2f072010-08-23 23:25:46 +0000478Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
Anders Carlsson729b8532011-02-23 03:46:46 +0000479 // Don't report an error if 'throw' is used in system headers.
480 if (!getLangOptions().Exceptions &&
481 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb1fba312011-02-19 21:53:09 +0000482 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Anders Carlsson7f11d9c2011-02-19 19:26:44 +0000483
Sebastian Redl972041f2009-04-27 20:27:31 +0000484 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
485 return ExprError();
486 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
487}
488
489/// CheckCXXThrowOperand - Validate the operand of a throw.
490bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
491 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000492 // A throw-expression initializes a temporary object, called the exception
493 // object, the type of which is determined by removing any top-level
494 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000495 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor154fe982009-12-23 22:04:40 +0000496 // or "pointer to function returning T", [...]
497 if (E->getType().hasQualifiers())
John McCall2de56d12010-08-25 11:45:40 +0000498 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Sebastian Redl906082e2010-07-20 04:20:21 +0000499 CastCategory(E));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000500
Sebastian Redl972041f2009-04-27 20:27:31 +0000501 DefaultFunctionArrayConversion(E);
502
503 // If the type of the exception would be an incomplete type or a pointer
504 // to an incomplete type other than (cv) void the program is ill-formed.
505 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000506 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000507 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000508 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000509 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000510 }
511 if (!isPointer || !Ty->isVoidType()) {
512 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000513 PDiag(isPointer ? diag::err_throw_incomplete_ptr
514 : diag::err_throw_incomplete)
515 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000516 return true;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000517
Douglas Gregorbf422f92010-04-15 18:05:39 +0000518 if (RequireNonAbstractType(ThrowLoc, E->getType(),
519 PDiag(diag::err_throw_abstract_type)
520 << E->getSourceRange()))
521 return true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000522 }
523
John McCallac418162010-04-22 01:10:34 +0000524 // Initialize the exception result. This implicitly weeds out
525 // abstract types or types with inaccessible copy constructors.
Douglas Gregor72dfa272011-01-21 22:46:35 +0000526 const VarDecl *NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
527
Douglas Gregorf5d8f462011-01-21 18:05:27 +0000528 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p32.
John McCallac418162010-04-22 01:10:34 +0000529 InitializedEntity Entity =
Douglas Gregor72dfa272011-01-21 22:46:35 +0000530 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
531 /*NRVO=*/false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000532 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregor72dfa272011-01-21 22:46:35 +0000533 QualType(), E);
John McCallac418162010-04-22 01:10:34 +0000534 if (Res.isInvalid())
535 return true;
536 E = Res.takeAs<Expr>();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000537
Eli Friedman5ed9b932010-06-03 20:39:03 +0000538 // If the exception has class type, we need additional handling.
539 const RecordType *RecordTy = Ty->getAs<RecordType>();
540 if (!RecordTy)
541 return false;
542 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
543
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000544 // If we are throwing a polymorphic class type or pointer thereof,
545 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000546 MarkVTableUsed(ThrowLoc, RD);
547
Eli Friedman98efb9f2010-10-12 20:32:36 +0000548 // If a pointer is thrown, the referenced object will not be destroyed.
549 if (isPointer)
550 return false;
551
Eli Friedman5ed9b932010-06-03 20:39:03 +0000552 // If the class has a non-trivial destructor, we must be able to call it.
553 if (RD->hasTrivialDestructor())
554 return false;
555
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000556 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +0000557 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman5ed9b932010-06-03 20:39:03 +0000558 if (!Destructor)
559 return false;
560
561 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
562 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000563 PDiag(diag::err_access_dtor_exception) << Ty);
Sebastian Redl972041f2009-04-27 20:27:31 +0000564 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000565}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000566
John McCall5808ce42011-02-03 08:15:49 +0000567CXXMethodDecl *Sema::tryCaptureCXXThis() {
568 // Ignore block scopes: we can capture through them.
569 // Ignore nested enum scopes: we'll diagnose non-constant expressions
570 // where they're invalid, and other uses are legitimate.
571 // Don't ignore nested class scopes: you can't use 'this' in a local class.
John McCall469a1eb2011-02-02 13:00:07 +0000572 DeclContext *DC = CurContext;
John McCall5808ce42011-02-03 08:15:49 +0000573 while (true) {
574 if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
575 else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
576 else break;
577 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000578
John McCall5808ce42011-02-03 08:15:49 +0000579 // If we're not in an instance method, error out.
John McCall469a1eb2011-02-02 13:00:07 +0000580 CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC);
581 if (!method || !method->isInstance())
John McCall5808ce42011-02-03 08:15:49 +0000582 return 0;
John McCall469a1eb2011-02-02 13:00:07 +0000583
584 // Mark that we're closing on 'this' in all the block scopes, if applicable.
585 for (unsigned idx = FunctionScopes.size() - 1;
586 isa<BlockScopeInfo>(FunctionScopes[idx]);
587 --idx)
588 cast<BlockScopeInfo>(FunctionScopes[idx])->CapturesCXXThis = true;
589
John McCall5808ce42011-02-03 08:15:49 +0000590 return method;
591}
592
593ExprResult Sema::ActOnCXXThis(SourceLocation loc) {
594 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
595 /// is a non-lvalue expression whose value is the address of the object for
596 /// which the function is called.
597
598 CXXMethodDecl *method = tryCaptureCXXThis();
599 if (!method) return Diag(loc, diag::err_invalid_this_use);
600
601 return Owned(new (Context) CXXThisExpr(loc, method->getThisType(Context),
John McCall469a1eb2011-02-02 13:00:07 +0000602 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000603}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000604
John McCall60d7b3a2010-08-24 06:29:42 +0000605ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000606Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000607 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000608 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000609 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000610 if (!TypeRep)
611 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000612
John McCall9d125032010-01-15 18:39:57 +0000613 TypeSourceInfo *TInfo;
614 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
615 if (!TInfo)
616 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000617
618 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
619}
620
621/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
622/// Can be interpreted either as function-style casting ("int(x)")
623/// or class type construction ("ClassType(x,y,z)")
624/// or creation of a value-initialized type ("int()").
625ExprResult
626Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
627 SourceLocation LParenLoc,
628 MultiExprArg exprs,
629 SourceLocation RParenLoc) {
630 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000631 unsigned NumExprs = exprs.size();
632 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000633 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000634 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
635
Sebastian Redlf53597f2009-03-15 17:47:39 +0000636 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000637 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000638 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000639
Douglas Gregorab6677e2010-09-08 00:15:04 +0000640 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000641 LParenLoc,
642 Exprs, NumExprs,
643 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000644 }
645
Anders Carlssonbb60a502009-08-27 03:53:50 +0000646 if (Ty->isArrayType())
647 return ExprError(Diag(TyBeginLoc,
648 diag::err_value_init_for_array_type) << FullRange);
649 if (!Ty->isVoidType() &&
650 RequireCompleteType(TyBeginLoc, Ty,
651 PDiag(diag::err_invalid_incomplete_type_use)
652 << FullRange))
653 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000654
Anders Carlssonbb60a502009-08-27 03:53:50 +0000655 if (RequireNonAbstractType(TyBeginLoc, Ty,
656 diag::err_allocation_of_abstract_type))
657 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000658
659
Douglas Gregor506ae412009-01-16 18:33:17 +0000660 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000661 // If the expression list is a single expression, the type conversion
662 // expression is equivalent (in definedness, and if defined in meaning) to the
663 // corresponding cast expression.
664 //
665 if (NumExprs == 1) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000666 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +0000667 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +0000668 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000669 if (CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
John McCallf89e55a2010-11-18 06:31:45 +0000670 Kind, VK, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000671 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000672 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000673
674 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000675
John McCallf871d0c2010-08-07 06:22:56 +0000676 return Owned(CXXFunctionalCastExpr::Create(Context,
Douglas Gregorab6677e2010-09-08 00:15:04 +0000677 Ty.getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +0000678 VK, TInfo, TyBeginLoc, Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000679 Exprs[0], &BasePath,
680 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000681 }
682
Douglas Gregor19311e72010-09-08 21:40:08 +0000683 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
684 InitializationKind Kind
685 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
686 LParenLoc, RParenLoc)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000687 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor19311e72010-09-08 21:40:08 +0000688 LParenLoc, RParenLoc);
689 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
690 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000691
Douglas Gregor19311e72010-09-08 21:40:08 +0000692 // FIXME: Improve AST representation?
693 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000694}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000695
John McCall6ec278d2011-01-27 09:37:56 +0000696/// doesUsualArrayDeleteWantSize - Answers whether the usual
697/// operator delete[] for the given type has a size_t parameter.
698static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
699 QualType allocType) {
700 const RecordType *record =
701 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
702 if (!record) return false;
703
704 // Try to find an operator delete[] in class scope.
705
706 DeclarationName deleteName =
707 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
708 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
709 S.LookupQualifiedName(ops, record->getDecl());
710
711 // We're just doing this for information.
712 ops.suppressDiagnostics();
713
714 // Very likely: there's no operator delete[].
715 if (ops.empty()) return false;
716
717 // If it's ambiguous, it should be illegal to call operator delete[]
718 // on this thing, so it doesn't matter if we allocate extra space or not.
719 if (ops.isAmbiguous()) return false;
720
721 LookupResult::Filter filter = ops.makeFilter();
722 while (filter.hasNext()) {
723 NamedDecl *del = filter.next()->getUnderlyingDecl();
724
725 // C++0x [basic.stc.dynamic.deallocation]p2:
726 // A template instance is never a usual deallocation function,
727 // regardless of its signature.
728 if (isa<FunctionTemplateDecl>(del)) {
729 filter.erase();
730 continue;
731 }
732
733 // C++0x [basic.stc.dynamic.deallocation]p2:
734 // If class T does not declare [an operator delete[] with one
735 // parameter] but does declare a member deallocation function
736 // named operator delete[] with exactly two parameters, the
737 // second of which has type std::size_t, then this function
738 // is a usual deallocation function.
739 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
740 filter.erase();
741 continue;
742 }
743 }
744 filter.done();
745
746 if (!ops.isSingleResult()) return false;
747
748 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
749 return (del->getNumParams() == 2);
750}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000751
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000752/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
753/// @code new (memory) int[size][4] @endcode
754/// or
755/// @code ::new Foo(23, "hello") @endcode
756/// For the interpretation of this heap of arguments, consult the base version.
John McCall60d7b3a2010-08-24 06:29:42 +0000757ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000758Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000759 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000760 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000761 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000762 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000763 SourceLocation ConstructorRParen) {
Richard Smith34b41d92011-02-20 03:19:35 +0000764 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
765
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000766 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000767 // If the specified type is an array, unwrap it and save the expression.
768 if (D.getNumTypeObjects() > 0 &&
769 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
770 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith34b41d92011-02-20 03:19:35 +0000771 if (TypeContainsAuto)
772 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
773 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000774 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000775 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
776 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000777 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000778 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
779 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000780
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000781 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000782 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000783 }
784
Douglas Gregor043cad22009-09-11 00:18:58 +0000785 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000786 if (ArraySize) {
787 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000788 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
789 break;
790
791 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
792 if (Expr *NumElts = (Expr *)Array.NumElts) {
793 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
794 !NumElts->isIntegerConstantExpr(Context)) {
795 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
796 << NumElts->getSourceRange();
797 return ExprError();
798 }
799 }
800 }
801 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000802
Richard Smith34b41d92011-02-20 03:19:35 +0000803 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0, /*OwnedDecl=*/0,
804 /*AllowAuto=*/true);
John McCallbf1a0282010-06-04 23:28:52 +0000805 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000806 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000807 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000808
Mike Stump1eb44332009-09-09 15:08:12 +0000809 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000810 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000811 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000812 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000813 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000814 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000815 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000816 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000817 ConstructorLParen,
818 move(ConstructorArgs),
Richard Smith34b41d92011-02-20 03:19:35 +0000819 ConstructorRParen,
820 TypeContainsAuto);
Douglas Gregor3433cf72009-05-21 00:00:09 +0000821}
822
John McCall60d7b3a2010-08-24 06:29:42 +0000823ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000824Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
825 SourceLocation PlacementLParen,
826 MultiExprArg PlacementArgs,
827 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000828 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000829 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000830 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000831 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000832 SourceLocation ConstructorLParen,
833 MultiExprArg ConstructorArgs,
Richard Smith34b41d92011-02-20 03:19:35 +0000834 SourceLocation ConstructorRParen,
835 bool TypeMayContainAuto) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000836 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000837
Richard Smith34b41d92011-02-20 03:19:35 +0000838 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
839 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
840 if (ConstructorArgs.size() == 0)
841 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
842 << AllocType << TypeRange);
843 if (ConstructorArgs.size() != 1) {
844 Expr *FirstBad = ConstructorArgs.get()[1];
845 return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
846 diag::err_auto_new_ctor_multiple_expressions)
847 << AllocType << TypeRange);
848 }
849 QualType DeducedType;
850 if (!DeduceAutoType(AllocType, ConstructorArgs.get()[0], DeducedType))
851 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
852 << AllocType
853 << ConstructorArgs.get()[0]->getType()
854 << TypeRange
855 << ConstructorArgs.get()[0]->getSourceRange());
856
857 AllocType = DeducedType;
858 AllocTypeInfo = Context.getTrivialTypeSourceInfo(AllocType, StartLoc);
859 }
860
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000861 // Per C++0x [expr.new]p5, the type being constructed may be a
862 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +0000863 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000864 if (const ConstantArrayType *Array
865 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000866 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
867 Context.getSizeType(),
868 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000869 AllocType = Array->getElementType();
870 }
871 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000872
Douglas Gregora0750762010-10-06 16:00:31 +0000873 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
874 return ExprError();
875
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000876 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000877
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000878 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
879 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000880 if (ArraySize && !ArraySize->isTypeDependent()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000881
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000882 QualType SizeType = ArraySize->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000883
John McCall60d7b3a2010-08-24 06:29:42 +0000884 ExprResult ConvertedSize
John McCall9ae2f072010-08-23 23:25:46 +0000885 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000886 PDiag(diag::err_array_size_not_integral),
887 PDiag(diag::err_array_size_incomplete_type)
888 << ArraySize->getSourceRange(),
889 PDiag(diag::err_array_size_explicit_conversion),
890 PDiag(diag::note_array_size_conversion),
891 PDiag(diag::err_array_size_ambiguous_conversion),
892 PDiag(diag::note_array_size_conversion),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000893 PDiag(getLangOptions().CPlusPlus0x? 0
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000894 : diag::ext_array_size_conversion));
895 if (ConvertedSize.isInvalid())
896 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000897
John McCall9ae2f072010-08-23 23:25:46 +0000898 ArraySize = ConvertedSize.take();
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000899 SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000900 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000901 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000902
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000903 // Let's see if this is a constant < 0. If so, we reject it out of hand.
904 // We don't care about special rules, so we tell the machinery it's not
905 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000906 if (!ArraySize->isValueDependent()) {
907 llvm::APSInt Value;
908 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
909 if (Value < llvm::APSInt(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000910 llvm::APInt::getNullValue(Value.getBitWidth()),
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000911 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000912 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000913 diag::err_typecheck_negative_array_size)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000914 << ArraySize->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000915
Douglas Gregor2767ce22010-08-18 00:39:00 +0000916 if (!AllocType->isDependentType()) {
917 unsigned ActiveSizeBits
918 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
919 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000920 Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000921 diag::err_array_too_large)
922 << Value.toString(10)
923 << ArraySize->getSourceRange();
924 return ExprError();
925 }
926 }
Douglas Gregor4bd40312010-07-13 15:54:32 +0000927 } else if (TypeIdParens.isValid()) {
928 // Can't have dynamic array size when the type-id is in parentheses.
929 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
930 << ArraySize->getSourceRange()
931 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
932 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000933
Douglas Gregor4bd40312010-07-13 15:54:32 +0000934 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +0000935 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000936 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000937
Eli Friedman73c39ab2009-10-20 08:27:19 +0000938 ImpCastExprToType(ArraySize, Context.getSizeType(),
John McCall2de56d12010-08-25 11:45:40 +0000939 CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000940 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000941
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000942 FunctionDecl *OperatorNew = 0;
943 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000944 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
945 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000946
Sebastian Redl28507842009-02-26 14:39:58 +0000947 if (!AllocType->isDependentType() &&
948 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
949 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000950 SourceRange(PlacementLParen, PlacementRParen),
951 UseGlobal, AllocType, ArraySize, PlaceArgs,
952 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000953 return ExprError();
John McCall6ec278d2011-01-27 09:37:56 +0000954
955 // If this is an array allocation, compute whether the usual array
956 // deallocation function for the type has a size_t parameter.
957 bool UsualArrayDeleteWantsSize = false;
958 if (ArraySize && !AllocType->isDependentType())
959 UsualArrayDeleteWantsSize
960 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
961
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000962 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000963 if (OperatorNew) {
964 // Add default arguments, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000965 const FunctionProtoType *Proto =
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000966 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000967 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000968 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000969
Anders Carlsson28e94832010-05-03 02:07:56 +0000970 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000971 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlsson28e94832010-05-03 02:07:56 +0000972 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000973 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000974
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000975 NumPlaceArgs = AllPlaceArgs.size();
976 if (NumPlaceArgs > 0)
977 PlaceArgs = &AllPlaceArgs[0];
978 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000979
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000980 bool Init = ConstructorLParen.isValid();
981 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000982 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000983 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
984 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +0000985 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000986
Anders Carlsson48c95012010-05-03 15:45:23 +0000987 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +0000988 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +0000989 SourceRange InitRange(ConsArgs[0]->getLocStart(),
990 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000991
Anders Carlsson48c95012010-05-03 15:45:23 +0000992 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
993 return ExprError();
994 }
995
Douglas Gregor99a2e602009-12-16 01:38:02 +0000996 if (!AllocType->isDependentType() &&
997 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
998 // C++0x [expr.new]p15:
999 // A new-expression that creates an object of type T initializes that
1000 // object as follows:
1001 InitializationKind Kind
1002 // - If the new-initializer is omitted, the object is default-
1003 // initialized (8.5); if no initialization is performed,
1004 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001005 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001006 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor99a2e602009-12-16 01:38:02 +00001007 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001008 : InitializationKind::CreateDirect(TypeRange.getBegin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001009 ConstructorLParen,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001010 ConstructorRParen);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001011
Douglas Gregor99a2e602009-12-16 01:38:02 +00001012 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00001013 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001014 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001015 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001016 move(ConstructorArgs));
1017 if (FullInit.isInvalid())
1018 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001019
1020 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor99a2e602009-12-16 01:38:02 +00001021 // constructor call, which CXXNewExpr handles directly.
1022 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1023 if (CXXBindTemporaryExpr *Binder
1024 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1025 FullInitExpr = Binder->getSubExpr();
1026 if (CXXConstructExpr *Construct
1027 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1028 Constructor = Construct->getConstructor();
1029 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1030 AEnd = Construct->arg_end();
1031 A != AEnd; ++A)
John McCall3fa5cae2010-10-26 07:05:15 +00001032 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001033 } else {
1034 // Take the converted initializer.
1035 ConvertedConstructorArgs.push_back(FullInit.release());
1036 }
1037 } else {
1038 // No initialization required.
1039 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001040
Douglas Gregor99a2e602009-12-16 01:38:02 +00001041 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001042 NumConsArgs = ConvertedConstructorArgs.size();
1043 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001044 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001045
Douglas Gregor6d908702010-02-26 05:06:18 +00001046 // Mark the new and delete operators as referenced.
1047 if (OperatorNew)
1048 MarkDeclarationReferenced(StartLoc, OperatorNew);
1049 if (OperatorDelete)
1050 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1051
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001052 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001053
Sebastian Redlf53597f2009-03-15 17:47:39 +00001054 PlacementArgs.release();
1055 ConstructorArgs.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001056
Ted Kremenekad7fe862010-02-11 22:51:03 +00001057 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001058 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001059 ArraySize, Constructor, Init,
1060 ConsArgs, NumConsArgs, OperatorDelete,
John McCall6ec278d2011-01-27 09:37:56 +00001061 UsualArrayDeleteWantsSize,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001062 ResultType, AllocTypeInfo,
1063 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001064 Init ? ConstructorRParen :
Chandler Carruth428edaf2010-10-25 08:47:36 +00001065 TypeRange.getEnd(),
1066 ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001067}
1068
1069/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1070/// in a new-expression.
1071/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +00001072bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00001073 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001074 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1075 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +00001076 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001077 return Diag(Loc, diag::err_bad_new_type)
1078 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001079 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001080 return Diag(Loc, diag::err_bad_new_type)
1081 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001082 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +00001083 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001084 PDiag(diag::err_new_incomplete_type)
1085 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001086 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +00001087 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +00001088 diag::err_allocation_of_abstract_type))
1089 return true;
Douglas Gregora0750762010-10-06 16:00:31 +00001090 else if (AllocType->isVariablyModifiedType())
1091 return Diag(Loc, diag::err_variably_modified_new_type)
1092 << AllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001093
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001094 return false;
1095}
1096
Douglas Gregor6d908702010-02-26 05:06:18 +00001097/// \brief Determine whether the given function is a non-placement
1098/// deallocation function.
1099static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1100 if (FD->isInvalidDecl())
1101 return false;
1102
1103 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1104 return Method->isUsualDeallocationFunction();
1105
1106 return ((FD->getOverloadedOperator() == OO_Delete ||
1107 FD->getOverloadedOperator() == OO_Array_Delete) &&
1108 FD->getNumParams() == 1);
1109}
1110
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001111/// FindAllocationFunctions - Finds the overloads of operator new and delete
1112/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001113bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1114 bool UseGlobal, QualType AllocType,
1115 bool IsArray, Expr **PlaceArgs,
1116 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001117 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +00001118 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001119 // --- Choosing an allocation function ---
1120 // C++ 5.3.4p8 - 14 & 18
1121 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1122 // in the scope of the allocated class.
1123 // 2) If an array size is given, look for operator new[], else look for
1124 // operator new.
1125 // 3) The first argument is always size_t. Append the arguments from the
1126 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001127
1128 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
1129 // We don't care about the actual value of this argument.
1130 // FIXME: Should the Sema create the expression and embed it in the syntax
1131 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001132 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Anders Carlssond67c4c32009-08-16 20:29:29 +00001133 Context.Target.getPointerWidth(0)),
1134 Context.getSizeType(),
1135 SourceLocation());
1136 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001137 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1138
Douglas Gregor6d908702010-02-26 05:06:18 +00001139 // C++ [expr.new]p8:
1140 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001141 // function's name is operator new and the deallocation function's
Douglas Gregor6d908702010-02-26 05:06:18 +00001142 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001143 // type, the allocation function's name is operator new[] and the
1144 // deallocation function's name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001145 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1146 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001147 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1148 IsArray ? OO_Array_Delete : OO_Delete);
1149
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001150 QualType AllocElemType = Context.getBaseElementType(AllocType);
1151
1152 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001153 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001154 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001155 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001156 AllocArgs.size(), Record, /*AllowMissing=*/true,
1157 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001158 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001159 }
1160 if (!OperatorNew) {
1161 // Didn't find a member overload. Look for a global one.
1162 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001163 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001164 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001165 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1166 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001167 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001168 }
1169
John McCall9c82afc2010-04-20 02:18:25 +00001170 // We don't need an operator delete if we're running under
1171 // -fno-exceptions.
1172 if (!getLangOptions().Exceptions) {
1173 OperatorDelete = 0;
1174 return false;
1175 }
1176
Anders Carlssond9583892009-05-31 20:26:12 +00001177 // FindAllocationOverload can change the passed in arguments, so we need to
1178 // copy them back.
1179 if (NumPlaceArgs > 0)
1180 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Douglas Gregor6d908702010-02-26 05:06:18 +00001182 // C++ [expr.new]p19:
1183 //
1184 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001185 // deallocation function's name is looked up in the global
Douglas Gregor6d908702010-02-26 05:06:18 +00001186 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001187 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6d908702010-02-26 05:06:18 +00001188 // the scope of T. If this lookup fails to find the name, or if
1189 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001190 // deallocation function's name is looked up in the global scope.
Douglas Gregor6d908702010-02-26 05:06:18 +00001191 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001192 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001193 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001194 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001195 LookupQualifiedName(FoundDelete, RD);
1196 }
John McCall90c8c572010-03-18 08:19:33 +00001197 if (FoundDelete.isAmbiguous())
1198 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001199
1200 if (FoundDelete.empty()) {
1201 DeclareGlobalNewDelete();
1202 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1203 }
1204
1205 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001206
1207 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1208
John McCalledeb6c92010-09-14 21:34:24 +00001209 // Whether we're looking for a placement operator delete is dictated
1210 // by whether we selected a placement operator new, not by whether
1211 // we had explicit placement arguments. This matters for things like
1212 // struct A { void *operator new(size_t, int = 0); ... };
1213 // A *a = new A()
1214 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1215
1216 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001217 // C++ [expr.new]p20:
1218 // A declaration of a placement deallocation function matches the
1219 // declaration of a placement allocation function if it has the
1220 // same number of parameters and, after parameter transformations
1221 // (8.3.5), all parameter types except the first are
1222 // identical. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001223 //
Douglas Gregor6d908702010-02-26 05:06:18 +00001224 // To perform this comparison, we compute the function type that
1225 // the deallocation function should have, and use that type both
1226 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001227 //
1228 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001229 QualType ExpectedFunctionType;
1230 {
1231 const FunctionProtoType *Proto
1232 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001233
Douglas Gregor6d908702010-02-26 05:06:18 +00001234 llvm::SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001235 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6d908702010-02-26 05:06:18 +00001236 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1237 ArgTypes.push_back(Proto->getArgType(I));
1238
John McCalle23cf432010-12-14 08:05:40 +00001239 FunctionProtoType::ExtProtoInfo EPI;
1240 EPI.Variadic = Proto->isVariadic();
1241
Douglas Gregor6d908702010-02-26 05:06:18 +00001242 ExpectedFunctionType
1243 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalle23cf432010-12-14 08:05:40 +00001244 ArgTypes.size(), EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001245 }
1246
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001247 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001248 DEnd = FoundDelete.end();
1249 D != DEnd; ++D) {
1250 FunctionDecl *Fn = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001251 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6d908702010-02-26 05:06:18 +00001252 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1253 // Perform template argument deduction to try to match the
1254 // expected function type.
1255 TemplateDeductionInfo Info(Context, StartLoc);
1256 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1257 continue;
1258 } else
1259 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1260
1261 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001262 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001263 }
1264 } else {
1265 // C++ [expr.new]p20:
1266 // [...] Any non-placement deallocation function matches a
1267 // non-placement allocation function. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001268 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001269 DEnd = FoundDelete.end();
1270 D != DEnd; ++D) {
1271 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1272 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001273 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001274 }
1275 }
1276
1277 // C++ [expr.new]p20:
1278 // [...] If the lookup finds a single matching deallocation
1279 // function, that function will be called; otherwise, no
1280 // deallocation function will be called.
1281 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001282 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001283
1284 // C++0x [expr.new]p20:
1285 // If the lookup finds the two-parameter form of a usual
1286 // deallocation function (3.7.4.2) and that function, considered
1287 // as a placement deallocation function, would have been
1288 // selected as a match for the allocation function, the program
1289 // is ill-formed.
1290 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1291 isNonPlacementDeallocationFunction(OperatorDelete)) {
1292 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001293 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001294 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1295 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1296 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001297 } else {
1298 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001299 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001300 }
1301 }
1302
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001303 return false;
1304}
1305
Sebastian Redl7f662392008-12-04 22:20:51 +00001306/// FindAllocationOverload - Find an fitting overload for the allocation
1307/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001308bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1309 DeclarationName Name, Expr** Args,
1310 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001311 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001312 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1313 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001314 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001315 if (AllowMissing)
1316 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001317 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001318 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001319 }
1320
John McCall90c8c572010-03-18 08:19:33 +00001321 if (R.isAmbiguous())
1322 return true;
1323
1324 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001325
John McCall5769d612010-02-08 23:07:23 +00001326 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001327 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001328 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001329 // Even member operator new/delete are implicitly treated as
1330 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001331 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001332
John McCall9aa472c2010-03-19 07:35:19 +00001333 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1334 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001335 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1336 Candidates,
1337 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001338 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001339 }
1340
John McCall9aa472c2010-03-19 07:35:19 +00001341 FunctionDecl *Fn = cast<FunctionDecl>(D);
1342 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001343 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001344 }
1345
1346 // Do the resolution.
1347 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001348 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001349 case OR_Success: {
1350 // Got one!
1351 FunctionDecl *FnDecl = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00001352 MarkDeclarationReferenced(StartLoc, FnDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001353 // The first argument is size_t, and the first parameter must be size_t,
1354 // too. This is checked on declaration and can be assumed. (It can't be
1355 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001356 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001357 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1358 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
John McCall60d7b3a2010-08-24 06:29:42 +00001359 ExprResult Result
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001360 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001361 Context,
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001362 FnDecl->getParamDecl(i)),
1363 SourceLocation(),
John McCall3fa5cae2010-10-26 07:05:15 +00001364 Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001365 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001366 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001367
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001368 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001369 }
1370 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001371 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001372 return false;
1373 }
1374
1375 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001376 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001377 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001378 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001379 return true;
1380
1381 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001382 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001383 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001384 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001385 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001386
1387 case OR_Deleted:
1388 Diag(StartLoc, diag::err_ovl_deleted_call)
1389 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00001390 << Name
1391 << Best->Function->getMessageUnavailableAttr(
1392 !Best->Function->isDeleted())
1393 << Range;
John McCall120d63c2010-08-24 20:38:10 +00001394 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001395 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001396 }
1397 assert(false && "Unreachable, bad result from BestViableFunction");
1398 return true;
1399}
1400
1401
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001402/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1403/// delete. These are:
1404/// @code
1405/// void* operator new(std::size_t) throw(std::bad_alloc);
1406/// void* operator new[](std::size_t) throw(std::bad_alloc);
1407/// void operator delete(void *) throw();
1408/// void operator delete[](void *) throw();
1409/// @endcode
1410/// Note that the placement and nothrow forms of new are *not* implicitly
1411/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001412void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001413 if (GlobalNewDeleteDeclared)
1414 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001415
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001416 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001417 // [...] The following allocation and deallocation functions (18.4) are
1418 // implicitly declared in global scope in each translation unit of a
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001419 // program
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001420 //
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001421 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001422 // void* operator new[](std::size_t) throw(std::bad_alloc);
1423 // void operator delete(void*) throw();
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001424 // void operator delete[](void*) throw();
1425 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001426 // These implicit declarations introduce only the function names operator
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001427 // new, operator new[], operator delete, operator delete[].
1428 //
1429 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1430 // "std" or "bad_alloc" as necessary to form the exception specification.
1431 // However, we do not make these implicit declarations visible to name
1432 // lookup.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001433 if (!StdBadAlloc) {
1434 // The "std::bad_alloc" class has not yet been declared, so build it
1435 // implicitly.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001436 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1437 getOrCreateStdNamespace(),
1438 SourceLocation(),
1439 &PP.getIdentifierTable().get("bad_alloc"),
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001440 SourceLocation(), 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001441 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001442 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001443
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001444 GlobalNewDeleteDeclared = true;
1445
1446 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1447 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001448 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001449
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001450 DeclareGlobalAllocationFunction(
1451 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001452 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001453 DeclareGlobalAllocationFunction(
1454 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001455 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001456 DeclareGlobalAllocationFunction(
1457 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1458 Context.VoidTy, VoidPtr);
1459 DeclareGlobalAllocationFunction(
1460 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1461 Context.VoidTy, VoidPtr);
1462}
1463
1464/// DeclareGlobalAllocationFunction - Declares a single implicit global
1465/// allocation function if it doesn't already exist.
1466void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001467 QualType Return, QualType Argument,
1468 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001469 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1470
1471 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001472 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001473 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001474 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001475 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001476 // Only look at non-template functions, as it is the predefined,
1477 // non-templated allocation function we are trying to declare here.
1478 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1479 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001480 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001481 Func->getParamDecl(0)->getType().getUnqualifiedType());
1482 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001483 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1484 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001485 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001486 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001487 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001488 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001489 }
1490 }
1491
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001492 QualType BadAllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001493 bool HasBadAllocExceptionSpec
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001494 = (Name.getCXXOverloadedOperator() == OO_New ||
1495 Name.getCXXOverloadedOperator() == OO_Array_New);
1496 if (HasBadAllocExceptionSpec) {
1497 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001498 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001499 }
John McCalle23cf432010-12-14 08:05:40 +00001500
1501 FunctionProtoType::ExtProtoInfo EPI;
1502 EPI.HasExceptionSpec = true;
1503 if (HasBadAllocExceptionSpec) {
1504 EPI.NumExceptions = 1;
1505 EPI.Exceptions = &BadAllocType;
1506 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001507
John McCalle23cf432010-12-14 08:05:40 +00001508 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001509 FunctionDecl *Alloc =
1510 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001511 FnType, /*TInfo=*/0, SC_None,
1512 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001513 Alloc->setImplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001514
Nuno Lopesfc284482009-12-16 16:59:22 +00001515 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001516 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001517
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001518 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001519 0, Argument, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00001520 SC_None,
1521 SC_None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001522 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001523
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001524 // FIXME: Also add this declaration to the IdentifierResolver, but
1525 // make sure it is at the end of the chain to coincide with the
1526 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001527 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001528}
1529
Anders Carlsson78f74552009-11-15 18:45:20 +00001530bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1531 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001532 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001533 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001534 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001535 LookupQualifiedName(Found, RD);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001536
John McCalla24dc2e2009-11-17 02:14:36 +00001537 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001538 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001539
Chandler Carruth23893242010-06-28 00:30:51 +00001540 Found.suppressDiagnostics();
1541
John McCall046a7462010-08-04 00:31:26 +00001542 llvm::SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001543 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1544 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001545 NamedDecl *ND = (*F)->getUnderlyingDecl();
1546
1547 // Ignore template operator delete members from the check for a usual
1548 // deallocation function.
1549 if (isa<FunctionTemplateDecl>(ND))
1550 continue;
1551
1552 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001553 Matches.push_back(F.getPair());
1554 }
1555
1556 // There's exactly one suitable operator; pick it.
1557 if (Matches.size() == 1) {
1558 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1559 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1560 Matches[0]);
1561 return false;
1562
1563 // We found multiple suitable operators; complain about the ambiguity.
1564 } else if (!Matches.empty()) {
1565 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1566 << Name << RD;
1567
1568 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1569 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1570 Diag((*F)->getUnderlyingDecl()->getLocation(),
1571 diag::note_member_declared_here) << Name;
1572 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001573 }
1574
1575 // We did find operator delete/operator delete[] declarations, but
1576 // none of them were suitable.
1577 if (!Found.empty()) {
1578 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1579 << Name << RD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001580
Anders Carlsson78f74552009-11-15 18:45:20 +00001581 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
John McCall046a7462010-08-04 00:31:26 +00001582 F != FEnd; ++F)
1583 Diag((*F)->getUnderlyingDecl()->getLocation(),
1584 diag::note_member_declared_here) << Name;
Anders Carlsson78f74552009-11-15 18:45:20 +00001585
1586 return true;
1587 }
1588
1589 // Look for a global declaration.
1590 DeclareGlobalNewDelete();
1591 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001592
Anders Carlsson78f74552009-11-15 18:45:20 +00001593 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1594 Expr* DeallocArgs[1];
1595 DeallocArgs[0] = &Null;
1596 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1597 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1598 Operator))
1599 return true;
1600
1601 assert(Operator && "Did not find a deallocation function!");
1602 return false;
1603}
1604
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001605/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1606/// @code ::delete ptr; @endcode
1607/// or
1608/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001609ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001610Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John McCall9ae2f072010-08-23 23:25:46 +00001611 bool ArrayForm, Expr *Ex) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001612 // C++ [expr.delete]p1:
1613 // The operand shall have a pointer type, or a class type having a single
1614 // conversion function to a pointer type. The result has type void.
1615 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001616 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1617
Anders Carlssond67c4c32009-08-16 20:29:29 +00001618 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001619 bool ArrayFormAsWritten = ArrayForm;
John McCall6ec278d2011-01-27 09:37:56 +00001620 bool UsualArrayDeleteWantsSize = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Sebastian Redl28507842009-02-26 14:39:58 +00001622 if (!Ex->isTypeDependent()) {
1623 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001624
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001625 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001626 if (RequireCompleteType(StartLoc, Type,
Douglas Gregor254a9422010-07-29 14:44:35 +00001627 PDiag(diag::err_delete_incomplete_class_type)))
1628 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001629
John McCall32daa422010-03-31 01:36:47 +00001630 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1631
Fariborz Jahanian53462782009-09-11 21:44:33 +00001632 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001633 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001634 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001635 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001636 NamedDecl *D = I.getDecl();
1637 if (isa<UsingShadowDecl>(D))
1638 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1639
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001640 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001641 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001642 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001643
John McCall32daa422010-03-31 01:36:47 +00001644 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001645
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001646 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1647 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001648 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001649 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001650 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001651 if (ObjectPtrConversions.size() == 1) {
1652 // We have a single conversion to a pointer-to-object type. Perform
1653 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001654 // TODO: don't redo the conversion calculation.
John McCall32daa422010-03-31 01:36:47 +00001655 if (!PerformImplicitConversion(Ex,
1656 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001657 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001658 Type = Ex->getType();
1659 }
1660 }
1661 else if (ObjectPtrConversions.size() > 1) {
1662 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1663 << Type << Ex->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001664 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1665 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001666 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001667 }
Sebastian Redl28507842009-02-26 14:39:58 +00001668 }
1669
Sebastian Redlf53597f2009-03-15 17:47:39 +00001670 if (!Type->isPointerType())
1671 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1672 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001673
Ted Kremenek6217b802009-07-29 21:53:49 +00001674 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor94a61572010-05-24 17:01:56 +00001675 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001676 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregor94a61572010-05-24 17:01:56 +00001677 // effectively bans deletion of "void*". However, most compilers support
1678 // this, so we treat it as a warning unless we're in a SFINAE context.
1679 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1680 << Type << Ex->getSourceRange();
1681 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001682 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1683 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001684 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001685 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001686 PDiag(diag::warn_delete_incomplete)
1687 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001688 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001689
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001690 // C++ [expr.delete]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001691 // [Note: a pointer to a const type can be the operand of a
1692 // delete-expression; it is not necessary to cast away the constness
1693 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001694 // of the delete-expression. ]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001695 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
John McCall2de56d12010-08-25 11:45:40 +00001696 CK_NoOp);
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001697
1698 if (Pointee->isArrayType() && !ArrayForm) {
1699 Diag(StartLoc, diag::warn_delete_array_type)
1700 << Type << Ex->getSourceRange()
1701 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1702 ArrayForm = true;
1703 }
1704
Anders Carlssond67c4c32009-08-16 20:29:29 +00001705 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1706 ArrayForm ? OO_Array_Delete : OO_Delete);
1707
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001708 QualType PointeeElem = Context.getBaseElementType(Pointee);
1709 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001710 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1711
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001712 if (!UseGlobal &&
Anders Carlsson78f74552009-11-15 18:45:20 +00001713 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001714 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001715
John McCall6ec278d2011-01-27 09:37:56 +00001716 // If we're allocating an array of records, check whether the
1717 // usual operator delete[] has a size_t parameter.
1718 if (ArrayForm) {
1719 // If the user specifically asked to use the global allocator,
1720 // we'll need to do the lookup into the class.
1721 if (UseGlobal)
1722 UsualArrayDeleteWantsSize =
1723 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1724
1725 // Otherwise, the usual operator delete[] should be the
1726 // function we just found.
1727 else if (isa<CXXMethodDecl>(OperatorDelete))
1728 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1729 }
1730
Anders Carlsson78f74552009-11-15 18:45:20 +00001731 if (!RD->hasTrivialDestructor())
Douglas Gregor9b623632010-10-12 23:32:35 +00001732 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001733 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001734 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00001735 DiagnoseUseOfDecl(Dtor, StartLoc);
1736 }
Anders Carlssond67c4c32009-08-16 20:29:29 +00001737 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001738
Anders Carlssond67c4c32009-08-16 20:29:29 +00001739 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001740 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001741 DeclareGlobalNewDelete();
1742 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001743 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001744 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001745 OperatorDelete))
1746 return ExprError();
1747 }
Mike Stump1eb44332009-09-09 15:08:12 +00001748
John McCall9c82afc2010-04-20 02:18:25 +00001749 MarkDeclarationReferenced(StartLoc, OperatorDelete);
John McCall6ec278d2011-01-27 09:37:56 +00001750
Douglas Gregord880f522011-02-01 15:50:11 +00001751 // Check access and ambiguity of operator delete and destructor.
1752 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1753 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1754 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
1755 CheckDestructorAccess(Ex->getExprLoc(), Dtor,
1756 PDiag(diag::err_access_dtor) << PointeeElem);
1757 }
1758 }
1759
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001760 }
1761
Sebastian Redlf53597f2009-03-15 17:47:39 +00001762 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall6ec278d2011-01-27 09:37:56 +00001763 ArrayFormAsWritten,
1764 UsualArrayDeleteWantsSize,
1765 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001766}
1767
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001768/// \brief Check the use of the given variable as a C++ condition in an if,
1769/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001770ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00001771 SourceLocation StmtLoc,
1772 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001773 QualType T = ConditionVar->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001774
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001775 // C++ [stmt.select]p2:
1776 // The declarator shall not specify a function or an array.
1777 if (T->isFunctionType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001778 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001779 diag::err_invalid_use_of_function_type)
1780 << ConditionVar->getSourceRange());
1781 else if (T->isArrayType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001782 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001783 diag::err_invalid_use_of_array_type)
1784 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001785
Douglas Gregor586596f2010-05-06 17:25:47 +00001786 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001787 ConditionVar->getLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00001788 ConditionVar->getType().getNonReferenceType(),
John McCall09431682010-11-18 19:01:18 +00001789 VK_LValue);
Douglas Gregorff331c12010-07-25 18:17:45 +00001790 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
Douglas Gregor586596f2010-05-06 17:25:47 +00001791 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001792
Douglas Gregor586596f2010-05-06 17:25:47 +00001793 return Owned(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001794}
1795
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001796/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1797bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1798 // C++ 6.4p4:
1799 // The value of a condition that is an initialized declaration in a statement
1800 // other than a switch statement is the value of the declared variable
1801 // implicitly converted to type bool. If that conversion is ill-formed, the
1802 // program is ill-formed.
1803 // The value of a condition that is an expression is the value of the
1804 // expression, implicitly converted to bool.
1805 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001806 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001807}
Douglas Gregor77a52232008-09-12 00:47:35 +00001808
1809/// Helper function to determine whether this is the (deprecated) C++
1810/// conversion from a string literal to a pointer to non-const char or
1811/// non-const wchar_t (for narrow and wide string literals,
1812/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001813bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001814Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1815 // Look inside the implicit cast, if it exists.
1816 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1817 From = Cast->getSubExpr();
1818
1819 // A string literal (2.13.4) that is not a wide string literal can
1820 // be converted to an rvalue of type "pointer to char"; a wide
1821 // string literal can be converted to an rvalue of type "pointer
1822 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00001823 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00001824 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001825 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001826 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001827 // This conversion is considered only when there is an
1828 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001829 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001830 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1831 (!StrLit->isWide() &&
1832 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1833 ToPointeeType->getKind() == BuiltinType::Char_S))))
1834 return true;
1835 }
1836
1837 return false;
1838}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001839
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001840static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00001841 SourceLocation CastLoc,
1842 QualType Ty,
1843 CastKind Kind,
1844 CXXMethodDecl *Method,
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001845 NamedDecl *FoundDecl,
John McCall2de56d12010-08-25 11:45:40 +00001846 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001847 switch (Kind) {
1848 default: assert(0 && "Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00001849 case CK_ConstructorConversion: {
John McCallca0408f2010-08-23 06:44:23 +00001850 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001851
Douglas Gregorba70ab62010-04-16 22:17:36 +00001852 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
John McCallf312b1e2010-08-26 23:41:50 +00001853 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00001854 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00001855 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001856
1857 ExprResult Result =
1858 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
John McCall7a1fad32010-08-24 07:32:53 +00001859 move_arg(ConstructorArgs),
Chandler Carruth428edaf2010-10-25 08:47:36 +00001860 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete,
1861 SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00001862 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00001863 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001864
Douglas Gregorba70ab62010-04-16 22:17:36 +00001865 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1866 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001867
John McCall2de56d12010-08-25 11:45:40 +00001868 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001869 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001870
Douglas Gregorba70ab62010-04-16 22:17:36 +00001871 // Create an implicit call expr that calls it.
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001872 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00001873 if (Result.isInvalid())
1874 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001875
Douglas Gregorf2ae5262011-01-20 00:18:04 +00001876 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00001877 }
1878 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001879}
Douglas Gregorba70ab62010-04-16 22:17:36 +00001880
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001881/// PerformImplicitConversion - Perform an implicit conversion of the
1882/// expression From to the type ToType using the pre-computed implicit
1883/// conversion sequence ICS. Returns true if there was an error, false
1884/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001885/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001886/// used in the error message.
1887bool
1888Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1889 const ImplicitConversionSequence &ICS,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001890 AssignmentAction Action, bool CStyle) {
John McCall1d318332010-01-12 00:44:57 +00001891 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001892 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001893 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001894 CStyle))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001895 return true;
1896 break;
1897
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001898 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001899
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001900 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00001901 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001902 QualType BeforeToType;
1903 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00001904 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001905
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001906 // If the user-defined conversion is specified by a conversion function,
1907 // the initial standard conversion sequence converts the source type to
1908 // the implicit object parameter of the conversion function.
1909 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00001910 } else {
1911 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00001912 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001913 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001914 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001915 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001916 // initial standard conversion sequence converts the source type to the
1917 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001918 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1919 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001920 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00001921 // Watch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001922 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001923 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001924 ICS.UserDefined.Before, AA_Converting,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001925 CStyle))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001926 return true;
1927 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001928
1929 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00001930 = BuildCXXCastArgument(*this,
1931 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00001932 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001933 CastKind, cast<CXXMethodDecl>(FD),
1934 ICS.UserDefined.FoundConversionFunction,
John McCall9ae2f072010-08-23 23:25:46 +00001935 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00001936
1937 if (CastArg.isInvalid())
1938 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001939
1940 From = CastArg.takeAs<Expr>();
1941
Eli Friedmand8889622009-11-27 04:41:50 +00001942 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001943 AA_Converting, CStyle);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001944 }
John McCall1d318332010-01-12 00:44:57 +00001945
1946 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00001947 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00001948 PDiag(diag::err_typecheck_ambiguous_condition)
1949 << From->getSourceRange());
1950 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001951
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001952 case ImplicitConversionSequence::EllipsisConversion:
1953 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001954 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001955
1956 case ImplicitConversionSequence::BadConversion:
1957 return true;
1958 }
1959
1960 // Everything went well.
1961 return false;
1962}
1963
1964/// PerformImplicitConversion - Perform an implicit conversion of the
1965/// expression From to the type ToType by following the standard
1966/// conversion sequence SCS. Returns true if there was an error, false
1967/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001968/// expression. Flavor is the context in which we're performing this
1969/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001970bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001971Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001972 const StandardConversionSequence& SCS,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001973 AssignmentAction Action, bool CStyle) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001974 // Overall FIXME: we are recomputing too many types here and doing far too
1975 // much extra work. What this means is that we need to keep track of more
1976 // information that is computed when we try the implicit conversion initially,
1977 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001978 QualType FromType = From->getType();
1979
Douglas Gregor225c41e2008-11-03 19:09:14 +00001980 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001981 // FIXME: When can ToType be a reference type?
1982 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001983 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00001984 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001985 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00001986 MultiExprArg(*this, &From, 1),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001987 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001988 ConstructorArgs))
1989 return true;
John McCall60d7b3a2010-08-24 06:29:42 +00001990 ExprResult FromResult =
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001991 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1992 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00001993 move_arg(ConstructorArgs),
1994 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00001995 CXXConstructExpr::CK_Complete,
1996 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001997 if (FromResult.isInvalid())
1998 return true;
1999 From = FromResult.takeAs<Expr>();
2000 return false;
2001 }
John McCall60d7b3a2010-08-24 06:29:42 +00002002 ExprResult FromResult =
Mike Stump1eb44332009-09-09 15:08:12 +00002003 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2004 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00002005 MultiExprArg(*this, &From, 1),
2006 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00002007 CXXConstructExpr::CK_Complete,
2008 SourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00002009
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002010 if (FromResult.isInvalid())
2011 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002012
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002013 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00002014 return false;
2015 }
2016
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002017 // Resolve overloaded function references.
2018 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2019 DeclAccessPair Found;
2020 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2021 true, Found);
2022 if (!Fn)
2023 return true;
2024
2025 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
2026 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002027
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002028 From = FixOverloadedFunctionReference(From, Found, Fn);
2029 FromType = From->getType();
2030 }
2031
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002032 // Perform the first implicit conversion.
2033 switch (SCS.First) {
2034 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002035 // Nothing to do.
2036 break;
2037
John McCallf6a16482010-12-04 03:47:34 +00002038 case ICK_Lvalue_To_Rvalue:
2039 // Should this get its own ICK?
2040 if (From->getObjectKind() == OK_ObjCProperty) {
2041 ConvertPropertyForRValue(From);
John McCall241d5582010-12-07 22:54:16 +00002042 if (!From->isGLValue()) break;
John McCallf6a16482010-12-04 03:47:34 +00002043 }
2044
Chandler Carruth35001ca2011-02-17 21:10:52 +00002045 // Check for trivial buffer overflows.
2046 if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(From))
2047 CheckArrayAccess(AE);
2048
John McCallf6a16482010-12-04 03:47:34 +00002049 FromType = FromType.getUnqualifiedType();
2050 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2051 From, 0, VK_RValue);
2052 break;
2053
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002054 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002055 FromType = Context.getArrayDecayedType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00002056 ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002057 break;
2058
2059 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002060 FromType = Context.getPointerType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00002061 ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002062 break;
2063
2064 default:
2065 assert(false && "Improper first standard conversion");
2066 break;
2067 }
2068
2069 // Perform the second implicit conversion
2070 switch (SCS.Second) {
2071 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002072 // If both sides are functions (or pointers/references to them), there could
2073 // be incompatible exception declarations.
2074 if (CheckExceptionSpecCompatibility(From, ToType))
2075 return true;
2076 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002077 break;
2078
Douglas Gregor43c79c22009-12-09 00:47:37 +00002079 case ICK_NoReturn_Adjustment:
2080 // If both sides are functions (or pointers/references to them), there could
2081 // be incompatible exception declarations.
2082 if (CheckExceptionSpecCompatibility(From, ToType))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002083 return true;
2084
John McCalle6a365d2010-12-19 02:44:49 +00002085 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor43c79c22009-12-09 00:47:37 +00002086 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002087
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002088 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002089 case ICK_Integral_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002090 ImpCastExprToType(From, ToType, CK_IntegralCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002091 break;
2092
2093 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002094 case ICK_Floating_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002095 ImpCastExprToType(From, ToType, CK_FloatingCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002096 break;
2097
2098 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00002099 case ICK_Complex_Conversion: {
2100 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2101 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2102 CastKind CK;
2103 if (FromEl->isRealFloatingType()) {
2104 if (ToEl->isRealFloatingType())
2105 CK = CK_FloatingComplexCast;
2106 else
2107 CK = CK_FloatingComplexToIntegralComplex;
2108 } else if (ToEl->isRealFloatingType()) {
2109 CK = CK_IntegralComplexToFloatingComplex;
2110 } else {
2111 CK = CK_IntegralComplexCast;
2112 }
2113 ImpCastExprToType(From, ToType, CK);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002114 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00002115 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002116
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002117 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002118 if (ToType->isRealFloatingType())
John McCall2de56d12010-08-25 11:45:40 +00002119 ImpCastExprToType(From, ToType, CK_IntegralToFloating);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002120 else
John McCall2de56d12010-08-25 11:45:40 +00002121 ImpCastExprToType(From, ToType, CK_FloatingToIntegral);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002122 break;
2123
Douglas Gregorf9201e02009-02-11 23:02:49 +00002124 case ICK_Compatible_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002125 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002126 break;
2127
Anders Carlsson61faec12009-09-12 04:46:44 +00002128 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00002129 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002130 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00002131 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00002132 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00002133 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00002134 << From->getSourceRange();
2135 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002136
John McCalldaa8e4e2010-11-15 09:13:47 +00002137 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002138 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002139 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002140 return true;
John McCall5baba9d2010-08-25 10:28:54 +00002141 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002142 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00002143 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002144
Anders Carlsson61faec12009-09-12 04:46:44 +00002145 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002146 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002147 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002148 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
Anders Carlsson61faec12009-09-12 04:46:44 +00002149 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002150 if (CheckExceptionSpecCompatibility(From, ToType))
2151 return true;
John McCall5baba9d2010-08-25 10:28:54 +00002152 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Anders Carlsson61faec12009-09-12 04:46:44 +00002153 break;
2154 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002155 case ICK_Boolean_Conversion: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002156 CastKind Kind = CK_Invalid;
2157 switch (FromType->getScalarTypeKind()) {
2158 case Type::STK_Pointer: Kind = CK_PointerToBoolean; break;
2159 case Type::STK_MemberPointer: Kind = CK_MemberPointerToBoolean; break;
2160 case Type::STK_Bool: llvm_unreachable("bool -> bool conversion?");
2161 case Type::STK_Integral: Kind = CK_IntegralToBoolean; break;
2162 case Type::STK_Floating: Kind = CK_FloatingToBoolean; break;
2163 case Type::STK_IntegralComplex: Kind = CK_IntegralComplexToBoolean; break;
2164 case Type::STK_FloatingComplex: Kind = CK_FloatingComplexToBoolean; break;
2165 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002166
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002167 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002168 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002169 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002170
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002171 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002172 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002173 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002174 ToType.getNonReferenceType(),
2175 From->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002176 From->getSourceRange(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002177 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002178 CStyle))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002179 return true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002180
Sebastian Redl906082e2010-07-20 04:20:21 +00002181 ImpCastExprToType(From, ToType.getNonReferenceType(),
John McCall2de56d12010-08-25 11:45:40 +00002182 CK_DerivedToBase, CastCategory(From),
John McCallf871d0c2010-08-07 06:22:56 +00002183 &BasePath);
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002184 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002185 }
2186
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002187 case ICK_Vector_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002188 ImpCastExprToType(From, ToType, CK_BitCast);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002189 break;
2190
2191 case ICK_Vector_Splat:
John McCall2de56d12010-08-25 11:45:40 +00002192 ImpCastExprToType(From, ToType, CK_VectorSplat);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002193 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002194
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002195 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002196 // Case 1. x -> _Complex y
2197 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2198 QualType ElType = ToComplex->getElementType();
2199 bool isFloatingComplex = ElType->isRealFloatingType();
2200
2201 // x -> y
2202 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2203 // do nothing
2204 } else if (From->getType()->isRealFloatingType()) {
2205 ImpCastExprToType(From, ElType,
2206 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral);
2207 } else {
2208 assert(From->getType()->isIntegerType());
2209 ImpCastExprToType(From, ElType,
2210 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast);
2211 }
2212 // y -> _Complex y
2213 ImpCastExprToType(From, ToType,
2214 isFloatingComplex ? CK_FloatingRealToComplex
2215 : CK_IntegralRealToComplex);
2216
2217 // Case 2. _Complex x -> y
2218 } else {
2219 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2220 assert(FromComplex);
2221
2222 QualType ElType = FromComplex->getElementType();
2223 bool isFloatingComplex = ElType->isRealFloatingType();
2224
2225 // _Complex x -> x
2226 ImpCastExprToType(From, ElType,
2227 isFloatingComplex ? CK_FloatingComplexToReal
2228 : CK_IntegralComplexToReal);
2229
2230 // x -> y
2231 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2232 // do nothing
2233 } else if (ToType->isRealFloatingType()) {
2234 ImpCastExprToType(From, ToType,
2235 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating);
2236 } else {
2237 assert(ToType->isIntegerType());
2238 ImpCastExprToType(From, ToType,
2239 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast);
2240 }
2241 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002242 break;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002243
2244 case ICK_Block_Pointer_Conversion: {
2245 ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast, VK_RValue);
2246 break;
2247 }
2248
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002249 case ICK_Lvalue_To_Rvalue:
2250 case ICK_Array_To_Pointer:
2251 case ICK_Function_To_Pointer:
2252 case ICK_Qualification:
2253 case ICK_Num_Conversion_Kinds:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002254 assert(false && "Improper second standard conversion");
2255 break;
2256 }
2257
2258 switch (SCS.Third) {
2259 case ICK_Identity:
2260 // Nothing to do.
2261 break;
2262
Sebastian Redl906082e2010-07-20 04:20:21 +00002263 case ICK_Qualification: {
2264 // The qualification keeps the category of the inner expression, unless the
2265 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002266 ExprValueKind VK = ToType->isReferenceType() ?
2267 CastCategory(From) : VK_RValue;
Douglas Gregor63982352010-07-13 18:40:04 +00002268 ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
John McCall2de56d12010-08-25 11:45:40 +00002269 CK_NoOp, VK);
Douglas Gregora9bff302010-02-28 18:30:25 +00002270
2271 if (SCS.DeprecatedStringLiteralToCharPtr)
2272 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2273 << ToType.getNonReferenceType();
2274
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002275 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002276 }
2277
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002278 default:
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002279 assert(false && "Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002280 break;
2281 }
2282
2283 return false;
2284}
2285
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002286ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002287 SourceLocation KWLoc,
2288 ParsedType Ty,
2289 SourceLocation RParen) {
2290 TypeSourceInfo *TSInfo;
2291 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002292
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002293 if (!TSInfo)
2294 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002295 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002296}
2297
Sebastian Redlf8aca862010-09-14 23:40:14 +00002298static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT, QualType T,
2299 SourceLocation KeyLoc) {
Douglas Gregora0506182011-01-27 20:35:44 +00002300 // FIXME: For many of these traits, we need a complete type before we can
2301 // check these properties.
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002302 assert(!T->isDependentType() &&
2303 "Cannot evaluate traits for dependent types.");
2304 ASTContext &C = Self.Context;
2305 switch(UTT) {
2306 default: assert(false && "Unknown type trait or not implemented");
2307 case UTT_IsPOD: return T->isPODType();
2308 case UTT_IsLiteral: return T->isLiteralType();
2309 case UTT_IsClass: // Fallthrough
2310 case UTT_IsUnion:
2311 if (const RecordType *Record = T->getAs<RecordType>()) {
2312 bool Union = Record->getDecl()->isUnion();
2313 return UTT == UTT_IsUnion ? Union : !Union;
2314 }
2315 return false;
2316 case UTT_IsEnum: return T->isEnumeralType();
2317 case UTT_IsPolymorphic:
2318 if (const RecordType *Record = T->getAs<RecordType>()) {
2319 // Type traits are only parsed in C++, so we've got CXXRecords.
2320 return cast<CXXRecordDecl>(Record->getDecl())->isPolymorphic();
2321 }
2322 return false;
2323 case UTT_IsAbstract:
2324 if (const RecordType *RT = T->getAs<RecordType>())
2325 return cast<CXXRecordDecl>(RT->getDecl())->isAbstract();
2326 return false;
2327 case UTT_IsEmpty:
2328 if (const RecordType *Record = T->getAs<RecordType>()) {
2329 return !Record->getDecl()->isUnion()
2330 && cast<CXXRecordDecl>(Record->getDecl())->isEmpty();
2331 }
2332 return false;
2333 case UTT_HasTrivialConstructor:
2334 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2335 // If __is_pod (type) is true then the trait is true, else if type is
2336 // a cv class or union type (or array thereof) with a trivial default
2337 // constructor ([class.ctor]) then the trait is true, else it is false.
2338 if (T->isPODType())
2339 return true;
2340 if (const RecordType *RT =
2341 C.getBaseElementType(T)->getAs<RecordType>())
2342 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialConstructor();
2343 return false;
2344 case UTT_HasTrivialCopy:
2345 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2346 // If __is_pod (type) is true or type is a reference type then
2347 // the trait is true, else if type is a cv class or union type
2348 // with a trivial copy constructor ([class.copy]) then the trait
2349 // is true, else it is false.
2350 if (T->isPODType() || T->isReferenceType())
2351 return true;
2352 if (const RecordType *RT = T->getAs<RecordType>())
2353 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2354 return false;
2355 case UTT_HasTrivialAssign:
2356 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2357 // If type is const qualified or is a reference type then the
2358 // trait is false. Otherwise if __is_pod (type) is true then the
2359 // trait is true, else if type is a cv class or union type with
2360 // a trivial copy assignment ([class.copy]) then the trait is
2361 // true, else it is false.
2362 // Note: the const and reference restrictions are interesting,
2363 // given that const and reference members don't prevent a class
2364 // from having a trivial copy assignment operator (but do cause
2365 // errors if the copy assignment operator is actually used, q.v.
2366 // [class.copy]p12).
2367
2368 if (C.getBaseElementType(T).isConstQualified())
2369 return false;
2370 if (T->isPODType())
2371 return true;
2372 if (const RecordType *RT = T->getAs<RecordType>())
2373 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2374 return false;
2375 case UTT_HasTrivialDestructor:
2376 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2377 // If __is_pod (type) is true or type is a reference type
2378 // then the trait is true, else if type is a cv class or union
2379 // type (or array thereof) with a trivial destructor
2380 // ([class.dtor]) then the trait is true, else it is
2381 // false.
2382 if (T->isPODType() || T->isReferenceType())
2383 return true;
2384 if (const RecordType *RT =
2385 C.getBaseElementType(T)->getAs<RecordType>())
2386 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2387 return false;
2388 // TODO: Propagate nothrowness for implicitly declared special members.
2389 case UTT_HasNothrowAssign:
2390 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2391 // If type is const qualified or is a reference type then the
2392 // trait is false. Otherwise if __has_trivial_assign (type)
2393 // is true then the trait is true, else if type is a cv class
2394 // or union type with copy assignment operators that are known
2395 // not to throw an exception then the trait is true, else it is
2396 // false.
2397 if (C.getBaseElementType(T).isConstQualified())
2398 return false;
2399 if (T->isReferenceType())
2400 return false;
2401 if (T->isPODType())
2402 return true;
2403 if (const RecordType *RT = T->getAs<RecordType>()) {
2404 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2405 if (RD->hasTrivialCopyAssignment())
2406 return true;
2407
2408 bool FoundAssign = false;
2409 bool AllNoThrow = true;
2410 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00002411 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2412 Sema::LookupOrdinaryName);
2413 if (Self.LookupQualifiedName(Res, RD)) {
2414 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2415 Op != OpEnd; ++Op) {
2416 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2417 if (Operator->isCopyAssignmentOperator()) {
2418 FoundAssign = true;
2419 const FunctionProtoType *CPT
2420 = Operator->getType()->getAs<FunctionProtoType>();
2421 if (!CPT->hasEmptyExceptionSpec()) {
2422 AllNoThrow = false;
2423 break;
2424 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002425 }
2426 }
2427 }
2428
2429 return FoundAssign && AllNoThrow;
2430 }
2431 return false;
2432 case UTT_HasNothrowCopy:
2433 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2434 // If __has_trivial_copy (type) is true then the trait is true, else
2435 // if type is a cv class or union type with copy constructors that are
2436 // known not to throw an exception then the trait is true, else it is
2437 // false.
2438 if (T->isPODType() || T->isReferenceType())
2439 return true;
2440 if (const RecordType *RT = T->getAs<RecordType>()) {
2441 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2442 if (RD->hasTrivialCopyConstructor())
2443 return true;
2444
2445 bool FoundConstructor = false;
2446 bool AllNoThrow = true;
2447 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002448 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00002449 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002450 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002451 // A template constructor is never a copy constructor.
2452 // FIXME: However, it may actually be selected at the actual overload
2453 // resolution point.
2454 if (isa<FunctionTemplateDecl>(*Con))
2455 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002456 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2457 if (Constructor->isCopyConstructor(FoundTQs)) {
2458 FoundConstructor = true;
2459 const FunctionProtoType *CPT
2460 = Constructor->getType()->getAs<FunctionProtoType>();
Sebastian Redl751025d2010-09-13 22:02:47 +00002461 // TODO: check whether evaluating default arguments can throw.
2462 // For now, we'll be conservative and assume that they can throw.
2463 if (!CPT->hasEmptyExceptionSpec() || CPT->getNumArgs() > 1) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002464 AllNoThrow = false;
2465 break;
2466 }
2467 }
2468 }
2469
2470 return FoundConstructor && AllNoThrow;
2471 }
2472 return false;
2473 case UTT_HasNothrowConstructor:
2474 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2475 // If __has_trivial_constructor (type) is true then the trait is
2476 // true, else if type is a cv class or union type (or array
2477 // thereof) with a default constructor that is known not to
2478 // throw an exception then the trait is true, else it is false.
2479 if (T->isPODType())
2480 return true;
2481 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2482 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2483 if (RD->hasTrivialConstructor())
2484 return true;
2485
Sebastian Redl751025d2010-09-13 22:02:47 +00002486 DeclContext::lookup_const_iterator Con, ConEnd;
2487 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2488 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002489 // FIXME: In C++0x, a constructor template can be a default constructor.
2490 if (isa<FunctionTemplateDecl>(*Con))
2491 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00002492 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2493 if (Constructor->isDefaultConstructor()) {
2494 const FunctionProtoType *CPT
2495 = Constructor->getType()->getAs<FunctionProtoType>();
2496 // TODO: check whether evaluating default arguments can throw.
2497 // For now, we'll be conservative and assume that they can throw.
2498 return CPT->hasEmptyExceptionSpec() && CPT->getNumArgs() == 0;
2499 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002500 }
2501 }
2502 return false;
2503 case UTT_HasVirtualDestructor:
2504 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2505 // If type is a class type with a virtual destructor ([class.dtor])
2506 // then the trait is true, else it is false.
2507 if (const RecordType *Record = T->getAs<RecordType>()) {
2508 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00002509 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002510 return Destructor->isVirtual();
2511 }
2512 return false;
2513 }
2514}
2515
2516ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002517 SourceLocation KWLoc,
2518 TypeSourceInfo *TSInfo,
2519 SourceLocation RParen) {
2520 QualType T = TSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002521
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002522 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
2523 // all traits except __is_class, __is_enum and __is_union require a the type
Sebastian Redl607a1782010-09-08 00:48:43 +00002524 // to be complete, an array of unknown bound, or void.
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002525 if (UTT != UTT_IsClass && UTT != UTT_IsEnum && UTT != UTT_IsUnion) {
Sebastian Redl607a1782010-09-08 00:48:43 +00002526 QualType E = T;
2527 if (T->isIncompleteArrayType())
2528 E = Context.getAsArrayType(T)->getElementType();
2529 if (!T->isVoidType() &&
2530 RequireCompleteType(KWLoc, E,
Anders Carlssond497ba72009-08-26 22:59:12 +00002531 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002532 return ExprError();
2533 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002534
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002535 bool Value = false;
2536 if (!T->isDependentType())
Sebastian Redlf8aca862010-09-14 23:40:14 +00002537 Value = EvaluateUnaryTypeTrait(*this, UTT, T, KWLoc);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002538
2539 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002540 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00002541}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002542
Francois Pichet6ad6f282010-12-07 00:08:36 +00002543ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
2544 SourceLocation KWLoc,
2545 ParsedType LhsTy,
2546 ParsedType RhsTy,
2547 SourceLocation RParen) {
2548 TypeSourceInfo *LhsTSInfo;
2549 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
2550 if (!LhsTSInfo)
2551 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
2552
2553 TypeSourceInfo *RhsTSInfo;
2554 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
2555 if (!RhsTSInfo)
2556 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
2557
2558 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
2559}
2560
2561static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
2562 QualType LhsT, QualType RhsT,
2563 SourceLocation KeyLoc) {
2564 assert((!LhsT->isDependentType() || RhsT->isDependentType()) &&
2565 "Cannot evaluate traits for dependent types.");
2566
2567 switch(BTT) {
John McCalld89d30f2011-01-28 22:02:36 +00002568 case BTT_IsBaseOf: {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002569 // C++0x [meta.rel]p2
John McCalld89d30f2011-01-28 22:02:36 +00002570 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet6ad6f282010-12-07 00:08:36 +00002571 // Base and Derived are not unions and name the same class type without
2572 // regard to cv-qualifiers.
Francois Pichet6ad6f282010-12-07 00:08:36 +00002573
John McCalld89d30f2011-01-28 22:02:36 +00002574 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
2575 if (!lhsRecord) return false;
2576
2577 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
2578 if (!rhsRecord) return false;
2579
2580 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
2581 == (lhsRecord == rhsRecord));
2582
2583 if (lhsRecord == rhsRecord)
2584 return !lhsRecord->getDecl()->isUnion();
2585
2586 // C++0x [meta.rel]p2:
2587 // If Base and Derived are class types and are different types
2588 // (ignoring possible cv-qualifiers) then Derived shall be a
2589 // complete type.
2590 if (Self.RequireCompleteType(KeyLoc, RhsT,
2591 diag::err_incomplete_type_used_in_type_trait_expr))
2592 return false;
2593
2594 return cast<CXXRecordDecl>(rhsRecord->getDecl())
2595 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
2596 }
2597
Francois Pichetf1872372010-12-08 22:35:30 +00002598 case BTT_TypeCompatible:
2599 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
2600 RhsT.getUnqualifiedType());
Douglas Gregor9f361132011-01-27 20:28:01 +00002601
2602 case BTT_IsConvertibleTo: {
2603 // C++0x [meta.rel]p4:
2604 // Given the following function prototype:
2605 //
2606 // template <class T>
2607 // typename add_rvalue_reference<T>::type create();
2608 //
2609 // the predicate condition for a template specialization
2610 // is_convertible<From, To> shall be satisfied if and only if
2611 // the return expression in the following code would be
2612 // well-formed, including any implicit conversions to the return
2613 // type of the function:
2614 //
2615 // To test() {
2616 // return create<From>();
2617 // }
2618 //
2619 // Access checking is performed as if in a context unrelated to To and
2620 // From. Only the validity of the immediate context of the expression
2621 // of the return-statement (including conversions to the return type)
2622 // is considered.
2623 //
2624 // We model the initialization as a copy-initialization of a temporary
2625 // of the appropriate type, which for this expression is identical to the
2626 // return statement (since NRVO doesn't apply).
2627 if (LhsT->isObjectType() || LhsT->isFunctionType())
2628 LhsT = Self.Context.getRValueReferenceType(LhsT);
2629
2630 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorb608b982011-01-28 02:26:04 +00002631 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor9f361132011-01-27 20:28:01 +00002632 Expr::getValueKindForType(LhsT));
2633 Expr *FromPtr = &From;
2634 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
2635 SourceLocation()));
2636
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00002637 // Perform the initialization within a SFINAE trap at translation unit
2638 // scope.
2639 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
2640 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor9f361132011-01-27 20:28:01 +00002641 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
2642 if (Init.getKind() == InitializationSequence::FailedSequence)
2643 return false;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00002644
Douglas Gregor9f361132011-01-27 20:28:01 +00002645 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
2646 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
2647 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00002648 }
2649 llvm_unreachable("Unknown type trait or not implemented");
2650}
2651
2652ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
2653 SourceLocation KWLoc,
2654 TypeSourceInfo *LhsTSInfo,
2655 TypeSourceInfo *RhsTSInfo,
2656 SourceLocation RParen) {
2657 QualType LhsT = LhsTSInfo->getType();
2658 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002659
John McCalld89d30f2011-01-28 22:02:36 +00002660 if (BTT == BTT_TypeCompatible) {
Francois Pichetf1872372010-12-08 22:35:30 +00002661 if (getLangOptions().CPlusPlus) {
2662 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
2663 << SourceRange(KWLoc, RParen);
2664 return ExprError();
2665 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00002666 }
2667
2668 bool Value = false;
2669 if (!LhsT->isDependentType() && !RhsT->isDependentType())
2670 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
2671
Francois Pichetf1872372010-12-08 22:35:30 +00002672 // Select trait result type.
2673 QualType ResultType;
2674 switch (BTT) {
Francois Pichetf1872372010-12-08 22:35:30 +00002675 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
2676 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor9f361132011-01-27 20:28:01 +00002677 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00002678 }
2679
Francois Pichet6ad6f282010-12-07 00:08:36 +00002680 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
2681 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00002682 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00002683}
2684
John McCallf89e55a2010-11-18 06:31:45 +00002685QualType Sema::CheckPointerToMemberOperands(Expr *&lex, Expr *&rex,
2686 ExprValueKind &VK,
2687 SourceLocation Loc,
2688 bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002689 const char *OpSpelling = isIndirect ? "->*" : ".*";
2690 // C++ 5.5p2
2691 // The binary operator .* [p3: ->*] binds its second operand, which shall
2692 // be of type "pointer to member of T" (where T is a completely-defined
2693 // class type) [...]
2694 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002695 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00002696 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002697 Diag(Loc, diag::err_bad_memptr_rhs)
2698 << OpSpelling << RType << rex->getSourceRange();
2699 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00002700 }
Douglas Gregore7450f52009-03-24 19:52:54 +00002701
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002702 QualType Class(MemPtr->getClass(), 0);
2703
Douglas Gregor7d520ba2010-10-13 20:41:14 +00002704 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
2705 // member pointer points must be completely-defined. However, there is no
2706 // reason for this semantic distinction, and the rule is not enforced by
2707 // other compilers. Therefore, we do not check this property, as it is
2708 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00002709
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002710 // C++ 5.5p2
2711 // [...] to its first operand, which shall be of class T or of a class of
2712 // which T is an unambiguous and accessible base class. [p3: a pointer to
2713 // such a class]
2714 QualType LType = lex->getType();
2715 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002716 if (const PointerType *Ptr = LType->getAs<PointerType>())
John McCallf89e55a2010-11-18 06:31:45 +00002717 LType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002718 else {
2719 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00002720 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00002721 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002722 return QualType();
2723 }
2724 }
2725
Douglas Gregora4923eb2009-11-16 21:35:15 +00002726 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00002727 // If we want to check the hierarchy, we need a complete type.
2728 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
2729 << OpSpelling << (int)isIndirect)) {
2730 return QualType();
2731 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002732 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002733 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00002734 // FIXME: Would it be useful to print full ambiguity paths, or is that
2735 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002736 if (!IsDerivedFrom(LType, Class, Paths) ||
2737 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
2738 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00002739 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002740 return QualType();
2741 }
Eli Friedman3005efe2010-01-16 00:00:48 +00002742 // Cast LHS to type of use.
2743 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
John McCall5baba9d2010-08-25 10:28:54 +00002744 ExprValueKind VK =
2745 isIndirect ? VK_RValue : CastCategory(lex);
Sebastian Redl906082e2010-07-20 04:20:21 +00002746
John McCallf871d0c2010-08-07 06:22:56 +00002747 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002748 BuildBasePathArray(Paths, BasePath);
John McCall5baba9d2010-08-25 10:28:54 +00002749 ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002750 }
2751
Douglas Gregored8abf12010-07-08 06:14:04 +00002752 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00002753 // Diagnose use of pointer-to-member type which when used as
2754 // the functional cast in a pointer-to-member expression.
2755 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2756 return QualType();
2757 }
John McCallf89e55a2010-11-18 06:31:45 +00002758
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002759 // C++ 5.5p2
2760 // The result is an object or a function of the type specified by the
2761 // second operand.
2762 // The cv qualifiers are the union of those in the pointer and the left side,
2763 // in accordance with 5.5p5 and 5.2.5.
2764 // FIXME: This returns a dereferenced member function pointer as a normal
2765 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00002766 // calling them. There's also a GCC extension to get a function pointer to the
2767 // thing, which is another complication, because this type - unlike the type
2768 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002769 // argument.
2770 // We probably need a "MemberFunctionClosureType" or something like that.
2771 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00002772 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00002773
Douglas Gregor6b4df912011-01-26 16:40:18 +00002774 // C++0x [expr.mptr.oper]p6:
2775 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002776 // ill-formed if the second operand is a pointer to member function with
2777 // ref-qualifier &. In a ->* expression or in a .* expression whose object
2778 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor6b4df912011-01-26 16:40:18 +00002779 // is a pointer to member function with ref-qualifier &&.
2780 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
2781 switch (Proto->getRefQualifier()) {
2782 case RQ_None:
2783 // Do nothing
2784 break;
2785
2786 case RQ_LValue:
2787 if (!isIndirect && !lex->Classify(Context).isLValue())
2788 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2789 << RType << 1 << lex->getSourceRange();
2790 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002791
Douglas Gregor6b4df912011-01-26 16:40:18 +00002792 case RQ_RValue:
2793 if (isIndirect || !lex->Classify(Context).isRValue())
2794 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2795 << RType << 0 << lex->getSourceRange();
2796 break;
2797 }
2798 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002799
John McCallf89e55a2010-11-18 06:31:45 +00002800 // C++ [expr.mptr.oper]p6:
2801 // The result of a .* expression whose second operand is a pointer
2802 // to a data member is of the same value category as its
2803 // first operand. The result of a .* expression whose second
2804 // operand is a pointer to a member function is a prvalue. The
2805 // result of an ->* expression is an lvalue if its second operand
2806 // is a pointer to data member and a prvalue otherwise.
2807 if (Result->isFunctionType())
2808 VK = VK_RValue;
2809 else if (isIndirect)
2810 VK = VK_LValue;
2811 else
2812 VK = lex->getValueKind();
2813
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002814 return Result;
2815}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002816
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002817/// \brief Try to convert a type to another according to C++0x 5.16p3.
2818///
2819/// This is part of the parameter validation for the ? operator. If either
2820/// value operand is a class type, the two operands are attempted to be
2821/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002822/// It returns true if the program is ill-formed and has already been diagnosed
2823/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002824static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2825 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00002826 bool &HaveConversion,
2827 QualType &ToType) {
2828 HaveConversion = false;
2829 ToType = To->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002830
2831 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00002832 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002833 // C++0x 5.16p3
2834 // The process for determining whether an operand expression E1 of type T1
2835 // can be converted to match an operand expression E2 of type T2 is defined
2836 // as follows:
2837 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00002838 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002839 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002840 // E1 can be converted to match E2 if E1 can be implicitly converted to
2841 // type "lvalue reference to T2", subject to the constraint that in the
2842 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002843 QualType T = Self.Context.getLValueReferenceType(ToType);
2844 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002845
Douglas Gregorb70cf442010-03-26 20:14:36 +00002846 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2847 if (InitSeq.isDirectReferenceBinding()) {
2848 ToType = T;
2849 HaveConversion = true;
2850 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002851 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002852
Douglas Gregorb70cf442010-03-26 20:14:36 +00002853 if (InitSeq.isAmbiguous())
2854 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002855 }
John McCallb1bdc622010-02-25 01:37:24 +00002856
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002857 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2858 // -- if E1 and E2 have class type, and the underlying class types are
2859 // the same or one is a base class of the other:
2860 QualType FTy = From->getType();
2861 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002862 const RecordType *FRec = FTy->getAs<RecordType>();
2863 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002864 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00002865 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002866 if (FRec && TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00002867 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002868 // E1 can be converted to match E2 if the class of T2 is the
2869 // same type as, or a base class of, the class of T1, and
2870 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00002871 if (FRec == TRec || FDerivedFromT) {
2872 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002873 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2874 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2875 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2876 HaveConversion = true;
2877 return false;
2878 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002879
Douglas Gregorb70cf442010-03-26 20:14:36 +00002880 if (InitSeq.isAmbiguous())
2881 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002882 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002883 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002884
Douglas Gregorb70cf442010-03-26 20:14:36 +00002885 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002886 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002887
Douglas Gregorb70cf442010-03-26 20:14:36 +00002888 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2889 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002890 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002891 // an rvalue).
2892 //
2893 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2894 // to the array-to-pointer or function-to-pointer conversions.
2895 if (!TTy->getAs<TagType>())
2896 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002897
Douglas Gregorb70cf442010-03-26 20:14:36 +00002898 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2899 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002900 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002901 ToType = TTy;
2902 if (InitSeq.isAmbiguous())
2903 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2904
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002905 return false;
2906}
2907
2908/// \brief Try to find a common type for two according to C++0x 5.16p5.
2909///
2910/// This is part of the parameter validation for the ? operator. If either
2911/// value operand is a class type, overload resolution is used to find a
2912/// conversion to a common type.
2913static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
Chandler Carruth82214a82011-02-18 23:54:50 +00002914 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002915 Expr *Args[2] = { LHS, RHS };
Chandler Carruth82214a82011-02-18 23:54:50 +00002916 OverloadCandidateSet CandidateSet(QuestionLoc);
2917 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
2918 CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002919
2920 OverloadCandidateSet::iterator Best;
Chandler Carruth82214a82011-02-18 23:54:50 +00002921 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002922 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002923 // We found a match. Perform the conversions on the arguments and move on.
2924 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002925 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002926 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002927 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002928 break;
Chandler Carruth25ca4212011-02-25 19:41:05 +00002929 if (Best->Function)
2930 Self.MarkDeclarationReferenced(QuestionLoc, Best->Function);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002931 return false;
2932
Douglas Gregor20093b42009-12-09 23:02:17 +00002933 case OR_No_Viable_Function:
Chandler Carruth82214a82011-02-18 23:54:50 +00002934
2935 // Emit a better diagnostic if one of the expressions is a null pointer
2936 // constant and the other is a pointer type. In this case, the user most
2937 // likely forgot to take the address of the other expression.
2938 if (Self.DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
2939 return true;
2940
2941 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002942 << LHS->getType() << RHS->getType()
2943 << LHS->getSourceRange() << RHS->getSourceRange();
2944 return true;
2945
Douglas Gregor20093b42009-12-09 23:02:17 +00002946 case OR_Ambiguous:
Chandler Carruth82214a82011-02-18 23:54:50 +00002947 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002948 << LHS->getType() << RHS->getType()
2949 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002950 // FIXME: Print the possible common types by printing the return types of
2951 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002952 break;
2953
Douglas Gregor20093b42009-12-09 23:02:17 +00002954 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002955 assert(false && "Conditional operator has only built-in overloads");
2956 break;
2957 }
2958 return true;
2959}
2960
Sebastian Redl76458502009-04-17 16:30:52 +00002961/// \brief Perform an "extended" implicit conversion as returned by
2962/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002963static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2964 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2965 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2966 SourceLocation());
2967 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
John McCallf312b1e2010-08-26 23:41:50 +00002968 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00002969 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002970 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002971
Douglas Gregorb70cf442010-03-26 20:14:36 +00002972 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002973 return false;
2974}
2975
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002976/// \brief Check the operands of ?: under C++ semantics.
2977///
2978/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2979/// extension. In this case, LHS == Cond. (But they're not aliases.)
2980QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCall56ca35d2011-02-17 10:25:35 +00002981 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002982 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002983 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2984 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002985
2986 // C++0x 5.16p1
2987 // The first expression is contextually converted to bool.
2988 if (!Cond->isTypeDependent()) {
2989 if (CheckCXXBooleanCondition(Cond))
2990 return QualType();
2991 }
2992
John McCallf89e55a2010-11-18 06:31:45 +00002993 // Assume r-value.
2994 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00002995 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00002996
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002997 // Either of the arguments dependent?
2998 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2999 return Context.DependentTy;
3000
3001 // C++0x 5.16p2
3002 // If either the second or the third operand has type (cv) void, ...
3003 QualType LTy = LHS->getType();
3004 QualType RTy = RHS->getType();
3005 bool LVoid = LTy->isVoidType();
3006 bool RVoid = RTy->isVoidType();
3007 if (LVoid || RVoid) {
3008 // ... then the [l2r] conversions are performed on the second and third
3009 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00003010 DefaultFunctionArrayLvalueConversion(LHS);
3011 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003012 LTy = LHS->getType();
3013 RTy = RHS->getType();
3014
3015 // ... and one of the following shall hold:
3016 // -- The second or the third operand (but not both) is a throw-
3017 // expression; the result is of the type of the other and is an rvalue.
3018 bool LThrow = isa<CXXThrowExpr>(LHS);
3019 bool RThrow = isa<CXXThrowExpr>(RHS);
3020 if (LThrow && !RThrow)
3021 return RTy;
3022 if (RThrow && !LThrow)
3023 return LTy;
3024
3025 // -- Both the second and third operands have type void; the result is of
3026 // type void and is an rvalue.
3027 if (LVoid && RVoid)
3028 return Context.VoidTy;
3029
3030 // Neither holds, error.
3031 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3032 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
3033 << LHS->getSourceRange() << RHS->getSourceRange();
3034 return QualType();
3035 }
3036
3037 // Neither is void.
3038
3039 // C++0x 5.16p3
3040 // Otherwise, if the second and third operand have different types, and
3041 // either has (cv) class type, and attempt is made to convert each of those
3042 // operands to the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003043 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003044 (LTy->isRecordType() || RTy->isRecordType())) {
3045 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3046 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003047 QualType L2RType, R2LType;
3048 bool HaveL2R, HaveR2L;
3049 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003050 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00003051 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003052 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003053
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003054 // If both can be converted, [...] the program is ill-formed.
3055 if (HaveL2R && HaveR2L) {
3056 Diag(QuestionLoc, diag::err_conditional_ambiguous)
3057 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
3058 return QualType();
3059 }
3060
3061 // If exactly one conversion is possible, that conversion is applied to
3062 // the chosen operand and the converted operands are used in place of the
3063 // original operands for the remainder of this section.
3064 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003065 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003066 return QualType();
3067 LTy = LHS->getType();
3068 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003069 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003070 return QualType();
3071 RTy = RHS->getType();
3072 }
3073 }
3074
3075 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00003076 // If the second and third operands are glvalues of the same value
3077 // category and have the same type, the result is of that type and
3078 // value category and it is a bit-field if the second or the third
3079 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00003080 // We only extend this to bitfields, not to the crazy other kinds of
3081 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003082 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00003083 if (Same &&
John McCall56ca35d2011-02-17 10:25:35 +00003084 LHS->isGLValue() &&
John McCallf89e55a2010-11-18 06:31:45 +00003085 LHS->getValueKind() == RHS->getValueKind() &&
John McCall56ca35d2011-02-17 10:25:35 +00003086 LHS->isOrdinaryOrBitFieldObject() &&
3087 RHS->isOrdinaryOrBitFieldObject()) {
John McCallf89e55a2010-11-18 06:31:45 +00003088 VK = LHS->getValueKind();
John McCall09431682010-11-18 19:01:18 +00003089 if (LHS->getObjectKind() == OK_BitField ||
3090 RHS->getObjectKind() == OK_BitField)
3091 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00003092 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00003093 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003094
3095 // C++0x 5.16p5
3096 // Otherwise, the result is an rvalue. If the second and third operands
3097 // do not have the same type, and either has (cv) class type, ...
3098 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3099 // ... overload resolution is used to determine the conversions (if any)
3100 // to be applied to the operands. If the overload resolution fails, the
3101 // program is ill-formed.
3102 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3103 return QualType();
3104 }
3105
3106 // C++0x 5.16p6
3107 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3108 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00003109 DefaultFunctionArrayLvalueConversion(LHS);
3110 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003111 LTy = LHS->getType();
3112 RTy = RHS->getType();
3113
3114 // After those conversions, one of the following shall hold:
3115 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00003116 // is of that type. If the operands have class type, the result
3117 // is a prvalue temporary of the result type, which is
3118 // copy-initialized from either the second operand or the third
3119 // operand depending on the value of the first operand.
3120 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3121 if (LTy->isRecordType()) {
3122 // The operands have class type. Make a temporary copy.
3123 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003124 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3125 SourceLocation(),
John McCallf6a16482010-12-04 03:47:34 +00003126 Owned(LHS));
Douglas Gregorb65a4582010-05-19 23:40:50 +00003127 if (LHSCopy.isInvalid())
3128 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003129
3130 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3131 SourceLocation(),
John McCallf6a16482010-12-04 03:47:34 +00003132 Owned(RHS));
Douglas Gregorb65a4582010-05-19 23:40:50 +00003133 if (RHSCopy.isInvalid())
3134 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003135
Douglas Gregorb65a4582010-05-19 23:40:50 +00003136 LHS = LHSCopy.takeAs<Expr>();
3137 RHS = RHSCopy.takeAs<Expr>();
3138 }
3139
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003140 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003141 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003142
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003143 // Extension: conditional operator involving vector types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003144 if (LTy->isVectorType() || RTy->isVectorType())
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003145 return CheckVectorOperands(QuestionLoc, LHS, RHS);
3146
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003147 // -- The second and third operands have arithmetic or enumeration type;
3148 // the usual arithmetic conversions are performed to bring them to a
3149 // common type, and the result is of that type.
3150 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3151 UsualArithmeticConversions(LHS, RHS);
3152 return LHS->getType();
3153 }
3154
3155 // -- The second and third operands have pointer type, or one has pointer
3156 // type and the other is a null pointer constant; pointer conversions
3157 // and qualification conversions are performed to bring them to their
3158 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00003159 // -- The second and third operands have pointer to member type, or one has
3160 // pointer to member type and the other is a null pointer constant;
3161 // pointer to member conversions and qualification conversions are
3162 // performed to bring them to a common type, whose cv-qualification
3163 // shall match the cv-qualification of either the second or the third
3164 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003165 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003166 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003167 isSFINAEContext()? 0 : &NonStandardCompositeType);
3168 if (!Composite.isNull()) {
3169 if (NonStandardCompositeType)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003170 Diag(QuestionLoc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003171 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3172 << LTy << RTy << Composite
3173 << LHS->getSourceRange() << RHS->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003174
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003175 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003176 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003177
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003178 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00003179 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3180 if (!Composite.isNull())
3181 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003182
Chandler Carruth7ef93242011-02-19 00:13:59 +00003183 // Check if we are using a null with a non-pointer type.
3184 if (DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
3185 return QualType();
3186
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003187 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3188 << LHS->getType() << RHS->getType()
3189 << LHS->getSourceRange() << RHS->getSourceRange();
3190 return QualType();
3191}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003192
3193/// \brief Find a merged pointer type and convert the two expressions to it.
3194///
Douglas Gregor20b3e992009-08-24 17:42:35 +00003195/// This finds the composite pointer type (or member pointer type) for @p E1
3196/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3197/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003198/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003199///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003200/// \param Loc The location of the operator requiring these two expressions to
3201/// be converted to the composite pointer type.
3202///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003203/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3204/// a non-standard (but still sane) composite type to which both expressions
3205/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3206/// will be set true.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003207QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003208 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003209 bool *NonStandardCompositeType) {
3210 if (NonStandardCompositeType)
3211 *NonStandardCompositeType = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003212
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003213 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3214 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003215
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00003216 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3217 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00003218 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003219
3220 // C++0x 5.9p2
3221 // Pointer conversions and qualification conversions are performed on
3222 // pointer operands to bring them to their composite pointer type. If
3223 // one operand is a null pointer constant, the composite pointer type is
3224 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00003225 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003226 if (T2->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00003227 ImpCastExprToType(E1, T2, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003228 else
John McCall404cd162010-11-13 01:35:44 +00003229 ImpCastExprToType(E1, T2, CK_NullToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003230 return T2;
3231 }
Douglas Gregorce940492009-09-25 04:25:58 +00003232 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003233 if (T1->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00003234 ImpCastExprToType(E2, T1, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003235 else
John McCall404cd162010-11-13 01:35:44 +00003236 ImpCastExprToType(E2, T1, CK_NullToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003237 return T1;
3238 }
Mike Stump1eb44332009-09-09 15:08:12 +00003239
Douglas Gregor20b3e992009-08-24 17:42:35 +00003240 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003241 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3242 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003243 return QualType();
3244
3245 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3246 // the other has type "pointer to cv2 T" and the composite pointer type is
3247 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3248 // Otherwise, the composite pointer type is a pointer type similar to the
3249 // type of one of the operands, with a cv-qualification signature that is
3250 // the union of the cv-qualification signatures of the operand types.
3251 // In practice, the first part here is redundant; it's subsumed by the second.
3252 // What we do here is, we build the two possible composite types, and try the
3253 // conversions in both directions. If only one works, or if the two composite
3254 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00003255 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00003256 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
3257 QualifierVector QualifierUnion;
3258 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
3259 ContainingClassVector;
3260 ContainingClassVector MemberOfClass;
3261 QualType Composite1 = Context.getCanonicalType(T1),
3262 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003263 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00003264 do {
3265 const PointerType *Ptr1, *Ptr2;
3266 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3267 (Ptr2 = Composite2->getAs<PointerType>())) {
3268 Composite1 = Ptr1->getPointeeType();
3269 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003270
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003271 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003272 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003273 if (NonStandardCompositeType &&
3274 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3275 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003276
Douglas Gregor20b3e992009-08-24 17:42:35 +00003277 QualifierUnion.push_back(
3278 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3279 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3280 continue;
3281 }
Mike Stump1eb44332009-09-09 15:08:12 +00003282
Douglas Gregor20b3e992009-08-24 17:42:35 +00003283 const MemberPointerType *MemPtr1, *MemPtr2;
3284 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3285 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3286 Composite1 = MemPtr1->getPointeeType();
3287 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003288
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003289 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003290 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003291 if (NonStandardCompositeType &&
3292 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3293 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003294
Douglas Gregor20b3e992009-08-24 17:42:35 +00003295 QualifierUnion.push_back(
3296 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3297 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3298 MemPtr2->getClass()));
3299 continue;
3300 }
Mike Stump1eb44332009-09-09 15:08:12 +00003301
Douglas Gregor20b3e992009-08-24 17:42:35 +00003302 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00003303
Douglas Gregor20b3e992009-08-24 17:42:35 +00003304 // Cannot unwrap any more types.
3305 break;
3306 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00003307
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003308 if (NeedConstBefore && NonStandardCompositeType) {
3309 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003310 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003311 // requirements of C++ [conv.qual]p4 bullet 3.
3312 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3313 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3314 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3315 *NonStandardCompositeType = true;
3316 }
3317 }
3318 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003319
Douglas Gregor20b3e992009-08-24 17:42:35 +00003320 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003321 ContainingClassVector::reverse_iterator MOC
3322 = MemberOfClass.rbegin();
3323 for (QualifierVector::reverse_iterator
3324 I = QualifierUnion.rbegin(),
3325 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00003326 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00003327 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003328 if (MOC->first && MOC->second) {
3329 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00003330 Composite1 = Context.getMemberPointerType(
3331 Context.getQualifiedType(Composite1, Quals),
3332 MOC->first);
3333 Composite2 = Context.getMemberPointerType(
3334 Context.getQualifiedType(Composite2, Quals),
3335 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003336 } else {
3337 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00003338 Composite1
3339 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3340 Composite2
3341 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00003342 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003343 }
3344
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003345 // Try to convert to the first composite pointer type.
3346 InitializedEntity Entity1
3347 = InitializedEntity::InitializeTemporary(Composite1);
3348 InitializationKind Kind
3349 = InitializationKind::CreateCopy(Loc, SourceLocation());
3350 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3351 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00003352
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003353 if (E1ToC1 && E2ToC1) {
3354 // Conversion to Composite1 is viable.
3355 if (!Context.hasSameType(Composite1, Composite2)) {
3356 // Composite2 is a different type from Composite1. Check whether
3357 // Composite2 is also viable.
3358 InitializedEntity Entity2
3359 = InitializedEntity::InitializeTemporary(Composite2);
3360 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3361 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3362 if (E1ToC2 && E2ToC2) {
3363 // Both Composite1 and Composite2 are viable and are different;
3364 // this is an ambiguity.
3365 return QualType();
3366 }
3367 }
3368
3369 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003370 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00003371 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003372 if (E1Result.isInvalid())
3373 return QualType();
3374 E1 = E1Result.takeAs<Expr>();
3375
3376 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003377 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00003378 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003379 if (E2Result.isInvalid())
3380 return QualType();
3381 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003382
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003383 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003384 }
3385
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003386 // Check whether Composite2 is viable.
3387 InitializedEntity Entity2
3388 = InitializedEntity::InitializeTemporary(Composite2);
3389 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3390 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3391 if (!E1ToC2 || !E2ToC2)
3392 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003393
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003394 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00003395 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00003396 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003397 if (E1Result.isInvalid())
3398 return QualType();
3399 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003400
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003401 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00003402 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00003403 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003404 if (E2Result.isInvalid())
3405 return QualType();
3406 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003407
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003408 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003409}
Anders Carlsson165a0a02009-05-17 18:41:29 +00003410
John McCall60d7b3a2010-08-24 06:29:42 +00003411ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00003412 if (!E)
3413 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003414
Anders Carlsson089c2602009-08-15 23:41:35 +00003415 if (!Context.getLangOptions().CPlusPlus)
3416 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003417
Douglas Gregor51326552009-12-24 18:51:59 +00003418 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
3419
Ted Kremenek6217b802009-07-29 21:53:49 +00003420 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00003421 if (!RT)
3422 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003423
Douglas Gregor5e6fcd42011-02-08 02:14:35 +00003424 // If the result is a glvalue, we shouldn't bind it.
3425 if (E->Classify(Context).isGLValue())
3426 return Owned(E);
John McCall86ff3082010-02-04 22:26:26 +00003427
3428 // That should be enough to guarantee that this type is complete.
3429 // If it has a trivial destructor, we can avoid the extra copy.
Jeffrey Yasskinb7ee2e52011-01-27 19:17:54 +00003430 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall507384f2010-08-12 02:40:37 +00003431 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00003432 return Owned(E);
3433
Douglas Gregordb89f282010-07-01 22:47:18 +00003434 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
Anders Carlsson860306e2009-05-30 21:21:49 +00003435 ExprTemporaries.push_back(Temp);
Douglas Gregordb89f282010-07-01 22:47:18 +00003436 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003437 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00003438 CheckDestructorAccess(E->getExprLoc(), Destructor,
3439 PDiag(diag::err_access_dtor_temp)
3440 << E->getType());
3441 }
Anders Carlssondef11992009-05-30 20:36:53 +00003442 // FIXME: Add the temporary to the temporaries vector.
3443 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
3444}
3445
John McCall4765fa02010-12-06 08:20:24 +00003446Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003447 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00003448
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003449 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3450 assert(ExprTemporaries.size() >= FirstTemporary);
3451 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003452 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003453
John McCall4765fa02010-12-06 08:20:24 +00003454 Expr *E = ExprWithCleanups::Create(Context, SubExpr,
3455 &ExprTemporaries[FirstTemporary],
3456 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003457 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
3458 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00003459
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003460 return E;
3461}
3462
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003463ExprResult
John McCall4765fa02010-12-06 08:20:24 +00003464Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00003465 if (SubExpr.isInvalid())
3466 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003467
John McCall4765fa02010-12-06 08:20:24 +00003468 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00003469}
3470
John McCall4765fa02010-12-06 08:20:24 +00003471Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003472 assert(SubStmt && "sub statement can't be null!");
3473
3474 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3475 assert(ExprTemporaries.size() >= FirstTemporary);
3476 if (ExprTemporaries.size() == FirstTemporary)
3477 return SubStmt;
3478
3479 // FIXME: In order to attach the temporaries, wrap the statement into
3480 // a StmtExpr; currently this is only used for asm statements.
3481 // This is hacky, either create a new CXXStmtWithTemporaries statement or
3482 // a new AsmStmtWithTemporaries.
3483 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
3484 SourceLocation(),
3485 SourceLocation());
3486 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
3487 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00003488 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003489}
3490
John McCall60d7b3a2010-08-24 06:29:42 +00003491ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003492Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00003493 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00003494 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003495 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003496 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003497 if (Result.isInvalid()) return ExprError();
3498 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003499
John McCall9ae2f072010-08-23 23:25:46 +00003500 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00003501 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003502 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00003503 // If we have a pointer to a dependent type and are using the -> operator,
3504 // the object type is the type that the pointer points to. We might still
3505 // have enough information about that type to do something useful.
3506 if (OpKind == tok::arrow)
3507 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3508 BaseType = Ptr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003509
John McCallb3d87482010-08-24 05:47:05 +00003510 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00003511 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00003512 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003513 }
Mike Stump1eb44332009-09-09 15:08:12 +00003514
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003515 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00003516 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003517 // returned, with the original second operand.
3518 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00003519 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00003520 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00003521 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00003522 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003523
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003524 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00003525 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
3526 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003527 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00003528 Base = Result.get();
3529 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00003530 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00003531 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00003532 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00003533 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003534 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00003535 for (unsigned i = 0; i < Locations.size(); i++)
3536 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003537 return ExprError();
3538 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003539 }
Mike Stump1eb44332009-09-09 15:08:12 +00003540
Douglas Gregor31658df2009-11-20 19:58:21 +00003541 if (BaseType->isPointerType())
3542 BaseType = BaseType->getPointeeType();
3543 }
Mike Stump1eb44332009-09-09 15:08:12 +00003544
3545 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003546 // vector types or Objective-C interfaces. Just return early and let
3547 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00003548 if (!BaseType->isRecordType()) {
3549 // C++ [basic.lookup.classref]p2:
3550 // [...] If the type of the object expression is of pointer to scalar
3551 // type, the unqualified-id is looked up in the context of the complete
3552 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00003553 //
3554 // This also indicates that we should be parsing a
3555 // pseudo-destructor-name.
John McCallb3d87482010-08-24 05:47:05 +00003556 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00003557 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00003558 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00003559 }
Mike Stump1eb44332009-09-09 15:08:12 +00003560
Douglas Gregor03c57052009-11-17 05:17:33 +00003561 // The object type must be complete (or dependent).
3562 if (!BaseType->isDependentType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003563 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor03c57052009-11-17 05:17:33 +00003564 PDiag(diag::err_incomplete_member_access)))
3565 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003566
Douglas Gregorc68afe22009-09-03 21:38:09 +00003567 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00003568 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00003569 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00003570 // type C (or of pointer to a class type C), the unqualified-id is looked
3571 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00003572 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00003573 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003574}
3575
John McCall60d7b3a2010-08-24 06:29:42 +00003576ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003577 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00003578 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00003579 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
3580 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00003581 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003582
Douglas Gregor77549082010-02-24 21:29:12 +00003583 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00003584 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00003585 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00003586 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00003587 /*RPLoc*/ ExpectedLParenLoc);
3588}
Douglas Gregord4dca082010-02-24 18:44:31 +00003589
John McCall60d7b3a2010-08-24 06:29:42 +00003590ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00003591 SourceLocation OpLoc,
3592 tok::TokenKind OpKind,
3593 const CXXScopeSpec &SS,
3594 TypeSourceInfo *ScopeTypeInfo,
3595 SourceLocation CCLoc,
3596 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003597 PseudoDestructorTypeStorage Destructed,
John McCall2d9f5fa2011-02-25 05:21:17 +00003598 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003599 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003600
Douglas Gregorb57fb492010-02-24 22:38:50 +00003601 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003602 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregorb57fb492010-02-24 22:38:50 +00003603 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003604 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00003605 QualType ObjectType = Base->getType();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003606 if (OpKind == tok::arrow) {
3607 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3608 ObjectType = Ptr->getPointeeType();
John McCall9ae2f072010-08-23 23:25:46 +00003609 } else if (!Base->isTypeDependent()) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003610 // The user wrote "p->" when she probably meant "p."; fix it.
3611 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3612 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00003613 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00003614 if (isSFINAEContext())
3615 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003616
Douglas Gregorb57fb492010-02-24 22:38:50 +00003617 OpKind = tok::period;
3618 }
3619 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003620
Douglas Gregorb57fb492010-02-24 22:38:50 +00003621 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
3622 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCall9ae2f072010-08-23 23:25:46 +00003623 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003624 return ExprError();
3625 }
3626
3627 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003628 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb57fb492010-02-24 22:38:50 +00003629 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003630 if (DestructedTypeInfo) {
3631 QualType DestructedType = DestructedTypeInfo->getType();
3632 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003633 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003634 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
3635 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
3636 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00003637 << ObjectType << DestructedType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003638 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003639
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003640 // Recover by setting the destructed type to the object type.
3641 DestructedType = ObjectType;
3642 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
3643 DestructedTypeStart);
3644 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3645 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00003646 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003647
Douglas Gregorb57fb492010-02-24 22:38:50 +00003648 // C++ [expr.pseudo]p2:
3649 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
3650 // form
3651 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003652 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb57fb492010-02-24 22:38:50 +00003653 //
3654 // shall designate the same scalar type.
3655 if (ScopeTypeInfo) {
3656 QualType ScopeType = ScopeTypeInfo->getType();
3657 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00003658 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003659
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003660 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00003661 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00003662 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003663 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003664
Douglas Gregorb57fb492010-02-24 22:38:50 +00003665 ScopeType = QualType();
3666 ScopeTypeInfo = 0;
3667 }
3668 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003669
John McCall9ae2f072010-08-23 23:25:46 +00003670 Expr *Result
3671 = new (Context) CXXPseudoDestructorExpr(Context, Base,
3672 OpKind == tok::arrow, OpLoc,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00003673 SS.getWithLocInContext(Context),
John McCall9ae2f072010-08-23 23:25:46 +00003674 ScopeTypeInfo,
3675 CCLoc,
3676 TildeLoc,
3677 Destructed);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003678
Douglas Gregorb57fb492010-02-24 22:38:50 +00003679 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00003680 return Owned(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003681
John McCall9ae2f072010-08-23 23:25:46 +00003682 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00003683}
3684
John McCall60d7b3a2010-08-24 06:29:42 +00003685ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00003686 SourceLocation OpLoc,
3687 tok::TokenKind OpKind,
3688 CXXScopeSpec &SS,
3689 UnqualifiedId &FirstTypeName,
3690 SourceLocation CCLoc,
3691 SourceLocation TildeLoc,
3692 UnqualifiedId &SecondTypeName,
3693 bool HasTrailingLParen) {
Douglas Gregor77549082010-02-24 21:29:12 +00003694 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3695 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3696 "Invalid first type name in pseudo-destructor");
3697 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3698 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3699 "Invalid second type name in pseudo-destructor");
3700
Douglas Gregor77549082010-02-24 21:29:12 +00003701 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003702 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregor77549082010-02-24 21:29:12 +00003703 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003704 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00003705 QualType ObjectType = Base->getType();
Douglas Gregor77549082010-02-24 21:29:12 +00003706 if (OpKind == tok::arrow) {
3707 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3708 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003709 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00003710 // The user wrote "p->" when she probably meant "p."; fix it.
3711 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003712 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00003713 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00003714 if (isSFINAEContext())
3715 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003716
Douglas Gregor77549082010-02-24 21:29:12 +00003717 OpKind = tok::period;
3718 }
3719 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003720
3721 // Compute the object type that we should use for name lookup purposes. Only
3722 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00003723 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003724 if (!SS.isSet()) {
John McCall2d9f5fa2011-02-25 05:21:17 +00003725 if (ObjectType->isRecordType())
3726 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallb3d87482010-08-24 05:47:05 +00003727 else if (ObjectType->isDependentType())
3728 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003729 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003730
3731 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb57fb492010-02-24 22:38:50 +00003732 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00003733 QualType DestructedType;
3734 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003735 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00003736 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003737 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00003738 SecondTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00003739 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003740 if (!T &&
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003741 ((SS.isSet() && !computeDeclContext(SS, false)) ||
3742 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003743 // The name of the type being destroyed is a dependent name, and we
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003744 // couldn't find anything useful in scope. Just store the identifier and
3745 // it's location, and we'll perform (qualified) name lookup again at
3746 // template instantiation time.
3747 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
3748 SecondTypeName.StartLocation);
3749 } else if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003750 Diag(SecondTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00003751 diag::err_pseudo_dtor_destructor_non_type)
3752 << SecondTypeName.Identifier << ObjectType;
3753 if (isSFINAEContext())
3754 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003755
Douglas Gregor77549082010-02-24 21:29:12 +00003756 // Recover by assuming we had the right type all along.
3757 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003758 } else
Douglas Gregor77549082010-02-24 21:29:12 +00003759 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003760 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003761 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003762 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003763 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3764 TemplateId->getTemplateArgs(),
3765 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003766 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003767 TemplateId->TemplateNameLoc,
3768 TemplateId->LAngleLoc,
3769 TemplateArgsPtr,
3770 TemplateId->RAngleLoc);
3771 if (T.isInvalid() || !T.get()) {
3772 // Recover by assuming we had the right type all along.
3773 DestructedType = ObjectType;
3774 } else
3775 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003776 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003777
3778 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb57fb492010-02-24 22:38:50 +00003779 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003780 if (!DestructedType.isNull()) {
3781 if (!DestructedTypeInfo)
3782 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003783 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003784 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3785 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003786
Douglas Gregorb57fb492010-02-24 22:38:50 +00003787 // Convert the name of the scope type (the type prior to '::') into a type.
3788 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00003789 QualType ScopeType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003790 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor77549082010-02-24 21:29:12 +00003791 FirstTypeName.Identifier) {
3792 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003793 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00003794 FirstTypeName.StartLocation,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00003795 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00003796 if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003797 Diag(FirstTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00003798 diag::err_pseudo_dtor_destructor_non_type)
3799 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003800
Douglas Gregorb57fb492010-02-24 22:38:50 +00003801 if (isSFINAEContext())
3802 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003803
Douglas Gregorb57fb492010-02-24 22:38:50 +00003804 // Just drop this type. It's unnecessary anyway.
3805 ScopeType = QualType();
3806 } else
3807 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003808 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003809 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003810 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003811 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3812 TemplateId->getTemplateArgs(),
3813 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003814 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003815 TemplateId->TemplateNameLoc,
3816 TemplateId->LAngleLoc,
3817 TemplateArgsPtr,
3818 TemplateId->RAngleLoc);
3819 if (T.isInvalid() || !T.get()) {
3820 // Recover by dropping this type.
3821 ScopeType = QualType();
3822 } else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003823 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003824 }
3825 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003826
Douglas Gregorb4a418f2010-02-24 23:02:30 +00003827 if (!ScopeType.isNull() && !ScopeTypeInfo)
3828 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3829 FirstTypeName.StartLocation);
3830
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003831
John McCall9ae2f072010-08-23 23:25:46 +00003832 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003833 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003834 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00003835}
3836
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003837ExprResult Sema::BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
3838 CXXMethodDecl *Method) {
John McCall6bb80172010-03-30 21:47:33 +00003839 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3840 FoundDecl, Method))
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003841 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00003842
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003843 MemberExpr *ME =
Abramo Bagnara25777432010-08-11 22:01:17 +00003844 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
John McCallf89e55a2010-11-18 06:31:45 +00003845 SourceLocation(), Method->getType(),
3846 VK_RValue, OK_Ordinary);
3847 QualType ResultType = Method->getResultType();
3848 ExprValueKind VK = Expr::getValueKindForType(ResultType);
3849 ResultType = ResultType.getNonLValueExprType(Context);
3850
Douglas Gregor7edfb692009-11-23 12:27:39 +00003851 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3852 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00003853 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
Douglas Gregor7edfb692009-11-23 12:27:39 +00003854 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003855 return CE;
3856}
3857
Sebastian Redl2e156222010-09-10 20:55:43 +00003858ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
3859 SourceLocation RParen) {
Sebastian Redl2e156222010-09-10 20:55:43 +00003860 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
3861 Operand->CanThrow(Context),
3862 KeyLoc, RParen));
3863}
3864
3865ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
3866 Expr *Operand, SourceLocation RParen) {
3867 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00003868}
3869
John McCallf6a16482010-12-04 03:47:34 +00003870/// Perform the conversions required for an expression used in a
3871/// context that ignores the result.
3872void Sema::IgnoredValueConversions(Expr *&E) {
John McCalla878cda2010-12-02 02:07:15 +00003873 // C99 6.3.2.1:
3874 // [Except in specific positions,] an lvalue that does not have
3875 // array type is converted to the value stored in the
3876 // designated object (and is no longer an lvalue).
John McCallf6a16482010-12-04 03:47:34 +00003877 if (E->isRValue()) return;
John McCalla878cda2010-12-02 02:07:15 +00003878
John McCallf6a16482010-12-04 03:47:34 +00003879 // We always want to do this on ObjC property references.
3880 if (E->getObjectKind() == OK_ObjCProperty) {
3881 ConvertPropertyForRValue(E);
3882 if (E->isRValue()) return;
3883 }
3884
3885 // Otherwise, this rule does not apply in C++, at least not for the moment.
3886 if (getLangOptions().CPlusPlus) return;
3887
3888 // GCC seems to also exclude expressions of incomplete enum type.
3889 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
3890 if (!T->getDecl()->isComplete()) {
3891 // FIXME: stupid workaround for a codegen bug!
3892 ImpCastExprToType(E, Context.VoidTy, CK_ToVoid);
3893 return;
3894 }
3895 }
3896
3897 DefaultFunctionArrayLvalueConversion(E);
John McCall85515d62010-12-04 12:29:11 +00003898 if (!E->getType()->isVoidType())
3899 RequireCompleteType(E->getExprLoc(), E->getType(),
3900 diag::err_incomplete_type);
John McCallf6a16482010-12-04 03:47:34 +00003901}
3902
3903ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003904 if (!FullExpr)
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003905 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00003906
Douglas Gregord0937222010-12-13 22:49:22 +00003907 if (DiagnoseUnexpandedParameterPack(FullExpr))
3908 return ExprError();
3909
John McCallf6a16482010-12-04 03:47:34 +00003910 IgnoredValueConversions(FullExpr);
John McCallb4eb64d2010-10-08 02:01:28 +00003911 CheckImplicitConversions(FullExpr);
John McCall4765fa02010-12-06 08:20:24 +00003912 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00003913}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003914
3915StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
3916 if (!FullStmt) return StmtError();
3917
John McCall4765fa02010-12-06 08:20:24 +00003918 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003919}