blob: 8581c6f649482fb156d71a55b355be9ad6779d87 [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"
19#include "clang/Sema/TemplateDeduction.h"
Steve Naroff210679c2007-08-25 14:02:58 +000020#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000021#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000023#include "clang/AST/ExprCXX.h"
Fariborz Jahaniand4266622010-06-16 18:56:04 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregorb57fb492010-02-24 22:38:50 +000025#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000026#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000027#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000028#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000029#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000031using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000032
John McCallb3d87482010-08-24 05:47:05 +000033ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000034 IdentifierInfo &II,
John McCallb3d87482010-08-24 05:47:05 +000035 SourceLocation NameLoc,
36 Scope *S, CXXScopeSpec &SS,
37 ParsedType ObjectTypePtr,
38 bool EnteringContext) {
Douglas Gregor124b8782010-02-16 19:09:40 +000039 // Determine where to perform name lookup.
40
41 // FIXME: This area of the standard is very messy, and the current
42 // wording is rather unclear about which scopes we search for the
43 // destructor name; see core issues 399 and 555. Issue 399 in
44 // particular shows where the current description of destructor name
45 // lookup is completely out of line with existing practice, e.g.,
46 // this appears to be ill-formed:
47 //
48 // namespace N {
49 // template <typename T> struct S {
50 // ~S();
51 // };
52 // }
53 //
54 // void f(N::S<int>* s) {
55 // s->N::S<int>::~S();
56 // }
57 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000058 // See also PR6358 and PR6359.
Sebastian Redlc0fee502010-07-07 23:17:38 +000059 // For this reason, we're currently only doing the C++03 version of this
60 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregor124b8782010-02-16 19:09:40 +000061 QualType SearchType;
62 DeclContext *LookupCtx = 0;
63 bool isDependent = false;
64 bool LookInScope = false;
65
66 // If we have an object type, it's because we are in a
67 // pseudo-destructor-expression or a member access expression, and
68 // we know what type we're looking for.
69 if (ObjectTypePtr)
70 SearchType = GetTypeFromParser(ObjectTypePtr);
71
72 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000073 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000074
Douglas Gregor93649fd2010-02-23 00:15:22 +000075 bool AlreadySearched = false;
76 bool LookAtPrefix = true;
Sebastian Redlc0fee502010-07-07 23:17:38 +000077 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000078 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redlc0fee502010-07-07 23:17:38 +000079 // the type-names are looked up as types in the scope designated by the
80 // nested-name-specifier. In a qualified-id of the form:
NAKAMURA Takumi00995302011-01-27 07:09:49 +000081 //
82 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redlc0fee502010-07-07 23:17:38 +000083 //
84 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth5e895a82010-02-21 10:19:54 +000085 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +000086 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +000087 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregor124b8782010-02-16 19:09:40 +000088 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000089 // the class-names are looked up as types in the scope designated by
Sebastian Redlc0fee502010-07-07 23:17:38 +000090 // the nested-name-specifier.
Douglas Gregor124b8782010-02-16 19:09:40 +000091 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000092 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000093 // code below is permitted to look at the prefix of the
Sebastian Redlc0fee502010-07-07 23:17:38 +000094 // nested-name-specifier.
95 DeclContext *DC = computeDeclContext(SS, EnteringContext);
96 if (DC && DC->isFileContext()) {
97 AlreadySearched = true;
98 LookupCtx = DC;
99 isDependent = false;
100 } else if (DC && isa<CXXRecordDecl>(DC))
101 LookAtPrefix = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000102
Sebastian Redlc0fee502010-07-07 23:17:38 +0000103 // The second case from the C++03 rules quoted further above.
Douglas Gregor93649fd2010-02-23 00:15:22 +0000104 NestedNameSpecifier *Prefix = 0;
105 if (AlreadySearched) {
106 // Nothing left to do.
107 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
108 CXXScopeSpec PrefixSS;
109 PrefixSS.setScopeRep(Prefix);
110 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
111 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000112 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000113 LookupCtx = computeDeclContext(SearchType);
114 isDependent = SearchType->isDependentType();
115 } else {
116 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000117 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000118 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000119
Douglas Gregoredc90502010-02-25 04:46:04 +0000120 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000121 } else if (ObjectTypePtr) {
122 // C++ [basic.lookup.classref]p3:
123 // If the unqualified-id is ~type-name, the type-name is looked up
124 // in the context of the entire postfix-expression. If the type T
125 // of the object expression is of a class type C, the type-name is
126 // also looked up in the scope of class C. At least one of the
127 // lookups shall find a name that refers to (possibly
128 // cv-qualified) T.
129 LookupCtx = computeDeclContext(SearchType);
130 isDependent = SearchType->isDependentType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000131 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregor124b8782010-02-16 19:09:40 +0000132 "Caller should have completed object type");
133
134 LookInScope = true;
135 } else {
136 // Perform lookup into the current scope (only).
137 LookInScope = true;
138 }
139
140 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
141 for (unsigned Step = 0; Step != 2; ++Step) {
142 // Look for the name first in the computed lookup context (if we
143 // have one) and, if that fails to find a match, in the sope (if
144 // we're allowed to look there).
145 Found.clear();
146 if (Step == 0 && LookupCtx)
147 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000148 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000149 LookupName(Found, S);
150 else
151 continue;
152
153 // FIXME: Should we be suppressing ambiguities here?
154 if (Found.isAmbiguous())
John McCallb3d87482010-08-24 05:47:05 +0000155 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000156
157 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
158 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000159
160 if (SearchType.isNull() || SearchType->isDependentType() ||
161 Context.hasSameUnqualifiedType(T, SearchType)) {
162 // We found our type!
163
John McCallb3d87482010-08-24 05:47:05 +0000164 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000165 }
166 }
167
168 // If the name that we found is a class template name, and it is
169 // the same name as the template name in the last part of the
170 // nested-name-specifier (if present) or the object type, then
171 // this is the destructor for that class.
172 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000173 // issue 399, for which there isn't even an obvious direction.
Douglas Gregor124b8782010-02-16 19:09:40 +0000174 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
175 QualType MemberOfType;
176 if (SS.isSet()) {
177 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
178 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000179 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
180 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000181 }
182 }
183 if (MemberOfType.isNull())
184 MemberOfType = SearchType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000185
Douglas Gregor124b8782010-02-16 19:09:40 +0000186 if (MemberOfType.isNull())
187 continue;
188
189 // We're referring into a class template specialization. If the
190 // class template we found is the same as the template being
191 // specialized, we found what we are looking for.
192 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
193 if (ClassTemplateSpecializationDecl *Spec
194 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
195 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
196 Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000197 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000198 }
199
200 continue;
201 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000202
Douglas Gregor124b8782010-02-16 19:09:40 +0000203 // We're referring to an unresolved class template
204 // specialization. Determine whether we class template we found
205 // is the same as the template being specialized or, if we don't
206 // know which template is being specialized, that it at least
207 // has the same name.
208 if (const TemplateSpecializationType *SpecType
209 = MemberOfType->getAs<TemplateSpecializationType>()) {
210 TemplateName SpecName = SpecType->getTemplateName();
211
212 // The class template we found is the same template being
213 // specialized.
214 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
215 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000216 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000217
218 continue;
219 }
220
221 // The class template we found has the same name as the
222 // (dependent) template name being specialized.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000223 if (DependentTemplateName *DepTemplate
Douglas Gregor124b8782010-02-16 19:09:40 +0000224 = SpecName.getAsDependentTemplateName()) {
225 if (DepTemplate->isIdentifier() &&
226 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallb3d87482010-08-24 05:47:05 +0000227 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000228
229 continue;
230 }
231 }
232 }
233 }
234
235 if (isDependent) {
236 // We didn't find our type, but that's okay: it's dependent
237 // anyway.
238 NestedNameSpecifier *NNS = 0;
239 SourceRange Range;
240 if (SS.isSet()) {
241 NNS = (NestedNameSpecifier *)SS.getScopeRep();
242 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
243 } else {
244 NNS = NestedNameSpecifier::Create(Context, &II);
245 Range = SourceRange(NameLoc);
246 }
247
John McCallb3d87482010-08-24 05:47:05 +0000248 QualType T = CheckTypenameType(ETK_None, NNS, II,
249 SourceLocation(),
250 Range, NameLoc);
251 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000252 }
253
254 if (ObjectTypePtr)
255 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000256 << &II;
Douglas Gregor124b8782010-02-16 19:09:40 +0000257 else
258 Diag(NameLoc, diag::err_destructor_class_name);
259
John McCallb3d87482010-08-24 05:47:05 +0000260 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000261}
262
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000263/// \brief Build a C++ typeid expression with a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000264ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000265 SourceLocation TypeidLoc,
266 TypeSourceInfo *Operand,
267 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000268 // C++ [expr.typeid]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000269 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000270 // that is the operand of typeid are always ignored.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000271 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000272 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000273 Qualifiers Quals;
274 QualType T
275 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
276 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000277 if (T->getAs<RecordType>() &&
278 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
279 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000280
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000281 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
282 Operand,
283 SourceRange(TypeidLoc, RParenLoc)));
284}
285
286/// \brief Build a C++ typeid expression with an expression operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000287ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000288 SourceLocation TypeidLoc,
289 Expr *E,
290 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000291 bool isUnevaluatedOperand = true;
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000292 if (E && !E->isTypeDependent()) {
293 QualType T = E->getType();
294 if (const RecordType *RecordT = T->getAs<RecordType>()) {
295 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
296 // C++ [expr.typeid]p3:
297 // [...] If the type of the expression is a class type, the class
298 // shall be completely-defined.
299 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
300 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000301
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000302 // C++ [expr.typeid]p3:
Sebastian Redl906082e2010-07-20 04:20:21 +0000303 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000304 // polymorphic class type [...] [the] expression is an unevaluated
305 // operand. [...]
Sebastian Redl906082e2010-07-20 04:20:21 +0000306 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000307 isUnevaluatedOperand = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000308
309 // We require a vtable to query the type at run time.
310 MarkVTableUsed(TypeidLoc, RecordD);
311 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000312 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000313
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000314 // C++ [expr.typeid]p4:
315 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000316 // cv-qualified type, the result of the typeid expression refers to a
317 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000318 // type.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000319 Qualifiers Quals;
320 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
321 if (!Context.hasSameType(T, UnqualT)) {
322 T = UnqualT;
John McCall2de56d12010-08-25 11:45:40 +0000323 ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000324 }
325 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000326
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000327 // If this is an unevaluated operand, clear out the set of
328 // declaration references we have been computing and eliminate any
329 // temporaries introduced in its computation.
330 if (isUnevaluatedOperand)
331 ExprEvalContexts.back().Context = Unevaluated;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000332
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000333 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCall9ae2f072010-08-23 23:25:46 +0000334 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000335 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000336}
337
338/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCall60d7b3a2010-08-24 06:29:42 +0000339ExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000340Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
341 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000342 // Find the std::type_info type.
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000343 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000344 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000345
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000346 if (!CXXTypeInfoDecl) {
347 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
348 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
349 LookupQualifiedName(R, getStdNamespace());
350 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
351 if (!CXXTypeInfoDecl)
352 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
353 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000354
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000355 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000356
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000357 if (isType) {
358 // The operand is a type; handle it as such.
359 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +0000360 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
361 &TInfo);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000362 if (T.isNull())
363 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000364
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000365 if (!TInfo)
366 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000367
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000368 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000369 }
Mike Stump1eb44332009-09-09 15:08:12 +0000370
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000371 // The operand is an expression.
John McCall9ae2f072010-08-23 23:25:46 +0000372 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000373}
374
Francois Pichet6915c522010-12-27 01:32:00 +0000375/// Retrieve the UuidAttr associated with QT.
376static UuidAttr *GetUuidAttrOfType(QualType QT) {
377 // Optionally remove one level of pointer, reference or array indirection.
John McCallf4c73712011-01-19 06:33:43 +0000378 const Type *Ty = QT.getTypePtr();;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000379 if (QT->isPointerType() || QT->isReferenceType())
380 Ty = QT->getPointeeType().getTypePtr();
381 else if (QT->isArrayType())
382 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
383
Francois Pichet6915c522010-12-27 01:32:00 +0000384 // Loop all class definition and declaration looking for an uuid attribute.
385 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
386 while (RD) {
387 if (UuidAttr *Uuid = RD->getAttr<UuidAttr>())
388 return Uuid;
389 RD = RD->getPreviousDeclaration();
390 }
391 return 0;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000392}
393
Francois Pichet01b7c302010-09-08 12:20:18 +0000394/// \brief Build a Microsoft __uuidof expression with a type operand.
395ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
396 SourceLocation TypeidLoc,
397 TypeSourceInfo *Operand,
398 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000399 if (!Operand->getType()->isDependentType()) {
400 if (!GetUuidAttrOfType(Operand->getType()))
401 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
402 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000403
Francois Pichet01b7c302010-09-08 12:20:18 +0000404 // FIXME: add __uuidof semantic analysis for type operand.
405 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
406 Operand,
407 SourceRange(TypeidLoc, RParenLoc)));
408}
409
410/// \brief Build a Microsoft __uuidof expression with an expression operand.
411ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
412 SourceLocation TypeidLoc,
413 Expr *E,
414 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000415 if (!E->getType()->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000416 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichet6915c522010-12-27 01:32:00 +0000417 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
418 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
419 }
420 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet01b7c302010-09-08 12:20:18 +0000421 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
422 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000423 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet01b7c302010-09-08 12:20:18 +0000424}
425
426/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
427ExprResult
428Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
429 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000430 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet01b7c302010-09-08 12:20:18 +0000431 if (!MSVCGuidDecl) {
432 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
433 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
434 LookupQualifiedName(R, Context.getTranslationUnitDecl());
435 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
436 if (!MSVCGuidDecl)
437 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000438 }
439
Francois Pichet01b7c302010-09-08 12:20:18 +0000440 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000441
Francois Pichet01b7c302010-09-08 12:20:18 +0000442 if (isType) {
443 // The operand is a type; handle it as such.
444 TypeSourceInfo *TInfo = 0;
445 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
446 &TInfo);
447 if (T.isNull())
448 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000449
Francois Pichet01b7c302010-09-08 12:20:18 +0000450 if (!TInfo)
451 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
452
453 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
454 }
455
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000456 // The operand is an expression.
Francois Pichet01b7c302010-09-08 12:20:18 +0000457 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
458}
459
Steve Naroff1b273c42007-09-16 14:56:35 +0000460/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCall60d7b3a2010-08-24 06:29:42 +0000461ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000462Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000463 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000464 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000465 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
466 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000467}
Chris Lattner50dd2892008-02-26 00:51:44 +0000468
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000469/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCall60d7b3a2010-08-24 06:29:42 +0000470ExprResult
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000471Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
472 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
473}
474
Chris Lattner50dd2892008-02-26 00:51:44 +0000475/// ActOnCXXThrow - Parse throw expressions.
John McCall60d7b3a2010-08-24 06:29:42 +0000476ExprResult
John McCall9ae2f072010-08-23 23:25:46 +0000477Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000478 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
479 return ExprError();
480 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
481}
482
483/// CheckCXXThrowOperand - Validate the operand of a throw.
484bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
485 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000486 // A throw-expression initializes a temporary object, called the exception
487 // object, the type of which is determined by removing any top-level
488 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000489 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor154fe982009-12-23 22:04:40 +0000490 // or "pointer to function returning T", [...]
491 if (E->getType().hasQualifiers())
John McCall2de56d12010-08-25 11:45:40 +0000492 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Sebastian Redl906082e2010-07-20 04:20:21 +0000493 CastCategory(E));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000494
Sebastian Redl972041f2009-04-27 20:27:31 +0000495 DefaultFunctionArrayConversion(E);
496
497 // If the type of the exception would be an incomplete type or a pointer
498 // to an incomplete type other than (cv) void the program is ill-formed.
499 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000500 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000501 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000502 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000503 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000504 }
505 if (!isPointer || !Ty->isVoidType()) {
506 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000507 PDiag(isPointer ? diag::err_throw_incomplete_ptr
508 : diag::err_throw_incomplete)
509 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000510 return true;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000511
Douglas Gregorbf422f92010-04-15 18:05:39 +0000512 if (RequireNonAbstractType(ThrowLoc, E->getType(),
513 PDiag(diag::err_throw_abstract_type)
514 << E->getSourceRange()))
515 return true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000516 }
517
John McCallac418162010-04-22 01:10:34 +0000518 // Initialize the exception result. This implicitly weeds out
519 // abstract types or types with inaccessible copy constructors.
Douglas Gregor72dfa272011-01-21 22:46:35 +0000520 const VarDecl *NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
521
Douglas Gregorf5d8f462011-01-21 18:05:27 +0000522 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p32.
John McCallac418162010-04-22 01:10:34 +0000523 InitializedEntity Entity =
Douglas Gregor72dfa272011-01-21 22:46:35 +0000524 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
525 /*NRVO=*/false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000526 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregor72dfa272011-01-21 22:46:35 +0000527 QualType(), E);
John McCallac418162010-04-22 01:10:34 +0000528 if (Res.isInvalid())
529 return true;
530 E = Res.takeAs<Expr>();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000531
Eli Friedman5ed9b932010-06-03 20:39:03 +0000532 // If the exception has class type, we need additional handling.
533 const RecordType *RecordTy = Ty->getAs<RecordType>();
534 if (!RecordTy)
535 return false;
536 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
537
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000538 // If we are throwing a polymorphic class type or pointer thereof,
539 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000540 MarkVTableUsed(ThrowLoc, RD);
541
Eli Friedman98efb9f2010-10-12 20:32:36 +0000542 // If a pointer is thrown, the referenced object will not be destroyed.
543 if (isPointer)
544 return false;
545
Eli Friedman5ed9b932010-06-03 20:39:03 +0000546 // If the class has a non-trivial destructor, we must be able to call it.
547 if (RD->hasTrivialDestructor())
548 return false;
549
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000550 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +0000551 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman5ed9b932010-06-03 20:39:03 +0000552 if (!Destructor)
553 return false;
554
555 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
556 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000557 PDiag(diag::err_access_dtor_exception) << Ty);
Sebastian Redl972041f2009-04-27 20:27:31 +0000558 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000559}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000560
John McCall60d7b3a2010-08-24 06:29:42 +0000561ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000562 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
563 /// is a non-lvalue expression whose value is the address of the object for
564 /// which the function is called.
565
John McCallea1471e2010-05-20 01:18:31 +0000566 DeclContext *DC = getFunctionLevelDeclContext();
567 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000568 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000569 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000570 MD->getThisType(Context),
571 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000572
Sebastian Redlf53597f2009-03-15 17:47:39 +0000573 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000574}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000575
John McCall60d7b3a2010-08-24 06:29:42 +0000576ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000577Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000578 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000579 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000580 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000581 if (!TypeRep)
582 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000583
John McCall9d125032010-01-15 18:39:57 +0000584 TypeSourceInfo *TInfo;
585 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
586 if (!TInfo)
587 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000588
589 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
590}
591
592/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
593/// Can be interpreted either as function-style casting ("int(x)")
594/// or class type construction ("ClassType(x,y,z)")
595/// or creation of a value-initialized type ("int()").
596ExprResult
597Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
598 SourceLocation LParenLoc,
599 MultiExprArg exprs,
600 SourceLocation RParenLoc) {
601 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000602 unsigned NumExprs = exprs.size();
603 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000604 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000605 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
606
Sebastian Redlf53597f2009-03-15 17:47:39 +0000607 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000608 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000609 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000610
Douglas Gregorab6677e2010-09-08 00:15:04 +0000611 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000612 LParenLoc,
613 Exprs, NumExprs,
614 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000615 }
616
Anders Carlssonbb60a502009-08-27 03:53:50 +0000617 if (Ty->isArrayType())
618 return ExprError(Diag(TyBeginLoc,
619 diag::err_value_init_for_array_type) << FullRange);
620 if (!Ty->isVoidType() &&
621 RequireCompleteType(TyBeginLoc, Ty,
622 PDiag(diag::err_invalid_incomplete_type_use)
623 << FullRange))
624 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000625
Anders Carlssonbb60a502009-08-27 03:53:50 +0000626 if (RequireNonAbstractType(TyBeginLoc, Ty,
627 diag::err_allocation_of_abstract_type))
628 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000629
630
Douglas Gregor506ae412009-01-16 18:33:17 +0000631 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000632 // If the expression list is a single expression, the type conversion
633 // expression is equivalent (in definedness, and if defined in meaning) to the
634 // corresponding cast expression.
635 //
636 if (NumExprs == 1) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000637 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +0000638 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +0000639 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000640 if (CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
John McCallf89e55a2010-11-18 06:31:45 +0000641 Kind, VK, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000642 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000643 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000644
645 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000646
John McCallf871d0c2010-08-07 06:22:56 +0000647 return Owned(CXXFunctionalCastExpr::Create(Context,
Douglas Gregorab6677e2010-09-08 00:15:04 +0000648 Ty.getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +0000649 VK, TInfo, TyBeginLoc, Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000650 Exprs[0], &BasePath,
651 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000652 }
653
Douglas Gregor19311e72010-09-08 21:40:08 +0000654 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
655 InitializationKind Kind
656 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
657 LParenLoc, RParenLoc)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000658 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor19311e72010-09-08 21:40:08 +0000659 LParenLoc, RParenLoc);
660 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
661 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000662
Douglas Gregor19311e72010-09-08 21:40:08 +0000663 // FIXME: Improve AST representation?
664 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000665}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000666
John McCall6ec278d2011-01-27 09:37:56 +0000667/// doesUsualArrayDeleteWantSize - Answers whether the usual
668/// operator delete[] for the given type has a size_t parameter.
669static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
670 QualType allocType) {
671 const RecordType *record =
672 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
673 if (!record) return false;
674
675 // Try to find an operator delete[] in class scope.
676
677 DeclarationName deleteName =
678 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
679 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
680 S.LookupQualifiedName(ops, record->getDecl());
681
682 // We're just doing this for information.
683 ops.suppressDiagnostics();
684
685 // Very likely: there's no operator delete[].
686 if (ops.empty()) return false;
687
688 // If it's ambiguous, it should be illegal to call operator delete[]
689 // on this thing, so it doesn't matter if we allocate extra space or not.
690 if (ops.isAmbiguous()) return false;
691
692 LookupResult::Filter filter = ops.makeFilter();
693 while (filter.hasNext()) {
694 NamedDecl *del = filter.next()->getUnderlyingDecl();
695
696 // C++0x [basic.stc.dynamic.deallocation]p2:
697 // A template instance is never a usual deallocation function,
698 // regardless of its signature.
699 if (isa<FunctionTemplateDecl>(del)) {
700 filter.erase();
701 continue;
702 }
703
704 // C++0x [basic.stc.dynamic.deallocation]p2:
705 // If class T does not declare [an operator delete[] with one
706 // parameter] but does declare a member deallocation function
707 // named operator delete[] with exactly two parameters, the
708 // second of which has type std::size_t, then this function
709 // is a usual deallocation function.
710 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
711 filter.erase();
712 continue;
713 }
714 }
715 filter.done();
716
717 if (!ops.isSingleResult()) return false;
718
719 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
720 return (del->getNumParams() == 2);
721}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000722
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000723/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
724/// @code new (memory) int[size][4] @endcode
725/// or
726/// @code ::new Foo(23, "hello") @endcode
727/// For the interpretation of this heap of arguments, consult the base version.
John McCall60d7b3a2010-08-24 06:29:42 +0000728ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000729Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000730 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000731 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000732 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000733 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000734 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000735 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000736 // If the specified type is an array, unwrap it and save the expression.
737 if (D.getNumTypeObjects() > 0 &&
738 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
739 DeclaratorChunk &Chunk = D.getTypeObject(0);
740 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000741 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
742 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000743 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000744 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
745 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000746
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000747 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000748 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000749 }
750
Douglas Gregor043cad22009-09-11 00:18:58 +0000751 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000752 if (ArraySize) {
753 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000754 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
755 break;
756
757 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
758 if (Expr *NumElts = (Expr *)Array.NumElts) {
759 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
760 !NumElts->isIntegerConstantExpr(Context)) {
761 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
762 << NumElts->getSourceRange();
763 return ExprError();
764 }
765 }
766 }
767 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000768
John McCallbf1a0282010-06-04 23:28:52 +0000769 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
770 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000771 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000772 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000773
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000774 if (!TInfo)
775 TInfo = Context.getTrivialTypeSourceInfo(AllocType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000776
Mike Stump1eb44332009-09-09 15:08:12 +0000777 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000778 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000779 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000780 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000781 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000782 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000783 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000784 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000785 ConstructorLParen,
786 move(ConstructorArgs),
787 ConstructorRParen);
788}
789
John McCall60d7b3a2010-08-24 06:29:42 +0000790ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000791Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
792 SourceLocation PlacementLParen,
793 MultiExprArg PlacementArgs,
794 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000795 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000796 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000797 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000798 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000799 SourceLocation ConstructorLParen,
800 MultiExprArg ConstructorArgs,
801 SourceLocation ConstructorRParen) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000802 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000803
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000804 // Per C++0x [expr.new]p5, the type being constructed may be a
805 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +0000806 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000807 if (const ConstantArrayType *Array
808 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000809 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
810 Context.getSizeType(),
811 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000812 AllocType = Array->getElementType();
813 }
814 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000815
Douglas Gregora0750762010-10-06 16:00:31 +0000816 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
817 return ExprError();
818
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000819 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000820
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000821 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
822 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000823 if (ArraySize && !ArraySize->isTypeDependent()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000824
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000825 QualType SizeType = ArraySize->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000826
John McCall60d7b3a2010-08-24 06:29:42 +0000827 ExprResult ConvertedSize
John McCall9ae2f072010-08-23 23:25:46 +0000828 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000829 PDiag(diag::err_array_size_not_integral),
830 PDiag(diag::err_array_size_incomplete_type)
831 << ArraySize->getSourceRange(),
832 PDiag(diag::err_array_size_explicit_conversion),
833 PDiag(diag::note_array_size_conversion),
834 PDiag(diag::err_array_size_ambiguous_conversion),
835 PDiag(diag::note_array_size_conversion),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000836 PDiag(getLangOptions().CPlusPlus0x? 0
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000837 : diag::ext_array_size_conversion));
838 if (ConvertedSize.isInvalid())
839 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000840
John McCall9ae2f072010-08-23 23:25:46 +0000841 ArraySize = ConvertedSize.take();
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000842 SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000843 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000844 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000845
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000846 // Let's see if this is a constant < 0. If so, we reject it out of hand.
847 // We don't care about special rules, so we tell the machinery it's not
848 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000849 if (!ArraySize->isValueDependent()) {
850 llvm::APSInt Value;
851 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
852 if (Value < llvm::APSInt(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000853 llvm::APInt::getNullValue(Value.getBitWidth()),
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000854 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000855 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000856 diag::err_typecheck_negative_array_size)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000857 << ArraySize->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000858
Douglas Gregor2767ce22010-08-18 00:39:00 +0000859 if (!AllocType->isDependentType()) {
860 unsigned ActiveSizeBits
861 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
862 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000863 Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000864 diag::err_array_too_large)
865 << Value.toString(10)
866 << ArraySize->getSourceRange();
867 return ExprError();
868 }
869 }
Douglas Gregor4bd40312010-07-13 15:54:32 +0000870 } else if (TypeIdParens.isValid()) {
871 // Can't have dynamic array size when the type-id is in parentheses.
872 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
873 << ArraySize->getSourceRange()
874 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
875 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000876
Douglas Gregor4bd40312010-07-13 15:54:32 +0000877 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +0000878 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000879 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000880
Eli Friedman73c39ab2009-10-20 08:27:19 +0000881 ImpCastExprToType(ArraySize, Context.getSizeType(),
John McCall2de56d12010-08-25 11:45:40 +0000882 CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000883 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000884
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000885 FunctionDecl *OperatorNew = 0;
886 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000887 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
888 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000889
Sebastian Redl28507842009-02-26 14:39:58 +0000890 if (!AllocType->isDependentType() &&
891 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
892 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000893 SourceRange(PlacementLParen, PlacementRParen),
894 UseGlobal, AllocType, ArraySize, PlaceArgs,
895 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000896 return ExprError();
John McCall6ec278d2011-01-27 09:37:56 +0000897
898 // If this is an array allocation, compute whether the usual array
899 // deallocation function for the type has a size_t parameter.
900 bool UsualArrayDeleteWantsSize = false;
901 if (ArraySize && !AllocType->isDependentType())
902 UsualArrayDeleteWantsSize
903 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
904
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000905 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000906 if (OperatorNew) {
907 // Add default arguments, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000908 const FunctionProtoType *Proto =
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000909 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000910 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000911 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000912
Anders Carlsson28e94832010-05-03 02:07:56 +0000913 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000914 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlsson28e94832010-05-03 02:07:56 +0000915 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000916 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000917
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000918 NumPlaceArgs = AllPlaceArgs.size();
919 if (NumPlaceArgs > 0)
920 PlaceArgs = &AllPlaceArgs[0];
921 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000922
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000923 bool Init = ConstructorLParen.isValid();
924 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000925 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000926 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
927 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +0000928 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000929
Anders Carlsson48c95012010-05-03 15:45:23 +0000930 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +0000931 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +0000932 SourceRange InitRange(ConsArgs[0]->getLocStart(),
933 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000934
Anders Carlsson48c95012010-05-03 15:45:23 +0000935 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
936 return ExprError();
937 }
938
Douglas Gregor99a2e602009-12-16 01:38:02 +0000939 if (!AllocType->isDependentType() &&
940 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
941 // C++0x [expr.new]p15:
942 // A new-expression that creates an object of type T initializes that
943 // object as follows:
944 InitializationKind Kind
945 // - If the new-initializer is omitted, the object is default-
946 // initialized (8.5); if no initialization is performed,
947 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000948 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000949 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor99a2e602009-12-16 01:38:02 +0000950 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000951 : InitializationKind::CreateDirect(TypeRange.getBegin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000952 ConstructorLParen,
Douglas Gregor99a2e602009-12-16 01:38:02 +0000953 ConstructorRParen);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000954
Douglas Gregor99a2e602009-12-16 01:38:02 +0000955 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000956 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000957 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000958 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +0000959 move(ConstructorArgs));
960 if (FullInit.isInvalid())
961 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000962
963 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor99a2e602009-12-16 01:38:02 +0000964 // constructor call, which CXXNewExpr handles directly.
965 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
966 if (CXXBindTemporaryExpr *Binder
967 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
968 FullInitExpr = Binder->getSubExpr();
969 if (CXXConstructExpr *Construct
970 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
971 Constructor = Construct->getConstructor();
972 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
973 AEnd = Construct->arg_end();
974 A != AEnd; ++A)
John McCall3fa5cae2010-10-26 07:05:15 +0000975 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000976 } else {
977 // Take the converted initializer.
978 ConvertedConstructorArgs.push_back(FullInit.release());
979 }
980 } else {
981 // No initialization required.
982 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000983
Douglas Gregor99a2e602009-12-16 01:38:02 +0000984 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000985 NumConsArgs = ConvertedConstructorArgs.size();
986 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000987 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000988
Douglas Gregor6d908702010-02-26 05:06:18 +0000989 // Mark the new and delete operators as referenced.
990 if (OperatorNew)
991 MarkDeclarationReferenced(StartLoc, OperatorNew);
992 if (OperatorDelete)
993 MarkDeclarationReferenced(StartLoc, OperatorDelete);
994
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000995 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000996
Sebastian Redlf53597f2009-03-15 17:47:39 +0000997 PlacementArgs.release();
998 ConstructorArgs.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000999
Ted Kremenekad7fe862010-02-11 22:51:03 +00001000 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001001 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001002 ArraySize, Constructor, Init,
1003 ConsArgs, NumConsArgs, OperatorDelete,
John McCall6ec278d2011-01-27 09:37:56 +00001004 UsualArrayDeleteWantsSize,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001005 ResultType, AllocTypeInfo,
1006 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001007 Init ? ConstructorRParen :
Chandler Carruth428edaf2010-10-25 08:47:36 +00001008 TypeRange.getEnd(),
1009 ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001010}
1011
1012/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1013/// in a new-expression.
1014/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +00001015bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00001016 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001017 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1018 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +00001019 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001020 return Diag(Loc, diag::err_bad_new_type)
1021 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001022 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001023 return Diag(Loc, diag::err_bad_new_type)
1024 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001025 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +00001026 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001027 PDiag(diag::err_new_incomplete_type)
1028 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001029 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +00001030 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +00001031 diag::err_allocation_of_abstract_type))
1032 return true;
Douglas Gregora0750762010-10-06 16:00:31 +00001033 else if (AllocType->isVariablyModifiedType())
1034 return Diag(Loc, diag::err_variably_modified_new_type)
1035 << AllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001036
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001037 return false;
1038}
1039
Douglas Gregor6d908702010-02-26 05:06:18 +00001040/// \brief Determine whether the given function is a non-placement
1041/// deallocation function.
1042static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1043 if (FD->isInvalidDecl())
1044 return false;
1045
1046 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1047 return Method->isUsualDeallocationFunction();
1048
1049 return ((FD->getOverloadedOperator() == OO_Delete ||
1050 FD->getOverloadedOperator() == OO_Array_Delete) &&
1051 FD->getNumParams() == 1);
1052}
1053
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001054/// FindAllocationFunctions - Finds the overloads of operator new and delete
1055/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001056bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1057 bool UseGlobal, QualType AllocType,
1058 bool IsArray, Expr **PlaceArgs,
1059 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001060 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +00001061 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001062 // --- Choosing an allocation function ---
1063 // C++ 5.3.4p8 - 14 & 18
1064 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1065 // in the scope of the allocated class.
1066 // 2) If an array size is given, look for operator new[], else look for
1067 // operator new.
1068 // 3) The first argument is always size_t. Append the arguments from the
1069 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001070
1071 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
1072 // We don't care about the actual value of this argument.
1073 // FIXME: Should the Sema create the expression and embed it in the syntax
1074 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001075 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Anders Carlssond67c4c32009-08-16 20:29:29 +00001076 Context.Target.getPointerWidth(0)),
1077 Context.getSizeType(),
1078 SourceLocation());
1079 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001080 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1081
Douglas Gregor6d908702010-02-26 05:06:18 +00001082 // C++ [expr.new]p8:
1083 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001084 // function's name is operator new and the deallocation function's
Douglas Gregor6d908702010-02-26 05:06:18 +00001085 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001086 // type, the allocation function's name is operator new[] and the
1087 // deallocation function's name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001088 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1089 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001090 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1091 IsArray ? OO_Array_Delete : OO_Delete);
1092
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001093 QualType AllocElemType = Context.getBaseElementType(AllocType);
1094
1095 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001096 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001097 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001098 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001099 AllocArgs.size(), Record, /*AllowMissing=*/true,
1100 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001101 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001102 }
1103 if (!OperatorNew) {
1104 // Didn't find a member overload. Look for a global one.
1105 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001106 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001107 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001108 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1109 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001110 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001111 }
1112
John McCall9c82afc2010-04-20 02:18:25 +00001113 // We don't need an operator delete if we're running under
1114 // -fno-exceptions.
1115 if (!getLangOptions().Exceptions) {
1116 OperatorDelete = 0;
1117 return false;
1118 }
1119
Anders Carlssond9583892009-05-31 20:26:12 +00001120 // FindAllocationOverload can change the passed in arguments, so we need to
1121 // copy them back.
1122 if (NumPlaceArgs > 0)
1123 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001124
Douglas Gregor6d908702010-02-26 05:06:18 +00001125 // C++ [expr.new]p19:
1126 //
1127 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001128 // deallocation function's name is looked up in the global
Douglas Gregor6d908702010-02-26 05:06:18 +00001129 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001130 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6d908702010-02-26 05:06:18 +00001131 // the scope of T. If this lookup fails to find the name, or if
1132 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001133 // deallocation function's name is looked up in the global scope.
Douglas Gregor6d908702010-02-26 05:06:18 +00001134 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001135 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001136 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001137 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001138 LookupQualifiedName(FoundDelete, RD);
1139 }
John McCall90c8c572010-03-18 08:19:33 +00001140 if (FoundDelete.isAmbiguous())
1141 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001142
1143 if (FoundDelete.empty()) {
1144 DeclareGlobalNewDelete();
1145 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1146 }
1147
1148 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001149
1150 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1151
John McCalledeb6c92010-09-14 21:34:24 +00001152 // Whether we're looking for a placement operator delete is dictated
1153 // by whether we selected a placement operator new, not by whether
1154 // we had explicit placement arguments. This matters for things like
1155 // struct A { void *operator new(size_t, int = 0); ... };
1156 // A *a = new A()
1157 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1158
1159 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001160 // C++ [expr.new]p20:
1161 // A declaration of a placement deallocation function matches the
1162 // declaration of a placement allocation function if it has the
1163 // same number of parameters and, after parameter transformations
1164 // (8.3.5), all parameter types except the first are
1165 // identical. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001166 //
Douglas Gregor6d908702010-02-26 05:06:18 +00001167 // To perform this comparison, we compute the function type that
1168 // the deallocation function should have, and use that type both
1169 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001170 //
1171 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001172 QualType ExpectedFunctionType;
1173 {
1174 const FunctionProtoType *Proto
1175 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001176
Douglas Gregor6d908702010-02-26 05:06:18 +00001177 llvm::SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001178 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6d908702010-02-26 05:06:18 +00001179 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1180 ArgTypes.push_back(Proto->getArgType(I));
1181
John McCalle23cf432010-12-14 08:05:40 +00001182 FunctionProtoType::ExtProtoInfo EPI;
1183 EPI.Variadic = Proto->isVariadic();
1184
Douglas Gregor6d908702010-02-26 05:06:18 +00001185 ExpectedFunctionType
1186 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalle23cf432010-12-14 08:05:40 +00001187 ArgTypes.size(), EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001188 }
1189
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001190 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001191 DEnd = FoundDelete.end();
1192 D != DEnd; ++D) {
1193 FunctionDecl *Fn = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001194 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6d908702010-02-26 05:06:18 +00001195 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1196 // Perform template argument deduction to try to match the
1197 // expected function type.
1198 TemplateDeductionInfo Info(Context, StartLoc);
1199 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1200 continue;
1201 } else
1202 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1203
1204 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001205 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001206 }
1207 } else {
1208 // C++ [expr.new]p20:
1209 // [...] Any non-placement deallocation function matches a
1210 // non-placement allocation function. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001211 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001212 DEnd = FoundDelete.end();
1213 D != DEnd; ++D) {
1214 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1215 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001216 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001217 }
1218 }
1219
1220 // C++ [expr.new]p20:
1221 // [...] If the lookup finds a single matching deallocation
1222 // function, that function will be called; otherwise, no
1223 // deallocation function will be called.
1224 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001225 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001226
1227 // C++0x [expr.new]p20:
1228 // If the lookup finds the two-parameter form of a usual
1229 // deallocation function (3.7.4.2) and that function, considered
1230 // as a placement deallocation function, would have been
1231 // selected as a match for the allocation function, the program
1232 // is ill-formed.
1233 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1234 isNonPlacementDeallocationFunction(OperatorDelete)) {
1235 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001236 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001237 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1238 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1239 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001240 } else {
1241 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001242 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001243 }
1244 }
1245
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001246 return false;
1247}
1248
Sebastian Redl7f662392008-12-04 22:20:51 +00001249/// FindAllocationOverload - Find an fitting overload for the allocation
1250/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001251bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1252 DeclarationName Name, Expr** Args,
1253 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001254 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001255 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1256 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001257 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001258 if (AllowMissing)
1259 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001260 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001261 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001262 }
1263
John McCall90c8c572010-03-18 08:19:33 +00001264 if (R.isAmbiguous())
1265 return true;
1266
1267 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001268
John McCall5769d612010-02-08 23:07:23 +00001269 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001270 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001271 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001272 // Even member operator new/delete are implicitly treated as
1273 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001274 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001275
John McCall9aa472c2010-03-19 07:35:19 +00001276 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1277 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001278 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1279 Candidates,
1280 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001281 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001282 }
1283
John McCall9aa472c2010-03-19 07:35:19 +00001284 FunctionDecl *Fn = cast<FunctionDecl>(D);
1285 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001286 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001287 }
1288
1289 // Do the resolution.
1290 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001291 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001292 case OR_Success: {
1293 // Got one!
1294 FunctionDecl *FnDecl = Best->Function;
1295 // The first argument is size_t, and the first parameter must be size_t,
1296 // too. This is checked on declaration and can be assumed. (It can't be
1297 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001298 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001299 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1300 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
John McCall60d7b3a2010-08-24 06:29:42 +00001301 ExprResult Result
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001302 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001303 Context,
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001304 FnDecl->getParamDecl(i)),
1305 SourceLocation(),
John McCall3fa5cae2010-10-26 07:05:15 +00001306 Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001307 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001308 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001309
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001310 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001311 }
1312 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001313 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001314 return false;
1315 }
1316
1317 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001318 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001319 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001320 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001321 return true;
1322
1323 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001324 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001325 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001326 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001327 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001328
1329 case OR_Deleted:
1330 Diag(StartLoc, diag::err_ovl_deleted_call)
1331 << Best->Function->isDeleted()
1332 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001333 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001334 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001335 }
1336 assert(false && "Unreachable, bad result from BestViableFunction");
1337 return true;
1338}
1339
1340
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001341/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1342/// delete. These are:
1343/// @code
1344/// void* operator new(std::size_t) throw(std::bad_alloc);
1345/// void* operator new[](std::size_t) throw(std::bad_alloc);
1346/// void operator delete(void *) throw();
1347/// void operator delete[](void *) throw();
1348/// @endcode
1349/// Note that the placement and nothrow forms of new are *not* implicitly
1350/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001351void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001352 if (GlobalNewDeleteDeclared)
1353 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001354
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001355 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001356 // [...] The following allocation and deallocation functions (18.4) are
1357 // implicitly declared in global scope in each translation unit of a
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001358 // program
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001359 //
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001360 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001361 // void* operator new[](std::size_t) throw(std::bad_alloc);
1362 // void operator delete(void*) throw();
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001363 // void operator delete[](void*) throw();
1364 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001365 // These implicit declarations introduce only the function names operator
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001366 // new, operator new[], operator delete, operator delete[].
1367 //
1368 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1369 // "std" or "bad_alloc" as necessary to form the exception specification.
1370 // However, we do not make these implicit declarations visible to name
1371 // lookup.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001372 if (!StdBadAlloc) {
1373 // The "std::bad_alloc" class has not yet been declared, so build it
1374 // implicitly.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001375 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1376 getOrCreateStdNamespace(),
1377 SourceLocation(),
1378 &PP.getIdentifierTable().get("bad_alloc"),
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001379 SourceLocation(), 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001380 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001381 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001382
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001383 GlobalNewDeleteDeclared = true;
1384
1385 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1386 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001387 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001388
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001389 DeclareGlobalAllocationFunction(
1390 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001391 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001392 DeclareGlobalAllocationFunction(
1393 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001394 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001395 DeclareGlobalAllocationFunction(
1396 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1397 Context.VoidTy, VoidPtr);
1398 DeclareGlobalAllocationFunction(
1399 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1400 Context.VoidTy, VoidPtr);
1401}
1402
1403/// DeclareGlobalAllocationFunction - Declares a single implicit global
1404/// allocation function if it doesn't already exist.
1405void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001406 QualType Return, QualType Argument,
1407 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001408 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1409
1410 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001411 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001412 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001413 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001414 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001415 // Only look at non-template functions, as it is the predefined,
1416 // non-templated allocation function we are trying to declare here.
1417 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1418 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001419 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001420 Func->getParamDecl(0)->getType().getUnqualifiedType());
1421 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001422 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1423 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001424 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001425 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001426 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001427 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001428 }
1429 }
1430
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001431 QualType BadAllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001432 bool HasBadAllocExceptionSpec
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001433 = (Name.getCXXOverloadedOperator() == OO_New ||
1434 Name.getCXXOverloadedOperator() == OO_Array_New);
1435 if (HasBadAllocExceptionSpec) {
1436 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001437 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001438 }
John McCalle23cf432010-12-14 08:05:40 +00001439
1440 FunctionProtoType::ExtProtoInfo EPI;
1441 EPI.HasExceptionSpec = true;
1442 if (HasBadAllocExceptionSpec) {
1443 EPI.NumExceptions = 1;
1444 EPI.Exceptions = &BadAllocType;
1445 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001446
John McCalle23cf432010-12-14 08:05:40 +00001447 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001448 FunctionDecl *Alloc =
1449 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001450 FnType, /*TInfo=*/0, SC_None,
1451 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001452 Alloc->setImplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001453
Nuno Lopesfc284482009-12-16 16:59:22 +00001454 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001455 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001456
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001457 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001458 0, Argument, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00001459 SC_None,
1460 SC_None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001461 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001462
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001463 // FIXME: Also add this declaration to the IdentifierResolver, but
1464 // make sure it is at the end of the chain to coincide with the
1465 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001466 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001467}
1468
Anders Carlsson78f74552009-11-15 18:45:20 +00001469bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1470 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001471 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001472 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001473 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001474 LookupQualifiedName(Found, RD);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001475
John McCalla24dc2e2009-11-17 02:14:36 +00001476 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001477 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001478
Chandler Carruth23893242010-06-28 00:30:51 +00001479 Found.suppressDiagnostics();
1480
John McCall046a7462010-08-04 00:31:26 +00001481 llvm::SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001482 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1483 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001484 NamedDecl *ND = (*F)->getUnderlyingDecl();
1485
1486 // Ignore template operator delete members from the check for a usual
1487 // deallocation function.
1488 if (isa<FunctionTemplateDecl>(ND))
1489 continue;
1490
1491 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001492 Matches.push_back(F.getPair());
1493 }
1494
1495 // There's exactly one suitable operator; pick it.
1496 if (Matches.size() == 1) {
1497 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1498 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1499 Matches[0]);
1500 return false;
1501
1502 // We found multiple suitable operators; complain about the ambiguity.
1503 } else if (!Matches.empty()) {
1504 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1505 << Name << RD;
1506
1507 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1508 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1509 Diag((*F)->getUnderlyingDecl()->getLocation(),
1510 diag::note_member_declared_here) << Name;
1511 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001512 }
1513
1514 // We did find operator delete/operator delete[] declarations, but
1515 // none of them were suitable.
1516 if (!Found.empty()) {
1517 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1518 << Name << RD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001519
Anders Carlsson78f74552009-11-15 18:45:20 +00001520 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
John McCall046a7462010-08-04 00:31:26 +00001521 F != FEnd; ++F)
1522 Diag((*F)->getUnderlyingDecl()->getLocation(),
1523 diag::note_member_declared_here) << Name;
Anders Carlsson78f74552009-11-15 18:45:20 +00001524
1525 return true;
1526 }
1527
1528 // Look for a global declaration.
1529 DeclareGlobalNewDelete();
1530 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001531
Anders Carlsson78f74552009-11-15 18:45:20 +00001532 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1533 Expr* DeallocArgs[1];
1534 DeallocArgs[0] = &Null;
1535 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1536 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1537 Operator))
1538 return true;
1539
1540 assert(Operator && "Did not find a deallocation function!");
1541 return false;
1542}
1543
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001544/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1545/// @code ::delete ptr; @endcode
1546/// or
1547/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001548ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001549Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John McCall9ae2f072010-08-23 23:25:46 +00001550 bool ArrayForm, Expr *Ex) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001551 // C++ [expr.delete]p1:
1552 // The operand shall have a pointer type, or a class type having a single
1553 // conversion function to a pointer type. The result has type void.
1554 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001555 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1556
Anders Carlssond67c4c32009-08-16 20:29:29 +00001557 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001558 bool ArrayFormAsWritten = ArrayForm;
John McCall6ec278d2011-01-27 09:37:56 +00001559 bool UsualArrayDeleteWantsSize = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001560
Sebastian Redl28507842009-02-26 14:39:58 +00001561 if (!Ex->isTypeDependent()) {
1562 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001563
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001564 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001565 if (RequireCompleteType(StartLoc, Type,
Douglas Gregor254a9422010-07-29 14:44:35 +00001566 PDiag(diag::err_delete_incomplete_class_type)))
1567 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001568
John McCall32daa422010-03-31 01:36:47 +00001569 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1570
Fariborz Jahanian53462782009-09-11 21:44:33 +00001571 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001572 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001573 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001574 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001575 NamedDecl *D = I.getDecl();
1576 if (isa<UsingShadowDecl>(D))
1577 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1578
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001579 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001580 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001581 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001582
John McCall32daa422010-03-31 01:36:47 +00001583 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001584
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001585 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1586 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001587 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001588 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001589 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001590 if (ObjectPtrConversions.size() == 1) {
1591 // We have a single conversion to a pointer-to-object type. Perform
1592 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001593 // TODO: don't redo the conversion calculation.
John McCall32daa422010-03-31 01:36:47 +00001594 if (!PerformImplicitConversion(Ex,
1595 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001596 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001597 Type = Ex->getType();
1598 }
1599 }
1600 else if (ObjectPtrConversions.size() > 1) {
1601 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1602 << Type << Ex->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001603 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1604 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001605 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001606 }
Sebastian Redl28507842009-02-26 14:39:58 +00001607 }
1608
Sebastian Redlf53597f2009-03-15 17:47:39 +00001609 if (!Type->isPointerType())
1610 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1611 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001612
Ted Kremenek6217b802009-07-29 21:53:49 +00001613 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor94a61572010-05-24 17:01:56 +00001614 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001615 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregor94a61572010-05-24 17:01:56 +00001616 // effectively bans deletion of "void*". However, most compilers support
1617 // this, so we treat it as a warning unless we're in a SFINAE context.
1618 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1619 << Type << Ex->getSourceRange();
1620 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001621 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1622 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001623 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001624 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001625 PDiag(diag::warn_delete_incomplete)
1626 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001627 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001628
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001629 // C++ [expr.delete]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001630 // [Note: a pointer to a const type can be the operand of a
1631 // delete-expression; it is not necessary to cast away the constness
1632 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001633 // of the delete-expression. ]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001634 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
John McCall2de56d12010-08-25 11:45:40 +00001635 CK_NoOp);
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001636
1637 if (Pointee->isArrayType() && !ArrayForm) {
1638 Diag(StartLoc, diag::warn_delete_array_type)
1639 << Type << Ex->getSourceRange()
1640 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1641 ArrayForm = true;
1642 }
1643
Anders Carlssond67c4c32009-08-16 20:29:29 +00001644 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1645 ArrayForm ? OO_Array_Delete : OO_Delete);
1646
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001647 QualType PointeeElem = Context.getBaseElementType(Pointee);
1648 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001649 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1650
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001651 if (!UseGlobal &&
Anders Carlsson78f74552009-11-15 18:45:20 +00001652 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001653 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001654
John McCall6ec278d2011-01-27 09:37:56 +00001655 // If we're allocating an array of records, check whether the
1656 // usual operator delete[] has a size_t parameter.
1657 if (ArrayForm) {
1658 // If the user specifically asked to use the global allocator,
1659 // we'll need to do the lookup into the class.
1660 if (UseGlobal)
1661 UsualArrayDeleteWantsSize =
1662 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1663
1664 // Otherwise, the usual operator delete[] should be the
1665 // function we just found.
1666 else if (isa<CXXMethodDecl>(OperatorDelete))
1667 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1668 }
1669
Anders Carlsson78f74552009-11-15 18:45:20 +00001670 if (!RD->hasTrivialDestructor())
Douglas Gregor9b623632010-10-12 23:32:35 +00001671 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001672 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001673 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00001674 DiagnoseUseOfDecl(Dtor, StartLoc);
1675 }
Anders Carlssond67c4c32009-08-16 20:29:29 +00001676 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001677
Anders Carlssond67c4c32009-08-16 20:29:29 +00001678 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001679 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001680 DeclareGlobalNewDelete();
1681 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001682 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001683 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001684 OperatorDelete))
1685 return ExprError();
1686 }
Mike Stump1eb44332009-09-09 15:08:12 +00001687
John McCall9c82afc2010-04-20 02:18:25 +00001688 MarkDeclarationReferenced(StartLoc, OperatorDelete);
John McCall6ec278d2011-01-27 09:37:56 +00001689
Sebastian Redl28507842009-02-26 14:39:58 +00001690 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001691 }
1692
Sebastian Redlf53597f2009-03-15 17:47:39 +00001693 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall6ec278d2011-01-27 09:37:56 +00001694 ArrayFormAsWritten,
1695 UsualArrayDeleteWantsSize,
1696 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001697}
1698
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001699/// \brief Check the use of the given variable as a C++ condition in an if,
1700/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001701ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00001702 SourceLocation StmtLoc,
1703 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001704 QualType T = ConditionVar->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001705
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001706 // C++ [stmt.select]p2:
1707 // The declarator shall not specify a function or an array.
1708 if (T->isFunctionType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001709 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001710 diag::err_invalid_use_of_function_type)
1711 << ConditionVar->getSourceRange());
1712 else if (T->isArrayType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001713 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001714 diag::err_invalid_use_of_array_type)
1715 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001716
Douglas Gregor586596f2010-05-06 17:25:47 +00001717 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001718 ConditionVar->getLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00001719 ConditionVar->getType().getNonReferenceType(),
John McCall09431682010-11-18 19:01:18 +00001720 VK_LValue);
Douglas Gregorff331c12010-07-25 18:17:45 +00001721 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
Douglas Gregor586596f2010-05-06 17:25:47 +00001722 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001723
Douglas Gregor586596f2010-05-06 17:25:47 +00001724 return Owned(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001725}
1726
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001727/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1728bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1729 // C++ 6.4p4:
1730 // The value of a condition that is an initialized declaration in a statement
1731 // other than a switch statement is the value of the declared variable
1732 // implicitly converted to type bool. If that conversion is ill-formed, the
1733 // program is ill-formed.
1734 // The value of a condition that is an expression is the value of the
1735 // expression, implicitly converted to bool.
1736 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001737 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001738}
Douglas Gregor77a52232008-09-12 00:47:35 +00001739
1740/// Helper function to determine whether this is the (deprecated) C++
1741/// conversion from a string literal to a pointer to non-const char or
1742/// non-const wchar_t (for narrow and wide string literals,
1743/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001744bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001745Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1746 // Look inside the implicit cast, if it exists.
1747 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1748 From = Cast->getSubExpr();
1749
1750 // A string literal (2.13.4) that is not a wide string literal can
1751 // be converted to an rvalue of type "pointer to char"; a wide
1752 // string literal can be converted to an rvalue of type "pointer
1753 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00001754 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00001755 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001756 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001757 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001758 // This conversion is considered only when there is an
1759 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001760 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001761 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1762 (!StrLit->isWide() &&
1763 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1764 ToPointeeType->getKind() == BuiltinType::Char_S))))
1765 return true;
1766 }
1767
1768 return false;
1769}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001770
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001771static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00001772 SourceLocation CastLoc,
1773 QualType Ty,
1774 CastKind Kind,
1775 CXXMethodDecl *Method,
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001776 NamedDecl *FoundDecl,
John McCall2de56d12010-08-25 11:45:40 +00001777 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001778 switch (Kind) {
1779 default: assert(0 && "Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00001780 case CK_ConstructorConversion: {
John McCallca0408f2010-08-23 06:44:23 +00001781 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001782
Douglas Gregorba70ab62010-04-16 22:17:36 +00001783 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
John McCallf312b1e2010-08-26 23:41:50 +00001784 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00001785 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00001786 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001787
1788 ExprResult Result =
1789 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
John McCall7a1fad32010-08-24 07:32:53 +00001790 move_arg(ConstructorArgs),
Chandler Carruth428edaf2010-10-25 08:47:36 +00001791 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete,
1792 SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00001793 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00001794 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001795
Douglas Gregorba70ab62010-04-16 22:17:36 +00001796 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1797 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001798
John McCall2de56d12010-08-25 11:45:40 +00001799 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001800 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001801
Douglas Gregorba70ab62010-04-16 22:17:36 +00001802 // Create an implicit call expr that calls it.
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001803 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00001804 if (Result.isInvalid())
1805 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001806
Douglas Gregorf2ae5262011-01-20 00:18:04 +00001807 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00001808 }
1809 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001810}
Douglas Gregorba70ab62010-04-16 22:17:36 +00001811
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001812/// PerformImplicitConversion - Perform an implicit conversion of the
1813/// expression From to the type ToType using the pre-computed implicit
1814/// conversion sequence ICS. Returns true if there was an error, false
1815/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001816/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001817/// used in the error message.
1818bool
1819Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1820 const ImplicitConversionSequence &ICS,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001821 AssignmentAction Action, bool CStyle) {
John McCall1d318332010-01-12 00:44:57 +00001822 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001823 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001824 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001825 CStyle))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001826 return true;
1827 break;
1828
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001829 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001830
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001831 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00001832 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001833 QualType BeforeToType;
1834 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00001835 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001836
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001837 // If the user-defined conversion is specified by a conversion function,
1838 // the initial standard conversion sequence converts the source type to
1839 // the implicit object parameter of the conversion function.
1840 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00001841 } else {
1842 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00001843 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001844 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001845 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001846 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001847 // initial standard conversion sequence converts the source type to the
1848 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001849 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1850 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001851 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00001852 // Watch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001853 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001854 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001855 ICS.UserDefined.Before, AA_Converting,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001856 CStyle))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001857 return true;
1858 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001859
1860 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00001861 = BuildCXXCastArgument(*this,
1862 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00001863 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001864 CastKind, cast<CXXMethodDecl>(FD),
1865 ICS.UserDefined.FoundConversionFunction,
John McCall9ae2f072010-08-23 23:25:46 +00001866 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00001867
1868 if (CastArg.isInvalid())
1869 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001870
1871 From = CastArg.takeAs<Expr>();
1872
Eli Friedmand8889622009-11-27 04:41:50 +00001873 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001874 AA_Converting, CStyle);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001875 }
John McCall1d318332010-01-12 00:44:57 +00001876
1877 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00001878 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00001879 PDiag(diag::err_typecheck_ambiguous_condition)
1880 << From->getSourceRange());
1881 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001882
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001883 case ImplicitConversionSequence::EllipsisConversion:
1884 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001885 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001886
1887 case ImplicitConversionSequence::BadConversion:
1888 return true;
1889 }
1890
1891 // Everything went well.
1892 return false;
1893}
1894
1895/// PerformImplicitConversion - Perform an implicit conversion of the
1896/// expression From to the type ToType by following the standard
1897/// conversion sequence SCS. Returns true if there was an error, false
1898/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001899/// expression. Flavor is the context in which we're performing this
1900/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001901bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001902Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001903 const StandardConversionSequence& SCS,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001904 AssignmentAction Action, bool CStyle) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001905 // Overall FIXME: we are recomputing too many types here and doing far too
1906 // much extra work. What this means is that we need to keep track of more
1907 // information that is computed when we try the implicit conversion initially,
1908 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001909 QualType FromType = From->getType();
1910
Douglas Gregor225c41e2008-11-03 19:09:14 +00001911 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001912 // FIXME: When can ToType be a reference type?
1913 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001914 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00001915 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001916 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00001917 MultiExprArg(*this, &From, 1),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001918 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001919 ConstructorArgs))
1920 return true;
John McCall60d7b3a2010-08-24 06:29:42 +00001921 ExprResult FromResult =
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001922 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1923 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00001924 move_arg(ConstructorArgs),
1925 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00001926 CXXConstructExpr::CK_Complete,
1927 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001928 if (FromResult.isInvalid())
1929 return true;
1930 From = FromResult.takeAs<Expr>();
1931 return false;
1932 }
John McCall60d7b3a2010-08-24 06:29:42 +00001933 ExprResult FromResult =
Mike Stump1eb44332009-09-09 15:08:12 +00001934 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1935 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00001936 MultiExprArg(*this, &From, 1),
1937 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00001938 CXXConstructExpr::CK_Complete,
1939 SourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00001940
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001941 if (FromResult.isInvalid())
1942 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001943
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001944 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001945 return false;
1946 }
1947
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001948 // Resolve overloaded function references.
1949 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1950 DeclAccessPair Found;
1951 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1952 true, Found);
1953 if (!Fn)
1954 return true;
1955
1956 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1957 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001958
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001959 From = FixOverloadedFunctionReference(From, Found, Fn);
1960 FromType = From->getType();
1961 }
1962
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001963 // Perform the first implicit conversion.
1964 switch (SCS.First) {
1965 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001966 // Nothing to do.
1967 break;
1968
John McCallf6a16482010-12-04 03:47:34 +00001969 case ICK_Lvalue_To_Rvalue:
1970 // Should this get its own ICK?
1971 if (From->getObjectKind() == OK_ObjCProperty) {
1972 ConvertPropertyForRValue(From);
John McCall241d5582010-12-07 22:54:16 +00001973 if (!From->isGLValue()) break;
John McCallf6a16482010-12-04 03:47:34 +00001974 }
1975
1976 FromType = FromType.getUnqualifiedType();
1977 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
1978 From, 0, VK_RValue);
1979 break;
1980
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001981 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001982 FromType = Context.getArrayDecayedType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00001983 ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001984 break;
1985
1986 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001987 FromType = Context.getPointerType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00001988 ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001989 break;
1990
1991 default:
1992 assert(false && "Improper first standard conversion");
1993 break;
1994 }
1995
1996 // Perform the second implicit conversion
1997 switch (SCS.Second) {
1998 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001999 // If both sides are functions (or pointers/references to them), there could
2000 // be incompatible exception declarations.
2001 if (CheckExceptionSpecCompatibility(From, ToType))
2002 return true;
2003 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002004 break;
2005
Douglas Gregor43c79c22009-12-09 00:47:37 +00002006 case ICK_NoReturn_Adjustment:
2007 // If both sides are functions (or pointers/references to them), there could
2008 // be incompatible exception declarations.
2009 if (CheckExceptionSpecCompatibility(From, ToType))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002010 return true;
2011
John McCalle6a365d2010-12-19 02:44:49 +00002012 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor43c79c22009-12-09 00:47:37 +00002013 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002014
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002015 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002016 case ICK_Integral_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002017 ImpCastExprToType(From, ToType, CK_IntegralCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002018 break;
2019
2020 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002021 case ICK_Floating_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002022 ImpCastExprToType(From, ToType, CK_FloatingCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002023 break;
2024
2025 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00002026 case ICK_Complex_Conversion: {
2027 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2028 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2029 CastKind CK;
2030 if (FromEl->isRealFloatingType()) {
2031 if (ToEl->isRealFloatingType())
2032 CK = CK_FloatingComplexCast;
2033 else
2034 CK = CK_FloatingComplexToIntegralComplex;
2035 } else if (ToEl->isRealFloatingType()) {
2036 CK = CK_IntegralComplexToFloatingComplex;
2037 } else {
2038 CK = CK_IntegralComplexCast;
2039 }
2040 ImpCastExprToType(From, ToType, CK);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002041 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00002042 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002043
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002044 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002045 if (ToType->isRealFloatingType())
John McCall2de56d12010-08-25 11:45:40 +00002046 ImpCastExprToType(From, ToType, CK_IntegralToFloating);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002047 else
John McCall2de56d12010-08-25 11:45:40 +00002048 ImpCastExprToType(From, ToType, CK_FloatingToIntegral);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002049 break;
2050
Douglas Gregorf9201e02009-02-11 23:02:49 +00002051 case ICK_Compatible_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002052 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002053 break;
2054
Anders Carlsson61faec12009-09-12 04:46:44 +00002055 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00002056 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002057 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00002058 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00002059 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00002060 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00002061 << From->getSourceRange();
2062 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002063
John McCalldaa8e4e2010-11-15 09:13:47 +00002064 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002065 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002066 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002067 return true;
John McCall5baba9d2010-08-25 10:28:54 +00002068 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002069 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00002070 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002071
Anders Carlsson61faec12009-09-12 04:46:44 +00002072 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002073 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002074 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002075 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
Anders Carlsson61faec12009-09-12 04:46:44 +00002076 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002077 if (CheckExceptionSpecCompatibility(From, ToType))
2078 return true;
John McCall5baba9d2010-08-25 10:28:54 +00002079 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Anders Carlsson61faec12009-09-12 04:46:44 +00002080 break;
2081 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002082 case ICK_Boolean_Conversion: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002083 CastKind Kind = CK_Invalid;
2084 switch (FromType->getScalarTypeKind()) {
2085 case Type::STK_Pointer: Kind = CK_PointerToBoolean; break;
2086 case Type::STK_MemberPointer: Kind = CK_MemberPointerToBoolean; break;
2087 case Type::STK_Bool: llvm_unreachable("bool -> bool conversion?");
2088 case Type::STK_Integral: Kind = CK_IntegralToBoolean; break;
2089 case Type::STK_Floating: Kind = CK_FloatingToBoolean; break;
2090 case Type::STK_IntegralComplex: Kind = CK_IntegralComplexToBoolean; break;
2091 case Type::STK_FloatingComplex: Kind = CK_FloatingComplexToBoolean; break;
2092 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002093
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002094 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002095 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002096 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002097
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002098 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002099 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002100 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002101 ToType.getNonReferenceType(),
2102 From->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002103 From->getSourceRange(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002104 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002105 CStyle))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002106 return true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002107
Sebastian Redl906082e2010-07-20 04:20:21 +00002108 ImpCastExprToType(From, ToType.getNonReferenceType(),
John McCall2de56d12010-08-25 11:45:40 +00002109 CK_DerivedToBase, CastCategory(From),
John McCallf871d0c2010-08-07 06:22:56 +00002110 &BasePath);
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002111 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002112 }
2113
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002114 case ICK_Vector_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002115 ImpCastExprToType(From, ToType, CK_BitCast);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002116 break;
2117
2118 case ICK_Vector_Splat:
John McCall2de56d12010-08-25 11:45:40 +00002119 ImpCastExprToType(From, ToType, CK_VectorSplat);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002120 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002121
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002122 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002123 // Case 1. x -> _Complex y
2124 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2125 QualType ElType = ToComplex->getElementType();
2126 bool isFloatingComplex = ElType->isRealFloatingType();
2127
2128 // x -> y
2129 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2130 // do nothing
2131 } else if (From->getType()->isRealFloatingType()) {
2132 ImpCastExprToType(From, ElType,
2133 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral);
2134 } else {
2135 assert(From->getType()->isIntegerType());
2136 ImpCastExprToType(From, ElType,
2137 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast);
2138 }
2139 // y -> _Complex y
2140 ImpCastExprToType(From, ToType,
2141 isFloatingComplex ? CK_FloatingRealToComplex
2142 : CK_IntegralRealToComplex);
2143
2144 // Case 2. _Complex x -> y
2145 } else {
2146 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2147 assert(FromComplex);
2148
2149 QualType ElType = FromComplex->getElementType();
2150 bool isFloatingComplex = ElType->isRealFloatingType();
2151
2152 // _Complex x -> x
2153 ImpCastExprToType(From, ElType,
2154 isFloatingComplex ? CK_FloatingComplexToReal
2155 : CK_IntegralComplexToReal);
2156
2157 // x -> y
2158 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2159 // do nothing
2160 } else if (ToType->isRealFloatingType()) {
2161 ImpCastExprToType(From, ToType,
2162 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating);
2163 } else {
2164 assert(ToType->isIntegerType());
2165 ImpCastExprToType(From, ToType,
2166 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast);
2167 }
2168 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002169 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002170
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002171 case ICK_Lvalue_To_Rvalue:
2172 case ICK_Array_To_Pointer:
2173 case ICK_Function_To_Pointer:
2174 case ICK_Qualification:
2175 case ICK_Num_Conversion_Kinds:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002176 assert(false && "Improper second standard conversion");
2177 break;
2178 }
2179
2180 switch (SCS.Third) {
2181 case ICK_Identity:
2182 // Nothing to do.
2183 break;
2184
Sebastian Redl906082e2010-07-20 04:20:21 +00002185 case ICK_Qualification: {
2186 // The qualification keeps the category of the inner expression, unless the
2187 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002188 ExprValueKind VK = ToType->isReferenceType() ?
2189 CastCategory(From) : VK_RValue;
Douglas Gregor63982352010-07-13 18:40:04 +00002190 ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
John McCall2de56d12010-08-25 11:45:40 +00002191 CK_NoOp, VK);
Douglas Gregora9bff302010-02-28 18:30:25 +00002192
2193 if (SCS.DeprecatedStringLiteralToCharPtr)
2194 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2195 << ToType.getNonReferenceType();
2196
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002197 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002198 }
2199
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002200 default:
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002201 assert(false && "Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002202 break;
2203 }
2204
2205 return false;
2206}
2207
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002208ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002209 SourceLocation KWLoc,
2210 ParsedType Ty,
2211 SourceLocation RParen) {
2212 TypeSourceInfo *TSInfo;
2213 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002214
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002215 if (!TSInfo)
2216 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002217 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002218}
2219
Sebastian Redlf8aca862010-09-14 23:40:14 +00002220static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT, QualType T,
2221 SourceLocation KeyLoc) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002222 assert(!T->isDependentType() &&
2223 "Cannot evaluate traits for dependent types.");
2224 ASTContext &C = Self.Context;
2225 switch(UTT) {
2226 default: assert(false && "Unknown type trait or not implemented");
2227 case UTT_IsPOD: return T->isPODType();
2228 case UTT_IsLiteral: return T->isLiteralType();
2229 case UTT_IsClass: // Fallthrough
2230 case UTT_IsUnion:
2231 if (const RecordType *Record = T->getAs<RecordType>()) {
2232 bool Union = Record->getDecl()->isUnion();
2233 return UTT == UTT_IsUnion ? Union : !Union;
2234 }
2235 return false;
2236 case UTT_IsEnum: return T->isEnumeralType();
2237 case UTT_IsPolymorphic:
2238 if (const RecordType *Record = T->getAs<RecordType>()) {
2239 // Type traits are only parsed in C++, so we've got CXXRecords.
2240 return cast<CXXRecordDecl>(Record->getDecl())->isPolymorphic();
2241 }
2242 return false;
2243 case UTT_IsAbstract:
2244 if (const RecordType *RT = T->getAs<RecordType>())
2245 return cast<CXXRecordDecl>(RT->getDecl())->isAbstract();
2246 return false;
2247 case UTT_IsEmpty:
2248 if (const RecordType *Record = T->getAs<RecordType>()) {
2249 return !Record->getDecl()->isUnion()
2250 && cast<CXXRecordDecl>(Record->getDecl())->isEmpty();
2251 }
2252 return false;
2253 case UTT_HasTrivialConstructor:
2254 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2255 // If __is_pod (type) is true then the trait is true, else if type is
2256 // a cv class or union type (or array thereof) with a trivial default
2257 // constructor ([class.ctor]) then the trait is true, else it is false.
2258 if (T->isPODType())
2259 return true;
2260 if (const RecordType *RT =
2261 C.getBaseElementType(T)->getAs<RecordType>())
2262 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialConstructor();
2263 return false;
2264 case UTT_HasTrivialCopy:
2265 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2266 // If __is_pod (type) is true or type is a reference type then
2267 // the trait is true, else if type is a cv class or union type
2268 // with a trivial copy constructor ([class.copy]) then the trait
2269 // is true, else it is false.
2270 if (T->isPODType() || T->isReferenceType())
2271 return true;
2272 if (const RecordType *RT = T->getAs<RecordType>())
2273 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2274 return false;
2275 case UTT_HasTrivialAssign:
2276 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2277 // If type is const qualified or is a reference type then the
2278 // trait is false. Otherwise if __is_pod (type) is true then the
2279 // trait is true, else if type is a cv class or union type with
2280 // a trivial copy assignment ([class.copy]) then the trait is
2281 // true, else it is false.
2282 // Note: the const and reference restrictions are interesting,
2283 // given that const and reference members don't prevent a class
2284 // from having a trivial copy assignment operator (but do cause
2285 // errors if the copy assignment operator is actually used, q.v.
2286 // [class.copy]p12).
2287
2288 if (C.getBaseElementType(T).isConstQualified())
2289 return false;
2290 if (T->isPODType())
2291 return true;
2292 if (const RecordType *RT = T->getAs<RecordType>())
2293 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2294 return false;
2295 case UTT_HasTrivialDestructor:
2296 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2297 // If __is_pod (type) is true or type is a reference type
2298 // then the trait is true, else if type is a cv class or union
2299 // type (or array thereof) with a trivial destructor
2300 // ([class.dtor]) then the trait is true, else it is
2301 // false.
2302 if (T->isPODType() || T->isReferenceType())
2303 return true;
2304 if (const RecordType *RT =
2305 C.getBaseElementType(T)->getAs<RecordType>())
2306 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2307 return false;
2308 // TODO: Propagate nothrowness for implicitly declared special members.
2309 case UTT_HasNothrowAssign:
2310 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2311 // If type is const qualified or is a reference type then the
2312 // trait is false. Otherwise if __has_trivial_assign (type)
2313 // is true then the trait is true, else if type is a cv class
2314 // or union type with copy assignment operators that are known
2315 // not to throw an exception then the trait is true, else it is
2316 // false.
2317 if (C.getBaseElementType(T).isConstQualified())
2318 return false;
2319 if (T->isReferenceType())
2320 return false;
2321 if (T->isPODType())
2322 return true;
2323 if (const RecordType *RT = T->getAs<RecordType>()) {
2324 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2325 if (RD->hasTrivialCopyAssignment())
2326 return true;
2327
2328 bool FoundAssign = false;
2329 bool AllNoThrow = true;
2330 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00002331 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2332 Sema::LookupOrdinaryName);
2333 if (Self.LookupQualifiedName(Res, RD)) {
2334 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2335 Op != OpEnd; ++Op) {
2336 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2337 if (Operator->isCopyAssignmentOperator()) {
2338 FoundAssign = true;
2339 const FunctionProtoType *CPT
2340 = Operator->getType()->getAs<FunctionProtoType>();
2341 if (!CPT->hasEmptyExceptionSpec()) {
2342 AllNoThrow = false;
2343 break;
2344 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002345 }
2346 }
2347 }
2348
2349 return FoundAssign && AllNoThrow;
2350 }
2351 return false;
2352 case UTT_HasNothrowCopy:
2353 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2354 // If __has_trivial_copy (type) is true then the trait is true, else
2355 // if type is a cv class or union type with copy constructors that are
2356 // known not to throw an exception then the trait is true, else it is
2357 // false.
2358 if (T->isPODType() || T->isReferenceType())
2359 return true;
2360 if (const RecordType *RT = T->getAs<RecordType>()) {
2361 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2362 if (RD->hasTrivialCopyConstructor())
2363 return true;
2364
2365 bool FoundConstructor = false;
2366 bool AllNoThrow = true;
2367 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002368 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00002369 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002370 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002371 // A template constructor is never a copy constructor.
2372 // FIXME: However, it may actually be selected at the actual overload
2373 // resolution point.
2374 if (isa<FunctionTemplateDecl>(*Con))
2375 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002376 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2377 if (Constructor->isCopyConstructor(FoundTQs)) {
2378 FoundConstructor = true;
2379 const FunctionProtoType *CPT
2380 = Constructor->getType()->getAs<FunctionProtoType>();
Sebastian Redl751025d2010-09-13 22:02:47 +00002381 // TODO: check whether evaluating default arguments can throw.
2382 // For now, we'll be conservative and assume that they can throw.
2383 if (!CPT->hasEmptyExceptionSpec() || CPT->getNumArgs() > 1) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002384 AllNoThrow = false;
2385 break;
2386 }
2387 }
2388 }
2389
2390 return FoundConstructor && AllNoThrow;
2391 }
2392 return false;
2393 case UTT_HasNothrowConstructor:
2394 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2395 // If __has_trivial_constructor (type) is true then the trait is
2396 // true, else if type is a cv class or union type (or array
2397 // thereof) with a default constructor that is known not to
2398 // throw an exception then the trait is true, else it is false.
2399 if (T->isPODType())
2400 return true;
2401 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2402 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2403 if (RD->hasTrivialConstructor())
2404 return true;
2405
Sebastian Redl751025d2010-09-13 22:02:47 +00002406 DeclContext::lookup_const_iterator Con, ConEnd;
2407 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2408 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002409 // FIXME: In C++0x, a constructor template can be a default constructor.
2410 if (isa<FunctionTemplateDecl>(*Con))
2411 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00002412 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2413 if (Constructor->isDefaultConstructor()) {
2414 const FunctionProtoType *CPT
2415 = Constructor->getType()->getAs<FunctionProtoType>();
2416 // TODO: check whether evaluating default arguments can throw.
2417 // For now, we'll be conservative and assume that they can throw.
2418 return CPT->hasEmptyExceptionSpec() && CPT->getNumArgs() == 0;
2419 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002420 }
2421 }
2422 return false;
2423 case UTT_HasVirtualDestructor:
2424 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2425 // If type is a class type with a virtual destructor ([class.dtor])
2426 // then the trait is true, else it is false.
2427 if (const RecordType *Record = T->getAs<RecordType>()) {
2428 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00002429 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002430 return Destructor->isVirtual();
2431 }
2432 return false;
2433 }
2434}
2435
2436ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002437 SourceLocation KWLoc,
2438 TypeSourceInfo *TSInfo,
2439 SourceLocation RParen) {
2440 QualType T = TSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002441
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002442 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
2443 // all traits except __is_class, __is_enum and __is_union require a the type
Sebastian Redl607a1782010-09-08 00:48:43 +00002444 // to be complete, an array of unknown bound, or void.
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002445 if (UTT != UTT_IsClass && UTT != UTT_IsEnum && UTT != UTT_IsUnion) {
Sebastian Redl607a1782010-09-08 00:48:43 +00002446 QualType E = T;
2447 if (T->isIncompleteArrayType())
2448 E = Context.getAsArrayType(T)->getElementType();
2449 if (!T->isVoidType() &&
2450 RequireCompleteType(KWLoc, E,
Anders Carlssond497ba72009-08-26 22:59:12 +00002451 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002452 return ExprError();
2453 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002454
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002455 bool Value = false;
2456 if (!T->isDependentType())
Sebastian Redlf8aca862010-09-14 23:40:14 +00002457 Value = EvaluateUnaryTypeTrait(*this, UTT, T, KWLoc);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002458
2459 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002460 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00002461}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002462
Francois Pichet6ad6f282010-12-07 00:08:36 +00002463ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
2464 SourceLocation KWLoc,
2465 ParsedType LhsTy,
2466 ParsedType RhsTy,
2467 SourceLocation RParen) {
2468 TypeSourceInfo *LhsTSInfo;
2469 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
2470 if (!LhsTSInfo)
2471 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
2472
2473 TypeSourceInfo *RhsTSInfo;
2474 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
2475 if (!RhsTSInfo)
2476 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
2477
2478 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
2479}
2480
2481static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
2482 QualType LhsT, QualType RhsT,
2483 SourceLocation KeyLoc) {
2484 assert((!LhsT->isDependentType() || RhsT->isDependentType()) &&
2485 "Cannot evaluate traits for dependent types.");
2486
2487 switch(BTT) {
2488 case BTT_IsBaseOf:
2489 // C++0x [meta.rel]p2
2490 // Base is a base class of Derived without regard to cv-qualifiers or
2491 // Base and Derived are not unions and name the same class type without
2492 // regard to cv-qualifiers.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002493 if (Self.IsDerivedFrom(RhsT, LhsT) ||
Francois Pichet6ad6f282010-12-07 00:08:36 +00002494 (!LhsT->isUnionType() && !RhsT->isUnionType()
2495 && LhsT->getAsCXXRecordDecl() == RhsT->getAsCXXRecordDecl()))
2496 return true;
2497
2498 return false;
Francois Pichetf1872372010-12-08 22:35:30 +00002499 case BTT_TypeCompatible:
2500 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
2501 RhsT.getUnqualifiedType());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002502 }
2503 llvm_unreachable("Unknown type trait or not implemented");
2504}
2505
2506ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
2507 SourceLocation KWLoc,
2508 TypeSourceInfo *LhsTSInfo,
2509 TypeSourceInfo *RhsTSInfo,
2510 SourceLocation RParen) {
2511 QualType LhsT = LhsTSInfo->getType();
2512 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002513
Francois Pichet6ad6f282010-12-07 00:08:36 +00002514 if (BTT == BTT_IsBaseOf) {
2515 // C++0x [meta.rel]p2
2516 // If Base and Derived are class types and are different types
2517 // (ignoring possible cv-qualifiers) then Derived shall be a complete
2518 // type. []
2519 CXXRecordDecl *LhsDecl = LhsT->getAsCXXRecordDecl();
2520 CXXRecordDecl *RhsDecl = RhsT->getAsCXXRecordDecl();
2521 if (!LhsT->isDependentType() && !RhsT->isDependentType() &&
2522 LhsDecl && RhsDecl && LhsT != RhsT &&
2523 RequireCompleteType(KWLoc, RhsT,
2524 diag::err_incomplete_type_used_in_type_trait_expr))
2525 return ExprError();
Francois Pichetf1872372010-12-08 22:35:30 +00002526 } else if (BTT == BTT_TypeCompatible) {
2527 if (getLangOptions().CPlusPlus) {
2528 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
2529 << SourceRange(KWLoc, RParen);
2530 return ExprError();
2531 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00002532 }
2533
2534 bool Value = false;
2535 if (!LhsT->isDependentType() && !RhsT->isDependentType())
2536 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
2537
Francois Pichetf1872372010-12-08 22:35:30 +00002538 // Select trait result type.
2539 QualType ResultType;
2540 switch (BTT) {
2541 default: llvm_unreachable("Unknown type trait or not implemented");
2542 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
2543 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
2544 }
2545
Francois Pichet6ad6f282010-12-07 00:08:36 +00002546 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
2547 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00002548 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00002549}
2550
John McCallf89e55a2010-11-18 06:31:45 +00002551QualType Sema::CheckPointerToMemberOperands(Expr *&lex, Expr *&rex,
2552 ExprValueKind &VK,
2553 SourceLocation Loc,
2554 bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002555 const char *OpSpelling = isIndirect ? "->*" : ".*";
2556 // C++ 5.5p2
2557 // The binary operator .* [p3: ->*] binds its second operand, which shall
2558 // be of type "pointer to member of T" (where T is a completely-defined
2559 // class type) [...]
2560 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002561 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00002562 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002563 Diag(Loc, diag::err_bad_memptr_rhs)
2564 << OpSpelling << RType << rex->getSourceRange();
2565 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00002566 }
Douglas Gregore7450f52009-03-24 19:52:54 +00002567
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002568 QualType Class(MemPtr->getClass(), 0);
2569
Douglas Gregor7d520ba2010-10-13 20:41:14 +00002570 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
2571 // member pointer points must be completely-defined. However, there is no
2572 // reason for this semantic distinction, and the rule is not enforced by
2573 // other compilers. Therefore, we do not check this property, as it is
2574 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00002575
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002576 // C++ 5.5p2
2577 // [...] to its first operand, which shall be of class T or of a class of
2578 // which T is an unambiguous and accessible base class. [p3: a pointer to
2579 // such a class]
2580 QualType LType = lex->getType();
2581 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002582 if (const PointerType *Ptr = LType->getAs<PointerType>())
John McCallf89e55a2010-11-18 06:31:45 +00002583 LType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002584 else {
2585 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00002586 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00002587 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002588 return QualType();
2589 }
2590 }
2591
Douglas Gregora4923eb2009-11-16 21:35:15 +00002592 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00002593 // If we want to check the hierarchy, we need a complete type.
2594 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
2595 << OpSpelling << (int)isIndirect)) {
2596 return QualType();
2597 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002598 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002599 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00002600 // FIXME: Would it be useful to print full ambiguity paths, or is that
2601 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002602 if (!IsDerivedFrom(LType, Class, Paths) ||
2603 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
2604 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00002605 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002606 return QualType();
2607 }
Eli Friedman3005efe2010-01-16 00:00:48 +00002608 // Cast LHS to type of use.
2609 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
John McCall5baba9d2010-08-25 10:28:54 +00002610 ExprValueKind VK =
2611 isIndirect ? VK_RValue : CastCategory(lex);
Sebastian Redl906082e2010-07-20 04:20:21 +00002612
John McCallf871d0c2010-08-07 06:22:56 +00002613 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002614 BuildBasePathArray(Paths, BasePath);
John McCall5baba9d2010-08-25 10:28:54 +00002615 ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002616 }
2617
Douglas Gregored8abf12010-07-08 06:14:04 +00002618 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00002619 // Diagnose use of pointer-to-member type which when used as
2620 // the functional cast in a pointer-to-member expression.
2621 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2622 return QualType();
2623 }
John McCallf89e55a2010-11-18 06:31:45 +00002624
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002625 // C++ 5.5p2
2626 // The result is an object or a function of the type specified by the
2627 // second operand.
2628 // The cv qualifiers are the union of those in the pointer and the left side,
2629 // in accordance with 5.5p5 and 5.2.5.
2630 // FIXME: This returns a dereferenced member function pointer as a normal
2631 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00002632 // calling them. There's also a GCC extension to get a function pointer to the
2633 // thing, which is another complication, because this type - unlike the type
2634 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002635 // argument.
2636 // We probably need a "MemberFunctionClosureType" or something like that.
2637 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00002638 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00002639
Douglas Gregor6b4df912011-01-26 16:40:18 +00002640 // C++0x [expr.mptr.oper]p6:
2641 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002642 // ill-formed if the second operand is a pointer to member function with
2643 // ref-qualifier &. In a ->* expression or in a .* expression whose object
2644 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor6b4df912011-01-26 16:40:18 +00002645 // is a pointer to member function with ref-qualifier &&.
2646 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
2647 switch (Proto->getRefQualifier()) {
2648 case RQ_None:
2649 // Do nothing
2650 break;
2651
2652 case RQ_LValue:
2653 if (!isIndirect && !lex->Classify(Context).isLValue())
2654 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2655 << RType << 1 << lex->getSourceRange();
2656 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002657
Douglas Gregor6b4df912011-01-26 16:40:18 +00002658 case RQ_RValue:
2659 if (isIndirect || !lex->Classify(Context).isRValue())
2660 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2661 << RType << 0 << lex->getSourceRange();
2662 break;
2663 }
2664 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002665
John McCallf89e55a2010-11-18 06:31:45 +00002666 // C++ [expr.mptr.oper]p6:
2667 // The result of a .* expression whose second operand is a pointer
2668 // to a data member is of the same value category as its
2669 // first operand. The result of a .* expression whose second
2670 // operand is a pointer to a member function is a prvalue. The
2671 // result of an ->* expression is an lvalue if its second operand
2672 // is a pointer to data member and a prvalue otherwise.
2673 if (Result->isFunctionType())
2674 VK = VK_RValue;
2675 else if (isIndirect)
2676 VK = VK_LValue;
2677 else
2678 VK = lex->getValueKind();
2679
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002680 return Result;
2681}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002682
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002683/// \brief Try to convert a type to another according to C++0x 5.16p3.
2684///
2685/// This is part of the parameter validation for the ? operator. If either
2686/// value operand is a class type, the two operands are attempted to be
2687/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002688/// It returns true if the program is ill-formed and has already been diagnosed
2689/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002690static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2691 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00002692 bool &HaveConversion,
2693 QualType &ToType) {
2694 HaveConversion = false;
2695 ToType = To->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002696
2697 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00002698 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002699 // C++0x 5.16p3
2700 // The process for determining whether an operand expression E1 of type T1
2701 // can be converted to match an operand expression E2 of type T2 is defined
2702 // as follows:
2703 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00002704 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002705 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002706 // E1 can be converted to match E2 if E1 can be implicitly converted to
2707 // type "lvalue reference to T2", subject to the constraint that in the
2708 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002709 QualType T = Self.Context.getLValueReferenceType(ToType);
2710 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002711
Douglas Gregorb70cf442010-03-26 20:14:36 +00002712 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2713 if (InitSeq.isDirectReferenceBinding()) {
2714 ToType = T;
2715 HaveConversion = true;
2716 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002717 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002718
Douglas Gregorb70cf442010-03-26 20:14:36 +00002719 if (InitSeq.isAmbiguous())
2720 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002721 }
John McCallb1bdc622010-02-25 01:37:24 +00002722
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002723 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2724 // -- if E1 and E2 have class type, and the underlying class types are
2725 // the same or one is a base class of the other:
2726 QualType FTy = From->getType();
2727 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002728 const RecordType *FRec = FTy->getAs<RecordType>();
2729 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002730 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00002731 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002732 if (FRec && TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00002733 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002734 // E1 can be converted to match E2 if the class of T2 is the
2735 // same type as, or a base class of, the class of T1, and
2736 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00002737 if (FRec == TRec || FDerivedFromT) {
2738 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002739 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2740 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2741 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2742 HaveConversion = true;
2743 return false;
2744 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002745
Douglas Gregorb70cf442010-03-26 20:14:36 +00002746 if (InitSeq.isAmbiguous())
2747 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002748 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002749 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002750
Douglas Gregorb70cf442010-03-26 20:14:36 +00002751 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002752 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002753
Douglas Gregorb70cf442010-03-26 20:14:36 +00002754 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2755 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002756 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002757 // an rvalue).
2758 //
2759 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2760 // to the array-to-pointer or function-to-pointer conversions.
2761 if (!TTy->getAs<TagType>())
2762 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002763
Douglas Gregorb70cf442010-03-26 20:14:36 +00002764 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2765 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002766 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002767 ToType = TTy;
2768 if (InitSeq.isAmbiguous())
2769 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2770
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002771 return false;
2772}
2773
2774/// \brief Try to find a common type for two according to C++0x 5.16p5.
2775///
2776/// This is part of the parameter validation for the ? operator. If either
2777/// value operand is a class type, overload resolution is used to find a
2778/// conversion to a common type.
2779static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2780 SourceLocation Loc) {
2781 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00002782 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002783 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002784
2785 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00002786 switch (CandidateSet.BestViableFunction(Self, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002787 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002788 // We found a match. Perform the conversions on the arguments and move on.
2789 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002790 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002791 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002792 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002793 break;
2794 return false;
2795
Douglas Gregor20093b42009-12-09 23:02:17 +00002796 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002797 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2798 << LHS->getType() << RHS->getType()
2799 << LHS->getSourceRange() << RHS->getSourceRange();
2800 return true;
2801
Douglas Gregor20093b42009-12-09 23:02:17 +00002802 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002803 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2804 << LHS->getType() << RHS->getType()
2805 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002806 // FIXME: Print the possible common types by printing the return types of
2807 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002808 break;
2809
Douglas Gregor20093b42009-12-09 23:02:17 +00002810 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002811 assert(false && "Conditional operator has only built-in overloads");
2812 break;
2813 }
2814 return true;
2815}
2816
Sebastian Redl76458502009-04-17 16:30:52 +00002817/// \brief Perform an "extended" implicit conversion as returned by
2818/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002819static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2820 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2821 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2822 SourceLocation());
2823 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
John McCallf312b1e2010-08-26 23:41:50 +00002824 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00002825 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002826 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002827
Douglas Gregorb70cf442010-03-26 20:14:36 +00002828 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002829 return false;
2830}
2831
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002832/// \brief Check the operands of ?: under C++ semantics.
2833///
2834/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2835/// extension. In this case, LHS == Cond. (But they're not aliases.)
2836QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCallf89e55a2010-11-18 06:31:45 +00002837 Expr *&SAVE, ExprValueKind &VK,
John McCall09431682010-11-18 19:01:18 +00002838 ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002839 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002840 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2841 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002842
2843 // C++0x 5.16p1
2844 // The first expression is contextually converted to bool.
2845 if (!Cond->isTypeDependent()) {
Fariborz Jahanian1fb019b2010-09-18 19:38:38 +00002846 if (SAVE && Cond->getType()->isArrayType()) {
2847 QualType CondTy = Cond->getType();
2848 CondTy = Context.getArrayDecayedType(CondTy);
2849 ImpCastExprToType(Cond, CondTy, CK_ArrayToPointerDecay);
2850 SAVE = LHS = Cond;
2851 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002852 if (CheckCXXBooleanCondition(Cond))
2853 return QualType();
2854 }
2855
John McCallf89e55a2010-11-18 06:31:45 +00002856 // Assume r-value.
2857 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00002858 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00002859
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002860 // Either of the arguments dependent?
2861 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2862 return Context.DependentTy;
2863
2864 // C++0x 5.16p2
2865 // If either the second or the third operand has type (cv) void, ...
2866 QualType LTy = LHS->getType();
2867 QualType RTy = RHS->getType();
2868 bool LVoid = LTy->isVoidType();
2869 bool RVoid = RTy->isVoidType();
2870 if (LVoid || RVoid) {
2871 // ... then the [l2r] conversions are performed on the second and third
2872 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00002873 DefaultFunctionArrayLvalueConversion(LHS);
2874 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002875 LTy = LHS->getType();
2876 RTy = RHS->getType();
2877
2878 // ... and one of the following shall hold:
2879 // -- The second or the third operand (but not both) is a throw-
2880 // expression; the result is of the type of the other and is an rvalue.
2881 bool LThrow = isa<CXXThrowExpr>(LHS);
2882 bool RThrow = isa<CXXThrowExpr>(RHS);
2883 if (LThrow && !RThrow)
2884 return RTy;
2885 if (RThrow && !LThrow)
2886 return LTy;
2887
2888 // -- Both the second and third operands have type void; the result is of
2889 // type void and is an rvalue.
2890 if (LVoid && RVoid)
2891 return Context.VoidTy;
2892
2893 // Neither holds, error.
2894 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2895 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2896 << LHS->getSourceRange() << RHS->getSourceRange();
2897 return QualType();
2898 }
2899
2900 // Neither is void.
2901
2902 // C++0x 5.16p3
2903 // Otherwise, if the second and third operand have different types, and
2904 // either has (cv) class type, and attempt is made to convert each of those
2905 // operands to the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002906 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002907 (LTy->isRecordType() || RTy->isRecordType())) {
2908 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2909 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002910 QualType L2RType, R2LType;
2911 bool HaveL2R, HaveR2L;
2912 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002913 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002914 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002915 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002916
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002917 // If both can be converted, [...] the program is ill-formed.
2918 if (HaveL2R && HaveR2L) {
2919 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2920 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2921 return QualType();
2922 }
2923
2924 // If exactly one conversion is possible, that conversion is applied to
2925 // the chosen operand and the converted operands are used in place of the
2926 // original operands for the remainder of this section.
2927 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002928 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002929 return QualType();
2930 LTy = LHS->getType();
2931 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002932 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002933 return QualType();
2934 RTy = RHS->getType();
2935 }
2936 }
2937
2938 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00002939 // If the second and third operands are glvalues of the same value
2940 // category and have the same type, the result is of that type and
2941 // value category and it is a bit-field if the second or the third
2942 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00002943 // We only extend this to bitfields, not to the crazy other kinds of
2944 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002945 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00002946 if (Same &&
2947 LHS->getValueKind() != VK_RValue &&
2948 LHS->getValueKind() == RHS->getValueKind() &&
John McCall09431682010-11-18 19:01:18 +00002949 (LHS->getObjectKind() == OK_Ordinary ||
2950 LHS->getObjectKind() == OK_BitField) &&
2951 (RHS->getObjectKind() == OK_Ordinary ||
2952 RHS->getObjectKind() == OK_BitField)) {
John McCallf89e55a2010-11-18 06:31:45 +00002953 VK = LHS->getValueKind();
John McCall09431682010-11-18 19:01:18 +00002954 if (LHS->getObjectKind() == OK_BitField ||
2955 RHS->getObjectKind() == OK_BitField)
2956 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00002957 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00002958 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002959
2960 // C++0x 5.16p5
2961 // Otherwise, the result is an rvalue. If the second and third operands
2962 // do not have the same type, and either has (cv) class type, ...
2963 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2964 // ... overload resolution is used to determine the conversions (if any)
2965 // to be applied to the operands. If the overload resolution fails, the
2966 // program is ill-formed.
2967 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2968 return QualType();
2969 }
2970
2971 // C++0x 5.16p6
2972 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2973 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002974 DefaultFunctionArrayLvalueConversion(LHS);
2975 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002976 LTy = LHS->getType();
2977 RTy = RHS->getType();
2978
2979 // After those conversions, one of the following shall hold:
2980 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00002981 // is of that type. If the operands have class type, the result
2982 // is a prvalue temporary of the result type, which is
2983 // copy-initialized from either the second operand or the third
2984 // operand depending on the value of the first operand.
2985 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
2986 if (LTy->isRecordType()) {
2987 // The operands have class type. Make a temporary copy.
2988 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002989 ExprResult LHSCopy = PerformCopyInitialization(Entity,
2990 SourceLocation(),
John McCallf6a16482010-12-04 03:47:34 +00002991 Owned(LHS));
Douglas Gregorb65a4582010-05-19 23:40:50 +00002992 if (LHSCopy.isInvalid())
2993 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002994
2995 ExprResult RHSCopy = PerformCopyInitialization(Entity,
2996 SourceLocation(),
John McCallf6a16482010-12-04 03:47:34 +00002997 Owned(RHS));
Douglas Gregorb65a4582010-05-19 23:40:50 +00002998 if (RHSCopy.isInvalid())
2999 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003000
Douglas Gregorb65a4582010-05-19 23:40:50 +00003001 LHS = LHSCopy.takeAs<Expr>();
3002 RHS = RHSCopy.takeAs<Expr>();
3003 }
3004
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003005 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003006 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003007
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003008 // Extension: conditional operator involving vector types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003009 if (LTy->isVectorType() || RTy->isVectorType())
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003010 return CheckVectorOperands(QuestionLoc, LHS, RHS);
3011
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003012 // -- The second and third operands have arithmetic or enumeration type;
3013 // the usual arithmetic conversions are performed to bring them to a
3014 // common type, and the result is of that type.
3015 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3016 UsualArithmeticConversions(LHS, RHS);
3017 return LHS->getType();
3018 }
3019
3020 // -- The second and third operands have pointer type, or one has pointer
3021 // type and the other is a null pointer constant; pointer conversions
3022 // and qualification conversions are performed to bring them to their
3023 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00003024 // -- The second and third operands have pointer to member type, or one has
3025 // pointer to member type and the other is a null pointer constant;
3026 // pointer to member conversions and qualification conversions are
3027 // performed to bring them to a common type, whose cv-qualification
3028 // shall match the cv-qualification of either the second or the third
3029 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003030 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003031 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003032 isSFINAEContext()? 0 : &NonStandardCompositeType);
3033 if (!Composite.isNull()) {
3034 if (NonStandardCompositeType)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003035 Diag(QuestionLoc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003036 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3037 << LTy << RTy << Composite
3038 << LHS->getSourceRange() << RHS->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003039
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003040 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003041 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003042
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003043 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00003044 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3045 if (!Composite.isNull())
3046 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003047
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003048 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3049 << LHS->getType() << RHS->getType()
3050 << LHS->getSourceRange() << RHS->getSourceRange();
3051 return QualType();
3052}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003053
3054/// \brief Find a merged pointer type and convert the two expressions to it.
3055///
Douglas Gregor20b3e992009-08-24 17:42:35 +00003056/// This finds the composite pointer type (or member pointer type) for @p E1
3057/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3058/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003059/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003060///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003061/// \param Loc The location of the operator requiring these two expressions to
3062/// be converted to the composite pointer type.
3063///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003064/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3065/// a non-standard (but still sane) composite type to which both expressions
3066/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3067/// will be set true.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003068QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003069 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003070 bool *NonStandardCompositeType) {
3071 if (NonStandardCompositeType)
3072 *NonStandardCompositeType = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003073
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003074 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3075 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003076
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00003077 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3078 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00003079 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003080
3081 // C++0x 5.9p2
3082 // Pointer conversions and qualification conversions are performed on
3083 // pointer operands to bring them to their composite pointer type. If
3084 // one operand is a null pointer constant, the composite pointer type is
3085 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00003086 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003087 if (T2->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00003088 ImpCastExprToType(E1, T2, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003089 else
John McCall404cd162010-11-13 01:35:44 +00003090 ImpCastExprToType(E1, T2, CK_NullToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003091 return T2;
3092 }
Douglas Gregorce940492009-09-25 04:25:58 +00003093 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003094 if (T1->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00003095 ImpCastExprToType(E2, T1, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003096 else
John McCall404cd162010-11-13 01:35:44 +00003097 ImpCastExprToType(E2, T1, CK_NullToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003098 return T1;
3099 }
Mike Stump1eb44332009-09-09 15:08:12 +00003100
Douglas Gregor20b3e992009-08-24 17:42:35 +00003101 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003102 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3103 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003104 return QualType();
3105
3106 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3107 // the other has type "pointer to cv2 T" and the composite pointer type is
3108 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3109 // Otherwise, the composite pointer type is a pointer type similar to the
3110 // type of one of the operands, with a cv-qualification signature that is
3111 // the union of the cv-qualification signatures of the operand types.
3112 // In practice, the first part here is redundant; it's subsumed by the second.
3113 // What we do here is, we build the two possible composite types, and try the
3114 // conversions in both directions. If only one works, or if the two composite
3115 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00003116 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00003117 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
3118 QualifierVector QualifierUnion;
3119 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
3120 ContainingClassVector;
3121 ContainingClassVector MemberOfClass;
3122 QualType Composite1 = Context.getCanonicalType(T1),
3123 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003124 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00003125 do {
3126 const PointerType *Ptr1, *Ptr2;
3127 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3128 (Ptr2 = Composite2->getAs<PointerType>())) {
3129 Composite1 = Ptr1->getPointeeType();
3130 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003131
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003132 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003133 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003134 if (NonStandardCompositeType &&
3135 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3136 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003137
Douglas Gregor20b3e992009-08-24 17:42:35 +00003138 QualifierUnion.push_back(
3139 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3140 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3141 continue;
3142 }
Mike Stump1eb44332009-09-09 15:08:12 +00003143
Douglas Gregor20b3e992009-08-24 17:42:35 +00003144 const MemberPointerType *MemPtr1, *MemPtr2;
3145 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3146 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3147 Composite1 = MemPtr1->getPointeeType();
3148 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003149
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003150 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003151 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003152 if (NonStandardCompositeType &&
3153 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3154 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003155
Douglas Gregor20b3e992009-08-24 17:42:35 +00003156 QualifierUnion.push_back(
3157 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3158 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3159 MemPtr2->getClass()));
3160 continue;
3161 }
Mike Stump1eb44332009-09-09 15:08:12 +00003162
Douglas Gregor20b3e992009-08-24 17:42:35 +00003163 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00003164
Douglas Gregor20b3e992009-08-24 17:42:35 +00003165 // Cannot unwrap any more types.
3166 break;
3167 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00003168
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003169 if (NeedConstBefore && NonStandardCompositeType) {
3170 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003171 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003172 // requirements of C++ [conv.qual]p4 bullet 3.
3173 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3174 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3175 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3176 *NonStandardCompositeType = true;
3177 }
3178 }
3179 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003180
Douglas Gregor20b3e992009-08-24 17:42:35 +00003181 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003182 ContainingClassVector::reverse_iterator MOC
3183 = MemberOfClass.rbegin();
3184 for (QualifierVector::reverse_iterator
3185 I = QualifierUnion.rbegin(),
3186 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00003187 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00003188 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003189 if (MOC->first && MOC->second) {
3190 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00003191 Composite1 = Context.getMemberPointerType(
3192 Context.getQualifiedType(Composite1, Quals),
3193 MOC->first);
3194 Composite2 = Context.getMemberPointerType(
3195 Context.getQualifiedType(Composite2, Quals),
3196 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003197 } else {
3198 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00003199 Composite1
3200 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3201 Composite2
3202 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00003203 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003204 }
3205
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003206 // Try to convert to the first composite pointer type.
3207 InitializedEntity Entity1
3208 = InitializedEntity::InitializeTemporary(Composite1);
3209 InitializationKind Kind
3210 = InitializationKind::CreateCopy(Loc, SourceLocation());
3211 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3212 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00003213
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003214 if (E1ToC1 && E2ToC1) {
3215 // Conversion to Composite1 is viable.
3216 if (!Context.hasSameType(Composite1, Composite2)) {
3217 // Composite2 is a different type from Composite1. Check whether
3218 // Composite2 is also viable.
3219 InitializedEntity Entity2
3220 = InitializedEntity::InitializeTemporary(Composite2);
3221 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3222 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3223 if (E1ToC2 && E2ToC2) {
3224 // Both Composite1 and Composite2 are viable and are different;
3225 // this is an ambiguity.
3226 return QualType();
3227 }
3228 }
3229
3230 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003231 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00003232 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003233 if (E1Result.isInvalid())
3234 return QualType();
3235 E1 = E1Result.takeAs<Expr>();
3236
3237 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003238 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00003239 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003240 if (E2Result.isInvalid())
3241 return QualType();
3242 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003243
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003244 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003245 }
3246
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003247 // Check whether Composite2 is viable.
3248 InitializedEntity Entity2
3249 = InitializedEntity::InitializeTemporary(Composite2);
3250 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3251 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3252 if (!E1ToC2 || !E2ToC2)
3253 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003254
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003255 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00003256 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00003257 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003258 if (E1Result.isInvalid())
3259 return QualType();
3260 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003261
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003262 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00003263 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00003264 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003265 if (E2Result.isInvalid())
3266 return QualType();
3267 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003268
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003269 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003270}
Anders Carlsson165a0a02009-05-17 18:41:29 +00003271
John McCall60d7b3a2010-08-24 06:29:42 +00003272ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00003273 if (!E)
3274 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003275
Anders Carlsson089c2602009-08-15 23:41:35 +00003276 if (!Context.getLangOptions().CPlusPlus)
3277 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003278
Douglas Gregor51326552009-12-24 18:51:59 +00003279 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
3280
Ted Kremenek6217b802009-07-29 21:53:49 +00003281 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00003282 if (!RT)
3283 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003284
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00003285 // If this is the result of a call or an Objective-C message send expression,
3286 // our source might actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00003287 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00003288 if (CE->getCallReturnType()->isReferenceType())
Anders Carlsson283e4d52009-09-14 01:30:44 +00003289 return Owned(E);
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00003290 } else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
3291 if (const ObjCMethodDecl *MD = ME->getMethodDecl()) {
3292 if (MD->getResultType()->isReferenceType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003293 return Owned(E);
Anders Carlsson0ea4dfd2010-07-16 21:18:37 +00003294 }
Anders Carlsson283e4d52009-09-14 01:30:44 +00003295 }
John McCall86ff3082010-02-04 22:26:26 +00003296
Jeffrey Yasskinc60e13a2011-01-25 20:08:12 +00003297 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3298 if (RD->getAttr<ForbidTemporariesAttr>())
3299 Diag(E->getExprLoc(), diag::warn_temporaries_forbidden) << E->getType();
3300
John McCall86ff3082010-02-04 22:26:26 +00003301 // That should be enough to guarantee that this type is complete.
3302 // If it has a trivial destructor, we can avoid the extra copy.
John McCall507384f2010-08-12 02:40:37 +00003303 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00003304 return Owned(E);
3305
Douglas Gregordb89f282010-07-01 22:47:18 +00003306 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
Anders Carlsson860306e2009-05-30 21:21:49 +00003307 ExprTemporaries.push_back(Temp);
Douglas Gregordb89f282010-07-01 22:47:18 +00003308 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003309 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00003310 CheckDestructorAccess(E->getExprLoc(), Destructor,
3311 PDiag(diag::err_access_dtor_temp)
3312 << E->getType());
3313 }
Anders Carlssondef11992009-05-30 20:36:53 +00003314 // FIXME: Add the temporary to the temporaries vector.
3315 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
3316}
3317
John McCall4765fa02010-12-06 08:20:24 +00003318Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003319 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00003320
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003321 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3322 assert(ExprTemporaries.size() >= FirstTemporary);
3323 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003324 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003325
John McCall4765fa02010-12-06 08:20:24 +00003326 Expr *E = ExprWithCleanups::Create(Context, SubExpr,
3327 &ExprTemporaries[FirstTemporary],
3328 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003329 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
3330 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00003331
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003332 return E;
3333}
3334
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003335ExprResult
John McCall4765fa02010-12-06 08:20:24 +00003336Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00003337 if (SubExpr.isInvalid())
3338 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003339
John McCall4765fa02010-12-06 08:20:24 +00003340 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00003341}
3342
John McCall4765fa02010-12-06 08:20:24 +00003343Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003344 assert(SubStmt && "sub statement can't be null!");
3345
3346 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3347 assert(ExprTemporaries.size() >= FirstTemporary);
3348 if (ExprTemporaries.size() == FirstTemporary)
3349 return SubStmt;
3350
3351 // FIXME: In order to attach the temporaries, wrap the statement into
3352 // a StmtExpr; currently this is only used for asm statements.
3353 // This is hacky, either create a new CXXStmtWithTemporaries statement or
3354 // a new AsmStmtWithTemporaries.
3355 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
3356 SourceLocation(),
3357 SourceLocation());
3358 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
3359 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00003360 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003361}
3362
John McCall60d7b3a2010-08-24 06:29:42 +00003363ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003364Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00003365 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00003366 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003367 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003368 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003369 if (Result.isInvalid()) return ExprError();
3370 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003371
John McCall9ae2f072010-08-23 23:25:46 +00003372 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00003373 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003374 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00003375 // If we have a pointer to a dependent type and are using the -> operator,
3376 // the object type is the type that the pointer points to. We might still
3377 // have enough information about that type to do something useful.
3378 if (OpKind == tok::arrow)
3379 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3380 BaseType = Ptr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003381
John McCallb3d87482010-08-24 05:47:05 +00003382 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00003383 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00003384 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003385 }
Mike Stump1eb44332009-09-09 15:08:12 +00003386
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003387 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00003388 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003389 // returned, with the original second operand.
3390 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00003391 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00003392 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00003393 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00003394 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003395
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003396 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00003397 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
3398 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003399 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00003400 Base = Result.get();
3401 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00003402 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00003403 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00003404 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00003405 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003406 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00003407 for (unsigned i = 0; i < Locations.size(); i++)
3408 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003409 return ExprError();
3410 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003411 }
Mike Stump1eb44332009-09-09 15:08:12 +00003412
Douglas Gregor31658df2009-11-20 19:58:21 +00003413 if (BaseType->isPointerType())
3414 BaseType = BaseType->getPointeeType();
3415 }
Mike Stump1eb44332009-09-09 15:08:12 +00003416
3417 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003418 // vector types or Objective-C interfaces. Just return early and let
3419 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00003420 if (!BaseType->isRecordType()) {
3421 // C++ [basic.lookup.classref]p2:
3422 // [...] If the type of the object expression is of pointer to scalar
3423 // type, the unqualified-id is looked up in the context of the complete
3424 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00003425 //
3426 // This also indicates that we should be parsing a
3427 // pseudo-destructor-name.
John McCallb3d87482010-08-24 05:47:05 +00003428 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00003429 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00003430 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00003431 }
Mike Stump1eb44332009-09-09 15:08:12 +00003432
Douglas Gregor03c57052009-11-17 05:17:33 +00003433 // The object type must be complete (or dependent).
3434 if (!BaseType->isDependentType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003435 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor03c57052009-11-17 05:17:33 +00003436 PDiag(diag::err_incomplete_member_access)))
3437 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003438
Douglas Gregorc68afe22009-09-03 21:38:09 +00003439 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00003440 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00003441 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00003442 // type C (or of pointer to a class type C), the unqualified-id is looked
3443 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00003444 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00003445 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003446}
3447
John McCall60d7b3a2010-08-24 06:29:42 +00003448ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003449 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00003450 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00003451 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
3452 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00003453 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003454
Douglas Gregor77549082010-02-24 21:29:12 +00003455 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00003456 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00003457 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00003458 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00003459 /*RPLoc*/ ExpectedLParenLoc);
3460}
Douglas Gregord4dca082010-02-24 18:44:31 +00003461
John McCall60d7b3a2010-08-24 06:29:42 +00003462ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003463 SourceLocation OpLoc,
3464 tok::TokenKind OpKind,
3465 const CXXScopeSpec &SS,
Douglas Gregor26d4ac92010-02-24 23:40:28 +00003466 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003467 SourceLocation CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003468 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003469 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003470 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003471 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003472
Douglas Gregorb57fb492010-02-24 22:38:50 +00003473 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003474 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregorb57fb492010-02-24 22:38:50 +00003475 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003476 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00003477 QualType ObjectType = Base->getType();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003478 if (OpKind == tok::arrow) {
3479 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3480 ObjectType = Ptr->getPointeeType();
John McCall9ae2f072010-08-23 23:25:46 +00003481 } else if (!Base->isTypeDependent()) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003482 // The user wrote "p->" when she probably meant "p."; fix it.
3483 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3484 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00003485 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00003486 if (isSFINAEContext())
3487 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003488
Douglas Gregorb57fb492010-02-24 22:38:50 +00003489 OpKind = tok::period;
3490 }
3491 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003492
Douglas Gregorb57fb492010-02-24 22:38:50 +00003493 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
3494 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCall9ae2f072010-08-23 23:25:46 +00003495 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003496 return ExprError();
3497 }
3498
3499 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003500 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb57fb492010-02-24 22:38:50 +00003501 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003502 if (DestructedTypeInfo) {
3503 QualType DestructedType = DestructedTypeInfo->getType();
3504 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003505 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003506 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
3507 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
3508 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00003509 << ObjectType << DestructedType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003510 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003511
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003512 // Recover by setting the destructed type to the object type.
3513 DestructedType = ObjectType;
3514 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
3515 DestructedTypeStart);
3516 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3517 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00003518 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003519
Douglas Gregorb57fb492010-02-24 22:38:50 +00003520 // C++ [expr.pseudo]p2:
3521 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
3522 // form
3523 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003524 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb57fb492010-02-24 22:38:50 +00003525 //
3526 // shall designate the same scalar type.
3527 if (ScopeTypeInfo) {
3528 QualType ScopeType = ScopeTypeInfo->getType();
3529 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00003530 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003531
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003532 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00003533 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00003534 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003535 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003536
Douglas Gregorb57fb492010-02-24 22:38:50 +00003537 ScopeType = QualType();
3538 ScopeTypeInfo = 0;
3539 }
3540 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003541
John McCall9ae2f072010-08-23 23:25:46 +00003542 Expr *Result
3543 = new (Context) CXXPseudoDestructorExpr(Context, Base,
3544 OpKind == tok::arrow, OpLoc,
3545 SS.getScopeRep(), SS.getRange(),
3546 ScopeTypeInfo,
3547 CCLoc,
3548 TildeLoc,
3549 Destructed);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003550
Douglas Gregorb57fb492010-02-24 22:38:50 +00003551 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00003552 return Owned(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003553
John McCall9ae2f072010-08-23 23:25:46 +00003554 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00003555}
3556
John McCall60d7b3a2010-08-24 06:29:42 +00003557ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
Douglas Gregor77549082010-02-24 21:29:12 +00003558 SourceLocation OpLoc,
3559 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003560 CXXScopeSpec &SS,
Douglas Gregor77549082010-02-24 21:29:12 +00003561 UnqualifiedId &FirstTypeName,
3562 SourceLocation CCLoc,
3563 SourceLocation TildeLoc,
3564 UnqualifiedId &SecondTypeName,
3565 bool HasTrailingLParen) {
3566 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3567 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3568 "Invalid first type name in pseudo-destructor");
3569 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3570 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3571 "Invalid second type name in pseudo-destructor");
3572
Douglas Gregor77549082010-02-24 21:29:12 +00003573 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003574 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregor77549082010-02-24 21:29:12 +00003575 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003576 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00003577 QualType ObjectType = Base->getType();
Douglas Gregor77549082010-02-24 21:29:12 +00003578 if (OpKind == tok::arrow) {
3579 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3580 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003581 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00003582 // The user wrote "p->" when she probably meant "p."; fix it.
3583 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003584 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00003585 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00003586 if (isSFINAEContext())
3587 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003588
Douglas Gregor77549082010-02-24 21:29:12 +00003589 OpKind = tok::period;
3590 }
3591 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003592
3593 // Compute the object type that we should use for name lookup purposes. Only
3594 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00003595 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003596 if (!SS.isSet()) {
John McCallb3d87482010-08-24 05:47:05 +00003597 if (const Type *T = ObjectType->getAs<RecordType>())
3598 ObjectTypePtrForLookup = ParsedType::make(QualType(T, 0));
3599 else if (ObjectType->isDependentType())
3600 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003601 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003602
3603 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb57fb492010-02-24 22:38:50 +00003604 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00003605 QualType DestructedType;
3606 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003607 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00003608 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003609 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00003610 SecondTypeName.StartLocation,
3611 S, &SS, true, ObjectTypePtrForLookup);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003612 if (!T &&
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003613 ((SS.isSet() && !computeDeclContext(SS, false)) ||
3614 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003615 // The name of the type being destroyed is a dependent name, and we
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003616 // couldn't find anything useful in scope. Just store the identifier and
3617 // it's location, and we'll perform (qualified) name lookup again at
3618 // template instantiation time.
3619 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
3620 SecondTypeName.StartLocation);
3621 } else if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003622 Diag(SecondTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00003623 diag::err_pseudo_dtor_destructor_non_type)
3624 << SecondTypeName.Identifier << ObjectType;
3625 if (isSFINAEContext())
3626 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003627
Douglas Gregor77549082010-02-24 21:29:12 +00003628 // Recover by assuming we had the right type all along.
3629 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003630 } else
Douglas Gregor77549082010-02-24 21:29:12 +00003631 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003632 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003633 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003634 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003635 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3636 TemplateId->getTemplateArgs(),
3637 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003638 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003639 TemplateId->TemplateNameLoc,
3640 TemplateId->LAngleLoc,
3641 TemplateArgsPtr,
3642 TemplateId->RAngleLoc);
3643 if (T.isInvalid() || !T.get()) {
3644 // Recover by assuming we had the right type all along.
3645 DestructedType = ObjectType;
3646 } else
3647 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003648 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003649
3650 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb57fb492010-02-24 22:38:50 +00003651 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003652 if (!DestructedType.isNull()) {
3653 if (!DestructedTypeInfo)
3654 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003655 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003656 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3657 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003658
Douglas Gregorb57fb492010-02-24 22:38:50 +00003659 // Convert the name of the scope type (the type prior to '::') into a type.
3660 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00003661 QualType ScopeType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003662 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor77549082010-02-24 21:29:12 +00003663 FirstTypeName.Identifier) {
3664 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003665 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00003666 FirstTypeName.StartLocation,
3667 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00003668 if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003669 Diag(FirstTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00003670 diag::err_pseudo_dtor_destructor_non_type)
3671 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003672
Douglas Gregorb57fb492010-02-24 22:38:50 +00003673 if (isSFINAEContext())
3674 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003675
Douglas Gregorb57fb492010-02-24 22:38:50 +00003676 // Just drop this type. It's unnecessary anyway.
3677 ScopeType = QualType();
3678 } else
3679 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003680 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003681 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003682 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003683 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3684 TemplateId->getTemplateArgs(),
3685 TemplateId->NumArgs);
John McCall2b5289b2010-08-23 07:28:44 +00003686 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003687 TemplateId->TemplateNameLoc,
3688 TemplateId->LAngleLoc,
3689 TemplateArgsPtr,
3690 TemplateId->RAngleLoc);
3691 if (T.isInvalid() || !T.get()) {
3692 // Recover by dropping this type.
3693 ScopeType = QualType();
3694 } else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003695 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003696 }
3697 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003698
Douglas Gregorb4a418f2010-02-24 23:02:30 +00003699 if (!ScopeType.isNull() && !ScopeTypeInfo)
3700 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3701 FirstTypeName.StartLocation);
3702
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003703
John McCall9ae2f072010-08-23 23:25:46 +00003704 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003705 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003706 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00003707}
3708
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003709ExprResult Sema::BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
3710 CXXMethodDecl *Method) {
John McCall6bb80172010-03-30 21:47:33 +00003711 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3712 FoundDecl, Method))
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003713 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00003714
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003715 MemberExpr *ME =
Abramo Bagnara25777432010-08-11 22:01:17 +00003716 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
John McCallf89e55a2010-11-18 06:31:45 +00003717 SourceLocation(), Method->getType(),
3718 VK_RValue, OK_Ordinary);
3719 QualType ResultType = Method->getResultType();
3720 ExprValueKind VK = Expr::getValueKindForType(ResultType);
3721 ResultType = ResultType.getNonLValueExprType(Context);
3722
Douglas Gregor7edfb692009-11-23 12:27:39 +00003723 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3724 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00003725 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
Douglas Gregor7edfb692009-11-23 12:27:39 +00003726 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003727 return CE;
3728}
3729
Sebastian Redl2e156222010-09-10 20:55:43 +00003730ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
3731 SourceLocation RParen) {
Sebastian Redl2e156222010-09-10 20:55:43 +00003732 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
3733 Operand->CanThrow(Context),
3734 KeyLoc, RParen));
3735}
3736
3737ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
3738 Expr *Operand, SourceLocation RParen) {
3739 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00003740}
3741
John McCallf6a16482010-12-04 03:47:34 +00003742/// Perform the conversions required for an expression used in a
3743/// context that ignores the result.
3744void Sema::IgnoredValueConversions(Expr *&E) {
John McCalla878cda2010-12-02 02:07:15 +00003745 // C99 6.3.2.1:
3746 // [Except in specific positions,] an lvalue that does not have
3747 // array type is converted to the value stored in the
3748 // designated object (and is no longer an lvalue).
John McCallf6a16482010-12-04 03:47:34 +00003749 if (E->isRValue()) return;
John McCalla878cda2010-12-02 02:07:15 +00003750
John McCallf6a16482010-12-04 03:47:34 +00003751 // We always want to do this on ObjC property references.
3752 if (E->getObjectKind() == OK_ObjCProperty) {
3753 ConvertPropertyForRValue(E);
3754 if (E->isRValue()) return;
3755 }
3756
3757 // Otherwise, this rule does not apply in C++, at least not for the moment.
3758 if (getLangOptions().CPlusPlus) return;
3759
3760 // GCC seems to also exclude expressions of incomplete enum type.
3761 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
3762 if (!T->getDecl()->isComplete()) {
3763 // FIXME: stupid workaround for a codegen bug!
3764 ImpCastExprToType(E, Context.VoidTy, CK_ToVoid);
3765 return;
3766 }
3767 }
3768
3769 DefaultFunctionArrayLvalueConversion(E);
John McCall85515d62010-12-04 12:29:11 +00003770 if (!E->getType()->isVoidType())
3771 RequireCompleteType(E->getExprLoc(), E->getType(),
3772 diag::err_incomplete_type);
John McCallf6a16482010-12-04 03:47:34 +00003773}
3774
3775ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003776 if (!FullExpr)
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003777 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00003778
Douglas Gregord0937222010-12-13 22:49:22 +00003779 if (DiagnoseUnexpandedParameterPack(FullExpr))
3780 return ExprError();
3781
John McCallf6a16482010-12-04 03:47:34 +00003782 IgnoredValueConversions(FullExpr);
John McCallb4eb64d2010-10-08 02:01:28 +00003783 CheckImplicitConversions(FullExpr);
John McCall4765fa02010-12-06 08:20:24 +00003784 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00003785}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003786
3787StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
3788 if (!FullStmt) return StmtError();
3789
John McCall4765fa02010-12-06 08:20:24 +00003790 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003791}