blob: 5701835c1a52a903ddbf61d89131b27cd0c16b70 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall2a7fb272010-08-25 05:32:35 +000015#include "clang/Sema/DeclSpec.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/ParsedTemplate.h"
John McCall469a1eb2011-02-02 13:00:07 +000019#include "clang/Sema/ScopeInfo.h"
John McCall2a7fb272010-08-25 05:32:35 +000020#include "clang/Sema/TemplateDeduction.h"
Steve Naroff210679c2007-08-25 14:02:58 +000021#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000024#include "clang/AST/ExprCXX.h"
Fariborz Jahaniand4266622010-06-16 18:56:04 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregorb57fb492010-02-24 22:38:50 +000026#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000027#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000028#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000029#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000030#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000032using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000033
John McCallb3d87482010-08-24 05:47:05 +000034ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000035 IdentifierInfo &II,
John McCallb3d87482010-08-24 05:47:05 +000036 SourceLocation NameLoc,
37 Scope *S, CXXScopeSpec &SS,
38 ParsedType ObjectTypePtr,
39 bool EnteringContext) {
Douglas Gregor124b8782010-02-16 19:09:40 +000040 // Determine where to perform name lookup.
41
42 // FIXME: This area of the standard is very messy, and the current
43 // wording is rather unclear about which scopes we search for the
44 // destructor name; see core issues 399 and 555. Issue 399 in
45 // particular shows where the current description of destructor name
46 // lookup is completely out of line with existing practice, e.g.,
47 // this appears to be ill-formed:
48 //
49 // namespace N {
50 // template <typename T> struct S {
51 // ~S();
52 // };
53 // }
54 //
55 // void f(N::S<int>* s) {
56 // s->N::S<int>::~S();
57 // }
58 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000059 // See also PR6358 and PR6359.
Sebastian Redlc0fee502010-07-07 23:17:38 +000060 // For this reason, we're currently only doing the C++03 version of this
61 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregor124b8782010-02-16 19:09:40 +000062 QualType SearchType;
63 DeclContext *LookupCtx = 0;
64 bool isDependent = false;
65 bool LookInScope = false;
66
67 // If we have an object type, it's because we are in a
68 // pseudo-destructor-expression or a member access expression, and
69 // we know what type we're looking for.
70 if (ObjectTypePtr)
71 SearchType = GetTypeFromParser(ObjectTypePtr);
72
73 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000074 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000075
Douglas Gregor93649fd2010-02-23 00:15:22 +000076 bool AlreadySearched = false;
77 bool LookAtPrefix = true;
Sebastian Redlc0fee502010-07-07 23:17:38 +000078 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000079 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redlc0fee502010-07-07 23:17:38 +000080 // the type-names are looked up as types in the scope designated by the
81 // nested-name-specifier. In a qualified-id of the form:
NAKAMURA Takumi00995302011-01-27 07:09:49 +000082 //
83 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redlc0fee502010-07-07 23:17:38 +000084 //
85 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth5e895a82010-02-21 10:19:54 +000086 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +000087 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +000088 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregor124b8782010-02-16 19:09:40 +000089 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000090 // the class-names are looked up as types in the scope designated by
Sebastian Redlc0fee502010-07-07 23:17:38 +000091 // the nested-name-specifier.
Douglas Gregor124b8782010-02-16 19:09:40 +000092 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000093 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000094 // code below is permitted to look at the prefix of the
Sebastian Redlc0fee502010-07-07 23:17:38 +000095 // nested-name-specifier.
96 DeclContext *DC = computeDeclContext(SS, EnteringContext);
97 if (DC && DC->isFileContext()) {
98 AlreadySearched = true;
99 LookupCtx = DC;
100 isDependent = false;
101 } else if (DC && isa<CXXRecordDecl>(DC))
102 LookAtPrefix = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000103
Sebastian Redlc0fee502010-07-07 23:17:38 +0000104 // The second case from the C++03 rules quoted further above.
Douglas Gregor93649fd2010-02-23 00:15:22 +0000105 NestedNameSpecifier *Prefix = 0;
106 if (AlreadySearched) {
107 // Nothing left to do.
108 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
109 CXXScopeSpec PrefixSS;
Douglas Gregor7e384942011-02-25 16:07:42 +0000110 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor93649fd2010-02-23 00:15:22 +0000111 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
112 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000113 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000114 LookupCtx = computeDeclContext(SearchType);
115 isDependent = SearchType->isDependentType();
116 } else {
117 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000118 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000119 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000120
Douglas Gregoredc90502010-02-25 04:46:04 +0000121 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000122 } else if (ObjectTypePtr) {
123 // C++ [basic.lookup.classref]p3:
124 // If the unqualified-id is ~type-name, the type-name is looked up
125 // in the context of the entire postfix-expression. If the type T
126 // of the object expression is of a class type C, the type-name is
127 // also looked up in the scope of class C. At least one of the
128 // lookups shall find a name that refers to (possibly
129 // cv-qualified) T.
130 LookupCtx = computeDeclContext(SearchType);
131 isDependent = SearchType->isDependentType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000132 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregor124b8782010-02-16 19:09:40 +0000133 "Caller should have completed object type");
134
135 LookInScope = true;
136 } else {
137 // Perform lookup into the current scope (only).
138 LookInScope = true;
139 }
140
Douglas Gregor7ec18732011-03-04 22:32:08 +0000141 TypeDecl *NonMatchingTypeDecl = 0;
Douglas Gregor124b8782010-02-16 19:09:40 +0000142 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
143 for (unsigned Step = 0; Step != 2; ++Step) {
144 // Look for the name first in the computed lookup context (if we
Douglas Gregor7ec18732011-03-04 22:32:08 +0000145 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregor124b8782010-02-16 19:09:40 +0000146 // we're allowed to look there).
147 Found.clear();
148 if (Step == 0 && LookupCtx)
149 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000150 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000151 LookupName(Found, S);
152 else
153 continue;
154
155 // FIXME: Should we be suppressing ambiguities here?
156 if (Found.isAmbiguous())
John McCallb3d87482010-08-24 05:47:05 +0000157 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000158
159 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
160 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000161
162 if (SearchType.isNull() || SearchType->isDependentType() ||
163 Context.hasSameUnqualifiedType(T, SearchType)) {
164 // We found our type!
165
John McCallb3d87482010-08-24 05:47:05 +0000166 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000167 }
John Wiegley36784e72011-03-08 08:13:22 +0000168
Douglas Gregor7ec18732011-03-04 22:32:08 +0000169 if (!SearchType.isNull())
170 NonMatchingTypeDecl = Type;
Douglas Gregor124b8782010-02-16 19:09:40 +0000171 }
172
173 // If the name that we found is a class template name, and it is
174 // the same name as the template name in the last part of the
175 // nested-name-specifier (if present) or the object type, then
176 // this is the destructor for that class.
177 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000178 // issue 399, for which there isn't even an obvious direction.
Douglas Gregor124b8782010-02-16 19:09:40 +0000179 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
180 QualType MemberOfType;
181 if (SS.isSet()) {
182 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
183 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000184 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
185 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000186 }
187 }
188 if (MemberOfType.isNull())
189 MemberOfType = SearchType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000190
Douglas Gregor124b8782010-02-16 19:09:40 +0000191 if (MemberOfType.isNull())
192 continue;
193
194 // We're referring into a class template specialization. If the
195 // class template we found is the same as the template being
196 // specialized, we found what we are looking for.
197 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
198 if (ClassTemplateSpecializationDecl *Spec
199 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
200 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
201 Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000202 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000203 }
204
205 continue;
206 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000207
Douglas Gregor124b8782010-02-16 19:09:40 +0000208 // We're referring to an unresolved class template
209 // specialization. Determine whether we class template we found
210 // is the same as the template being specialized or, if we don't
211 // know which template is being specialized, that it at least
212 // has the same name.
213 if (const TemplateSpecializationType *SpecType
214 = MemberOfType->getAs<TemplateSpecializationType>()) {
215 TemplateName SpecName = SpecType->getTemplateName();
216
217 // The class template we found is the same template being
218 // specialized.
219 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
220 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000221 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000222
223 continue;
224 }
225
226 // The class template we found has the same name as the
227 // (dependent) template name being specialized.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000228 if (DependentTemplateName *DepTemplate
Douglas Gregor124b8782010-02-16 19:09:40 +0000229 = SpecName.getAsDependentTemplateName()) {
230 if (DepTemplate->isIdentifier() &&
231 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallb3d87482010-08-24 05:47:05 +0000232 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000233
234 continue;
235 }
236 }
237 }
238 }
239
240 if (isDependent) {
241 // We didn't find our type, but that's okay: it's dependent
242 // anyway.
Douglas Gregore29425b2011-02-28 22:42:13 +0000243
244 // FIXME: What if we have no nested-name-specifier?
245 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
246 SS.getWithLocInContext(Context),
247 II, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000248 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000249 }
250
Douglas Gregor7ec18732011-03-04 22:32:08 +0000251 if (NonMatchingTypeDecl) {
252 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
253 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
254 << T << SearchType;
255 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
256 << T;
257 } else if (ObjectTypePtr)
258 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000259 << &II;
Douglas Gregor124b8782010-02-16 19:09:40 +0000260 else
261 Diag(NameLoc, diag::err_destructor_class_name);
262
John McCallb3d87482010-08-24 05:47:05 +0000263 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000264}
265
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000266/// \brief Build a C++ typeid expression with a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000267ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000268 SourceLocation TypeidLoc,
269 TypeSourceInfo *Operand,
270 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000271 // C++ [expr.typeid]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000272 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000273 // that is the operand of typeid are always ignored.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000274 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000275 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000276 Qualifiers Quals;
277 QualType T
278 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
279 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000280 if (T->getAs<RecordType>() &&
281 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
282 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000283
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000284 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
285 Operand,
286 SourceRange(TypeidLoc, RParenLoc)));
287}
288
289/// \brief Build a C++ typeid expression with an expression operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000290ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000291 SourceLocation TypeidLoc,
292 Expr *E,
293 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000294 bool isUnevaluatedOperand = true;
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000295 if (E && !E->isTypeDependent()) {
296 QualType T = E->getType();
297 if (const RecordType *RecordT = T->getAs<RecordType>()) {
298 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
299 // C++ [expr.typeid]p3:
300 // [...] If the type of the expression is a class type, the class
301 // shall be completely-defined.
302 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
303 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000304
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000305 // C++ [expr.typeid]p3:
Sebastian Redl906082e2010-07-20 04:20:21 +0000306 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000307 // polymorphic class type [...] [the] expression is an unevaluated
308 // operand. [...]
Sebastian Redl906082e2010-07-20 04:20:21 +0000309 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000310 isUnevaluatedOperand = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000311
312 // We require a vtable to query the type at run time.
313 MarkVTableUsed(TypeidLoc, RecordD);
314 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000315 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000316
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000317 // C++ [expr.typeid]p4:
318 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000319 // cv-qualified type, the result of the typeid expression refers to a
320 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000321 // type.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000322 Qualifiers Quals;
323 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
324 if (!Context.hasSameType(T, UnqualT)) {
325 T = UnqualT;
John McCall2de56d12010-08-25 11:45:40 +0000326 ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000327 }
328 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000329
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000330 // If this is an unevaluated operand, clear out the set of
331 // declaration references we have been computing and eliminate any
332 // temporaries introduced in its computation.
333 if (isUnevaluatedOperand)
334 ExprEvalContexts.back().Context = Unevaluated;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000335
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000336 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCall9ae2f072010-08-23 23:25:46 +0000337 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000338 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000339}
340
341/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCall60d7b3a2010-08-24 06:29:42 +0000342ExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000343Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
344 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000345 // Find the std::type_info type.
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000346 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000347 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000348
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000349 if (!CXXTypeInfoDecl) {
350 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
351 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
352 LookupQualifiedName(R, getStdNamespace());
353 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
354 if (!CXXTypeInfoDecl)
355 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
356 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000357
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000358 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000359
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000360 if (isType) {
361 // The operand is a type; handle it as such.
362 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +0000363 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
364 &TInfo);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000365 if (T.isNull())
366 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000367
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000368 if (!TInfo)
369 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000370
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000371 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000372 }
Mike Stump1eb44332009-09-09 15:08:12 +0000373
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000374 // The operand is an expression.
John McCall9ae2f072010-08-23 23:25:46 +0000375 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000376}
377
Francois Pichet6915c522010-12-27 01:32:00 +0000378/// Retrieve the UuidAttr associated with QT.
379static UuidAttr *GetUuidAttrOfType(QualType QT) {
380 // Optionally remove one level of pointer, reference or array indirection.
John McCallf4c73712011-01-19 06:33:43 +0000381 const Type *Ty = QT.getTypePtr();;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000382 if (QT->isPointerType() || QT->isReferenceType())
383 Ty = QT->getPointeeType().getTypePtr();
384 else if (QT->isArrayType())
385 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
386
Francois Pichet6915c522010-12-27 01:32:00 +0000387 // Loop all class definition and declaration looking for an uuid attribute.
388 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
389 while (RD) {
390 if (UuidAttr *Uuid = RD->getAttr<UuidAttr>())
391 return Uuid;
392 RD = RD->getPreviousDeclaration();
393 }
394 return 0;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000395}
396
Francois Pichet01b7c302010-09-08 12:20:18 +0000397/// \brief Build a Microsoft __uuidof expression with a type operand.
398ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
399 SourceLocation TypeidLoc,
400 TypeSourceInfo *Operand,
401 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000402 if (!Operand->getType()->isDependentType()) {
403 if (!GetUuidAttrOfType(Operand->getType()))
404 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
405 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000406
Francois Pichet01b7c302010-09-08 12:20:18 +0000407 // FIXME: add __uuidof semantic analysis for type operand.
408 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
409 Operand,
410 SourceRange(TypeidLoc, RParenLoc)));
411}
412
413/// \brief Build a Microsoft __uuidof expression with an expression operand.
414ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
415 SourceLocation TypeidLoc,
416 Expr *E,
417 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000418 if (!E->getType()->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000419 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichet6915c522010-12-27 01:32:00 +0000420 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
421 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
422 }
423 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet01b7c302010-09-08 12:20:18 +0000424 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
425 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000426 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet01b7c302010-09-08 12:20:18 +0000427}
428
429/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
430ExprResult
431Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
432 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000433 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet01b7c302010-09-08 12:20:18 +0000434 if (!MSVCGuidDecl) {
435 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
436 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
437 LookupQualifiedName(R, Context.getTranslationUnitDecl());
438 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
439 if (!MSVCGuidDecl)
440 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000441 }
442
Francois Pichet01b7c302010-09-08 12:20:18 +0000443 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000444
Francois Pichet01b7c302010-09-08 12:20:18 +0000445 if (isType) {
446 // The operand is a type; handle it as such.
447 TypeSourceInfo *TInfo = 0;
448 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
449 &TInfo);
450 if (T.isNull())
451 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000452
Francois Pichet01b7c302010-09-08 12:20:18 +0000453 if (!TInfo)
454 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
455
456 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
457 }
458
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000459 // The operand is an expression.
Francois Pichet01b7c302010-09-08 12:20:18 +0000460 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
461}
462
Steve Naroff1b273c42007-09-16 14:56:35 +0000463/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCall60d7b3a2010-08-24 06:29:42 +0000464ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000465Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000466 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000467 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000468 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
469 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000470}
Chris Lattner50dd2892008-02-26 00:51:44 +0000471
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000472/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCall60d7b3a2010-08-24 06:29:42 +0000473ExprResult
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000474Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
475 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
476}
477
Chris Lattner50dd2892008-02-26 00:51:44 +0000478/// ActOnCXXThrow - Parse throw expressions.
John McCall60d7b3a2010-08-24 06:29:42 +0000479ExprResult
John McCall9ae2f072010-08-23 23:25:46 +0000480Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
Anders Carlsson729b8532011-02-23 03:46:46 +0000481 // Don't report an error if 'throw' is used in system headers.
Anders Carlsson15348ae2011-02-28 02:27:16 +0000482 if (!getLangOptions().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +0000483 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb1fba312011-02-19 21:53:09 +0000484 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Anders Carlsson7f11d9c2011-02-19 19:26:44 +0000485
Sebastian Redl972041f2009-04-27 20:27:31 +0000486 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
487 return ExprError();
488 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
489}
490
491/// CheckCXXThrowOperand - Validate the operand of a throw.
492bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
493 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000494 // A throw-expression initializes a temporary object, called the exception
495 // object, the type of which is determined by removing any top-level
496 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000497 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor154fe982009-12-23 22:04:40 +0000498 // or "pointer to function returning T", [...]
499 if (E->getType().hasQualifiers())
John McCall2de56d12010-08-25 11:45:40 +0000500 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Sebastian Redl906082e2010-07-20 04:20:21 +0000501 CastCategory(E));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000502
Sebastian Redl972041f2009-04-27 20:27:31 +0000503 DefaultFunctionArrayConversion(E);
504
505 // If the type of the exception would be an incomplete type or a pointer
506 // to an incomplete type other than (cv) void the program is ill-formed.
507 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000508 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000509 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000510 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000511 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000512 }
513 if (!isPointer || !Ty->isVoidType()) {
514 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000515 PDiag(isPointer ? diag::err_throw_incomplete_ptr
516 : diag::err_throw_incomplete)
517 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000518 return true;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000519
Douglas Gregorbf422f92010-04-15 18:05:39 +0000520 if (RequireNonAbstractType(ThrowLoc, E->getType(),
521 PDiag(diag::err_throw_abstract_type)
522 << E->getSourceRange()))
523 return true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000524 }
525
John McCallac418162010-04-22 01:10:34 +0000526 // Initialize the exception result. This implicitly weeds out
527 // abstract types or types with inaccessible copy constructors.
Douglas Gregor72dfa272011-01-21 22:46:35 +0000528 const VarDecl *NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
529
Douglas Gregorf5d8f462011-01-21 18:05:27 +0000530 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p32.
John McCallac418162010-04-22 01:10:34 +0000531 InitializedEntity Entity =
Douglas Gregor72dfa272011-01-21 22:46:35 +0000532 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
533 /*NRVO=*/false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000534 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregor72dfa272011-01-21 22:46:35 +0000535 QualType(), E);
John McCallac418162010-04-22 01:10:34 +0000536 if (Res.isInvalid())
537 return true;
538 E = Res.takeAs<Expr>();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000539
Eli Friedman5ed9b932010-06-03 20:39:03 +0000540 // If the exception has class type, we need additional handling.
541 const RecordType *RecordTy = Ty->getAs<RecordType>();
542 if (!RecordTy)
543 return false;
544 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
545
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000546 // If we are throwing a polymorphic class type or pointer thereof,
547 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000548 MarkVTableUsed(ThrowLoc, RD);
549
Eli Friedman98efb9f2010-10-12 20:32:36 +0000550 // If a pointer is thrown, the referenced object will not be destroyed.
551 if (isPointer)
552 return false;
553
Eli Friedman5ed9b932010-06-03 20:39:03 +0000554 // If the class has a non-trivial destructor, we must be able to call it.
555 if (RD->hasTrivialDestructor())
556 return false;
557
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000558 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +0000559 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman5ed9b932010-06-03 20:39:03 +0000560 if (!Destructor)
561 return false;
562
563 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
564 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000565 PDiag(diag::err_access_dtor_exception) << Ty);
Sebastian Redl972041f2009-04-27 20:27:31 +0000566 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000567}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000568
John McCall5808ce42011-02-03 08:15:49 +0000569CXXMethodDecl *Sema::tryCaptureCXXThis() {
570 // Ignore block scopes: we can capture through them.
571 // Ignore nested enum scopes: we'll diagnose non-constant expressions
572 // where they're invalid, and other uses are legitimate.
573 // Don't ignore nested class scopes: you can't use 'this' in a local class.
John McCall469a1eb2011-02-02 13:00:07 +0000574 DeclContext *DC = CurContext;
John McCall5808ce42011-02-03 08:15:49 +0000575 while (true) {
576 if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
577 else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
578 else break;
579 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000580
John McCall5808ce42011-02-03 08:15:49 +0000581 // If we're not in an instance method, error out.
John McCall469a1eb2011-02-02 13:00:07 +0000582 CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC);
583 if (!method || !method->isInstance())
John McCall5808ce42011-02-03 08:15:49 +0000584 return 0;
John McCall469a1eb2011-02-02 13:00:07 +0000585
586 // Mark that we're closing on 'this' in all the block scopes, if applicable.
587 for (unsigned idx = FunctionScopes.size() - 1;
588 isa<BlockScopeInfo>(FunctionScopes[idx]);
589 --idx)
590 cast<BlockScopeInfo>(FunctionScopes[idx])->CapturesCXXThis = true;
591
John McCall5808ce42011-02-03 08:15:49 +0000592 return method;
593}
594
595ExprResult Sema::ActOnCXXThis(SourceLocation loc) {
596 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
597 /// is a non-lvalue expression whose value is the address of the object for
598 /// which the function is called.
599
600 CXXMethodDecl *method = tryCaptureCXXThis();
601 if (!method) return Diag(loc, diag::err_invalid_this_use);
602
603 return Owned(new (Context) CXXThisExpr(loc, method->getThisType(Context),
John McCall469a1eb2011-02-02 13:00:07 +0000604 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000605}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000606
John McCall60d7b3a2010-08-24 06:29:42 +0000607ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000608Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000609 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000610 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000611 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000612 if (!TypeRep)
613 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000614
John McCall9d125032010-01-15 18:39:57 +0000615 TypeSourceInfo *TInfo;
616 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
617 if (!TInfo)
618 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000619
620 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
621}
622
623/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
624/// Can be interpreted either as function-style casting ("int(x)")
625/// or class type construction ("ClassType(x,y,z)")
626/// or creation of a value-initialized type ("int()").
627ExprResult
628Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
629 SourceLocation LParenLoc,
630 MultiExprArg exprs,
631 SourceLocation RParenLoc) {
632 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000633 unsigned NumExprs = exprs.size();
634 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000635 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000636 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
637
Sebastian Redlf53597f2009-03-15 17:47:39 +0000638 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000639 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000640 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000641
Douglas Gregorab6677e2010-09-08 00:15:04 +0000642 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000643 LParenLoc,
644 Exprs, NumExprs,
645 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000646 }
647
Anders Carlssonbb60a502009-08-27 03:53:50 +0000648 if (Ty->isArrayType())
649 return ExprError(Diag(TyBeginLoc,
650 diag::err_value_init_for_array_type) << FullRange);
651 if (!Ty->isVoidType() &&
652 RequireCompleteType(TyBeginLoc, Ty,
653 PDiag(diag::err_invalid_incomplete_type_use)
654 << FullRange))
655 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000656
Anders Carlssonbb60a502009-08-27 03:53:50 +0000657 if (RequireNonAbstractType(TyBeginLoc, Ty,
658 diag::err_allocation_of_abstract_type))
659 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000660
661
Douglas Gregor506ae412009-01-16 18:33:17 +0000662 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000663 // If the expression list is a single expression, the type conversion
664 // expression is equivalent (in definedness, and if defined in meaning) to the
665 // corresponding cast expression.
666 //
667 if (NumExprs == 1) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000668 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +0000669 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +0000670 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000671 if (CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
John McCallf89e55a2010-11-18 06:31:45 +0000672 Kind, VK, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000673 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000674 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000675
676 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000677
John McCallf871d0c2010-08-07 06:22:56 +0000678 return Owned(CXXFunctionalCastExpr::Create(Context,
Douglas Gregorab6677e2010-09-08 00:15:04 +0000679 Ty.getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +0000680 VK, TInfo, TyBeginLoc, Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000681 Exprs[0], &BasePath,
682 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000683 }
684
Douglas Gregor19311e72010-09-08 21:40:08 +0000685 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
686 InitializationKind Kind
687 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
688 LParenLoc, RParenLoc)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000689 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor19311e72010-09-08 21:40:08 +0000690 LParenLoc, RParenLoc);
691 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
692 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000693
Douglas Gregor19311e72010-09-08 21:40:08 +0000694 // FIXME: Improve AST representation?
695 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000696}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000697
John McCall6ec278d2011-01-27 09:37:56 +0000698/// doesUsualArrayDeleteWantSize - Answers whether the usual
699/// operator delete[] for the given type has a size_t parameter.
700static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
701 QualType allocType) {
702 const RecordType *record =
703 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
704 if (!record) return false;
705
706 // Try to find an operator delete[] in class scope.
707
708 DeclarationName deleteName =
709 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
710 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
711 S.LookupQualifiedName(ops, record->getDecl());
712
713 // We're just doing this for information.
714 ops.suppressDiagnostics();
715
716 // Very likely: there's no operator delete[].
717 if (ops.empty()) return false;
718
719 // If it's ambiguous, it should be illegal to call operator delete[]
720 // on this thing, so it doesn't matter if we allocate extra space or not.
721 if (ops.isAmbiguous()) return false;
722
723 LookupResult::Filter filter = ops.makeFilter();
724 while (filter.hasNext()) {
725 NamedDecl *del = filter.next()->getUnderlyingDecl();
726
727 // C++0x [basic.stc.dynamic.deallocation]p2:
728 // A template instance is never a usual deallocation function,
729 // regardless of its signature.
730 if (isa<FunctionTemplateDecl>(del)) {
731 filter.erase();
732 continue;
733 }
734
735 // C++0x [basic.stc.dynamic.deallocation]p2:
736 // If class T does not declare [an operator delete[] with one
737 // parameter] but does declare a member deallocation function
738 // named operator delete[] with exactly two parameters, the
739 // second of which has type std::size_t, then this function
740 // is a usual deallocation function.
741 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
742 filter.erase();
743 continue;
744 }
745 }
746 filter.done();
747
748 if (!ops.isSingleResult()) return false;
749
750 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
751 return (del->getNumParams() == 2);
752}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000753
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000754/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
755/// @code new (memory) int[size][4] @endcode
756/// or
757/// @code ::new Foo(23, "hello") @endcode
758/// For the interpretation of this heap of arguments, consult the base version.
John McCall60d7b3a2010-08-24 06:29:42 +0000759ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000760Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000761 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000762 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000763 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000764 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000765 SourceLocation ConstructorRParen) {
Richard Smith34b41d92011-02-20 03:19:35 +0000766 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
767
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000768 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000769 // If the specified type is an array, unwrap it and save the expression.
770 if (D.getNumTypeObjects() > 0 &&
771 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
772 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith34b41d92011-02-20 03:19:35 +0000773 if (TypeContainsAuto)
774 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
775 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000776 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000777 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
778 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000779 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000780 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
781 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000782
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000783 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000784 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000785 }
786
Douglas Gregor043cad22009-09-11 00:18:58 +0000787 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000788 if (ArraySize) {
789 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000790 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
791 break;
792
793 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
794 if (Expr *NumElts = (Expr *)Array.NumElts) {
795 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
796 !NumElts->isIntegerConstantExpr(Context)) {
797 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
798 << NumElts->getSourceRange();
799 return ExprError();
800 }
801 }
802 }
803 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000804
Richard Smith34b41d92011-02-20 03:19:35 +0000805 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0, /*OwnedDecl=*/0,
806 /*AllowAuto=*/true);
John McCallbf1a0282010-06-04 23:28:52 +0000807 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000808 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000809 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000810
Mike Stump1eb44332009-09-09 15:08:12 +0000811 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000812 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000813 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000814 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000815 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000816 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000817 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000818 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000819 ConstructorLParen,
820 move(ConstructorArgs),
Richard Smith34b41d92011-02-20 03:19:35 +0000821 ConstructorRParen,
822 TypeContainsAuto);
Douglas Gregor3433cf72009-05-21 00:00:09 +0000823}
824
John McCall60d7b3a2010-08-24 06:29:42 +0000825ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000826Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
827 SourceLocation PlacementLParen,
828 MultiExprArg PlacementArgs,
829 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000830 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000831 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000832 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000833 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000834 SourceLocation ConstructorLParen,
835 MultiExprArg ConstructorArgs,
Richard Smith34b41d92011-02-20 03:19:35 +0000836 SourceLocation ConstructorRParen,
837 bool TypeMayContainAuto) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000838 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000839
Richard Smith34b41d92011-02-20 03:19:35 +0000840 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
841 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
842 if (ConstructorArgs.size() == 0)
843 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
844 << AllocType << TypeRange);
845 if (ConstructorArgs.size() != 1) {
846 Expr *FirstBad = ConstructorArgs.get()[1];
847 return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
848 diag::err_auto_new_ctor_multiple_expressions)
849 << AllocType << TypeRange);
850 }
851 QualType DeducedType;
852 if (!DeduceAutoType(AllocType, ConstructorArgs.get()[0], DeducedType))
853 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
854 << AllocType
855 << ConstructorArgs.get()[0]->getType()
856 << TypeRange
857 << ConstructorArgs.get()[0]->getSourceRange());
858
859 AllocType = DeducedType;
860 AllocTypeInfo = Context.getTrivialTypeSourceInfo(AllocType, StartLoc);
861 }
862
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000863 // Per C++0x [expr.new]p5, the type being constructed may be a
864 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +0000865 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000866 if (const ConstantArrayType *Array
867 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000868 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
869 Context.getSizeType(),
870 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000871 AllocType = Array->getElementType();
872 }
873 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000874
Douglas Gregora0750762010-10-06 16:00:31 +0000875 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
876 return ExprError();
877
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000878 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000879
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000880 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
881 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000882 if (ArraySize && !ArraySize->isTypeDependent()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000883
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000884 QualType SizeType = ArraySize->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000885
John McCall60d7b3a2010-08-24 06:29:42 +0000886 ExprResult ConvertedSize
John McCall9ae2f072010-08-23 23:25:46 +0000887 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000888 PDiag(diag::err_array_size_not_integral),
889 PDiag(diag::err_array_size_incomplete_type)
890 << ArraySize->getSourceRange(),
891 PDiag(diag::err_array_size_explicit_conversion),
892 PDiag(diag::note_array_size_conversion),
893 PDiag(diag::err_array_size_ambiguous_conversion),
894 PDiag(diag::note_array_size_conversion),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000895 PDiag(getLangOptions().CPlusPlus0x? 0
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000896 : diag::ext_array_size_conversion));
897 if (ConvertedSize.isInvalid())
898 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000899
John McCall9ae2f072010-08-23 23:25:46 +0000900 ArraySize = ConvertedSize.take();
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000901 SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000902 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000903 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000904
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000905 // Let's see if this is a constant < 0. If so, we reject it out of hand.
906 // We don't care about special rules, so we tell the machinery it's not
907 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000908 if (!ArraySize->isValueDependent()) {
909 llvm::APSInt Value;
910 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
911 if (Value < llvm::APSInt(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000912 llvm::APInt::getNullValue(Value.getBitWidth()),
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000913 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000914 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000915 diag::err_typecheck_negative_array_size)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000916 << ArraySize->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000917
Douglas Gregor2767ce22010-08-18 00:39:00 +0000918 if (!AllocType->isDependentType()) {
919 unsigned ActiveSizeBits
920 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
921 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000922 Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000923 diag::err_array_too_large)
924 << Value.toString(10)
925 << ArraySize->getSourceRange();
926 return ExprError();
927 }
928 }
Douglas Gregor4bd40312010-07-13 15:54:32 +0000929 } else if (TypeIdParens.isValid()) {
930 // Can't have dynamic array size when the type-id is in parentheses.
931 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
932 << ArraySize->getSourceRange()
933 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
934 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000935
Douglas Gregor4bd40312010-07-13 15:54:32 +0000936 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +0000937 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000938 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000939
Eli Friedman73c39ab2009-10-20 08:27:19 +0000940 ImpCastExprToType(ArraySize, Context.getSizeType(),
John McCall2de56d12010-08-25 11:45:40 +0000941 CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000942 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000943
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000944 FunctionDecl *OperatorNew = 0;
945 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000946 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
947 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000948
Sebastian Redl28507842009-02-26 14:39:58 +0000949 if (!AllocType->isDependentType() &&
950 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
951 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000952 SourceRange(PlacementLParen, PlacementRParen),
953 UseGlobal, AllocType, ArraySize, PlaceArgs,
954 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000955 return ExprError();
John McCall6ec278d2011-01-27 09:37:56 +0000956
957 // If this is an array allocation, compute whether the usual array
958 // deallocation function for the type has a size_t parameter.
959 bool UsualArrayDeleteWantsSize = false;
960 if (ArraySize && !AllocType->isDependentType())
961 UsualArrayDeleteWantsSize
962 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
963
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000964 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000965 if (OperatorNew) {
966 // Add default arguments, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000967 const FunctionProtoType *Proto =
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000968 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000969 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000970 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000971
Anders Carlsson28e94832010-05-03 02:07:56 +0000972 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000973 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlsson28e94832010-05-03 02:07:56 +0000974 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000975 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000976
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000977 NumPlaceArgs = AllPlaceArgs.size();
978 if (NumPlaceArgs > 0)
979 PlaceArgs = &AllPlaceArgs[0];
980 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000981
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000982 bool Init = ConstructorLParen.isValid();
983 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000984 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000985 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
986 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +0000987 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000988
Anders Carlsson48c95012010-05-03 15:45:23 +0000989 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +0000990 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +0000991 SourceRange InitRange(ConsArgs[0]->getLocStart(),
992 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000993
Anders Carlsson48c95012010-05-03 15:45:23 +0000994 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
995 return ExprError();
996 }
997
Douglas Gregor99a2e602009-12-16 01:38:02 +0000998 if (!AllocType->isDependentType() &&
999 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
1000 // C++0x [expr.new]p15:
1001 // A new-expression that creates an object of type T initializes that
1002 // object as follows:
1003 InitializationKind Kind
1004 // - If the new-initializer is omitted, the object is default-
1005 // initialized (8.5); if no initialization is performed,
1006 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001007 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001008 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor99a2e602009-12-16 01:38:02 +00001009 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001010 : InitializationKind::CreateDirect(TypeRange.getBegin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001011 ConstructorLParen,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001012 ConstructorRParen);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001013
Douglas Gregor99a2e602009-12-16 01:38:02 +00001014 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00001015 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001016 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001017 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001018 move(ConstructorArgs));
1019 if (FullInit.isInvalid())
1020 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001021
1022 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor99a2e602009-12-16 01:38:02 +00001023 // constructor call, which CXXNewExpr handles directly.
1024 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1025 if (CXXBindTemporaryExpr *Binder
1026 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1027 FullInitExpr = Binder->getSubExpr();
1028 if (CXXConstructExpr *Construct
1029 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1030 Constructor = Construct->getConstructor();
1031 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1032 AEnd = Construct->arg_end();
1033 A != AEnd; ++A)
John McCall3fa5cae2010-10-26 07:05:15 +00001034 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001035 } else {
1036 // Take the converted initializer.
1037 ConvertedConstructorArgs.push_back(FullInit.release());
1038 }
1039 } else {
1040 // No initialization required.
1041 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001042
Douglas Gregor99a2e602009-12-16 01:38:02 +00001043 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001044 NumConsArgs = ConvertedConstructorArgs.size();
1045 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001046 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001047
Douglas Gregor6d908702010-02-26 05:06:18 +00001048 // Mark the new and delete operators as referenced.
1049 if (OperatorNew)
1050 MarkDeclarationReferenced(StartLoc, OperatorNew);
1051 if (OperatorDelete)
1052 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1053
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001054 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001055
Sebastian Redlf53597f2009-03-15 17:47:39 +00001056 PlacementArgs.release();
1057 ConstructorArgs.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001058
Ted Kremenekad7fe862010-02-11 22:51:03 +00001059 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001060 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001061 ArraySize, Constructor, Init,
1062 ConsArgs, NumConsArgs, OperatorDelete,
John McCall6ec278d2011-01-27 09:37:56 +00001063 UsualArrayDeleteWantsSize,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001064 ResultType, AllocTypeInfo,
1065 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001066 Init ? ConstructorRParen :
Chandler Carruth428edaf2010-10-25 08:47:36 +00001067 TypeRange.getEnd(),
1068 ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001069}
1070
1071/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1072/// in a new-expression.
1073/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +00001074bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00001075 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001076 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1077 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +00001078 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001079 return Diag(Loc, diag::err_bad_new_type)
1080 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001081 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001082 return Diag(Loc, diag::err_bad_new_type)
1083 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001084 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +00001085 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001086 PDiag(diag::err_new_incomplete_type)
1087 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001088 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +00001089 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +00001090 diag::err_allocation_of_abstract_type))
1091 return true;
Douglas Gregora0750762010-10-06 16:00:31 +00001092 else if (AllocType->isVariablyModifiedType())
1093 return Diag(Loc, diag::err_variably_modified_new_type)
1094 << AllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001095
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001096 return false;
1097}
1098
Douglas Gregor6d908702010-02-26 05:06:18 +00001099/// \brief Determine whether the given function is a non-placement
1100/// deallocation function.
1101static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1102 if (FD->isInvalidDecl())
1103 return false;
1104
1105 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1106 return Method->isUsualDeallocationFunction();
1107
1108 return ((FD->getOverloadedOperator() == OO_Delete ||
1109 FD->getOverloadedOperator() == OO_Array_Delete) &&
1110 FD->getNumParams() == 1);
1111}
1112
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001113/// FindAllocationFunctions - Finds the overloads of operator new and delete
1114/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001115bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1116 bool UseGlobal, QualType AllocType,
1117 bool IsArray, Expr **PlaceArgs,
1118 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001119 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +00001120 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001121 // --- Choosing an allocation function ---
1122 // C++ 5.3.4p8 - 14 & 18
1123 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1124 // in the scope of the allocated class.
1125 // 2) If an array size is given, look for operator new[], else look for
1126 // operator new.
1127 // 3) The first argument is always size_t. Append the arguments from the
1128 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001129
1130 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
1131 // We don't care about the actual value of this argument.
1132 // FIXME: Should the Sema create the expression and embed it in the syntax
1133 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001134 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Anders Carlssond67c4c32009-08-16 20:29:29 +00001135 Context.Target.getPointerWidth(0)),
1136 Context.getSizeType(),
1137 SourceLocation());
1138 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001139 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1140
Douglas Gregor6d908702010-02-26 05:06:18 +00001141 // C++ [expr.new]p8:
1142 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001143 // function's name is operator new and the deallocation function's
Douglas Gregor6d908702010-02-26 05:06:18 +00001144 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001145 // type, the allocation function's name is operator new[] and the
1146 // deallocation function's name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001147 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1148 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001149 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1150 IsArray ? OO_Array_Delete : OO_Delete);
1151
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001152 QualType AllocElemType = Context.getBaseElementType(AllocType);
1153
1154 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001155 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001156 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001157 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001158 AllocArgs.size(), Record, /*AllowMissing=*/true,
1159 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001160 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001161 }
1162 if (!OperatorNew) {
1163 // Didn't find a member overload. Look for a global one.
1164 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001165 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001166 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001167 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1168 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001169 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001170 }
1171
John McCall9c82afc2010-04-20 02:18:25 +00001172 // We don't need an operator delete if we're running under
1173 // -fno-exceptions.
1174 if (!getLangOptions().Exceptions) {
1175 OperatorDelete = 0;
1176 return false;
1177 }
1178
Anders Carlssond9583892009-05-31 20:26:12 +00001179 // FindAllocationOverload can change the passed in arguments, so we need to
1180 // copy them back.
1181 if (NumPlaceArgs > 0)
1182 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Douglas Gregor6d908702010-02-26 05:06:18 +00001184 // C++ [expr.new]p19:
1185 //
1186 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001187 // deallocation function's name is looked up in the global
Douglas Gregor6d908702010-02-26 05:06:18 +00001188 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001189 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6d908702010-02-26 05:06:18 +00001190 // the scope of T. If this lookup fails to find the name, or if
1191 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001192 // deallocation function's name is looked up in the global scope.
Douglas Gregor6d908702010-02-26 05:06:18 +00001193 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001194 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001195 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001196 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001197 LookupQualifiedName(FoundDelete, RD);
1198 }
John McCall90c8c572010-03-18 08:19:33 +00001199 if (FoundDelete.isAmbiguous())
1200 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001201
1202 if (FoundDelete.empty()) {
1203 DeclareGlobalNewDelete();
1204 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1205 }
1206
1207 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001208
1209 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1210
John McCalledeb6c92010-09-14 21:34:24 +00001211 // Whether we're looking for a placement operator delete is dictated
1212 // by whether we selected a placement operator new, not by whether
1213 // we had explicit placement arguments. This matters for things like
1214 // struct A { void *operator new(size_t, int = 0); ... };
1215 // A *a = new A()
1216 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1217
1218 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001219 // C++ [expr.new]p20:
1220 // A declaration of a placement deallocation function matches the
1221 // declaration of a placement allocation function if it has the
1222 // same number of parameters and, after parameter transformations
1223 // (8.3.5), all parameter types except the first are
1224 // identical. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001225 //
Douglas Gregor6d908702010-02-26 05:06:18 +00001226 // To perform this comparison, we compute the function type that
1227 // the deallocation function should have, and use that type both
1228 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001229 //
1230 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001231 QualType ExpectedFunctionType;
1232 {
1233 const FunctionProtoType *Proto
1234 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001235
Douglas Gregor6d908702010-02-26 05:06:18 +00001236 llvm::SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001237 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6d908702010-02-26 05:06:18 +00001238 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1239 ArgTypes.push_back(Proto->getArgType(I));
1240
John McCalle23cf432010-12-14 08:05:40 +00001241 FunctionProtoType::ExtProtoInfo EPI;
1242 EPI.Variadic = Proto->isVariadic();
1243
Douglas Gregor6d908702010-02-26 05:06:18 +00001244 ExpectedFunctionType
1245 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalle23cf432010-12-14 08:05:40 +00001246 ArgTypes.size(), EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001247 }
1248
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001249 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001250 DEnd = FoundDelete.end();
1251 D != DEnd; ++D) {
1252 FunctionDecl *Fn = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001253 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6d908702010-02-26 05:06:18 +00001254 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1255 // Perform template argument deduction to try to match the
1256 // expected function type.
1257 TemplateDeductionInfo Info(Context, StartLoc);
1258 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1259 continue;
1260 } else
1261 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1262
1263 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001264 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001265 }
1266 } else {
1267 // C++ [expr.new]p20:
1268 // [...] Any non-placement deallocation function matches a
1269 // non-placement allocation function. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001270 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001271 DEnd = FoundDelete.end();
1272 D != DEnd; ++D) {
1273 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1274 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001275 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001276 }
1277 }
1278
1279 // C++ [expr.new]p20:
1280 // [...] If the lookup finds a single matching deallocation
1281 // function, that function will be called; otherwise, no
1282 // deallocation function will be called.
1283 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001284 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001285
1286 // C++0x [expr.new]p20:
1287 // If the lookup finds the two-parameter form of a usual
1288 // deallocation function (3.7.4.2) and that function, considered
1289 // as a placement deallocation function, would have been
1290 // selected as a match for the allocation function, the program
1291 // is ill-formed.
1292 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1293 isNonPlacementDeallocationFunction(OperatorDelete)) {
1294 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001295 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001296 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1297 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1298 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001299 } else {
1300 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001301 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001302 }
1303 }
1304
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001305 return false;
1306}
1307
Sebastian Redl7f662392008-12-04 22:20:51 +00001308/// FindAllocationOverload - Find an fitting overload for the allocation
1309/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001310bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1311 DeclarationName Name, Expr** Args,
1312 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001313 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001314 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1315 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001316 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001317 if (AllowMissing)
1318 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001319 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001320 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001321 }
1322
John McCall90c8c572010-03-18 08:19:33 +00001323 if (R.isAmbiguous())
1324 return true;
1325
1326 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001327
John McCall5769d612010-02-08 23:07:23 +00001328 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001329 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001330 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001331 // Even member operator new/delete are implicitly treated as
1332 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001333 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001334
John McCall9aa472c2010-03-19 07:35:19 +00001335 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1336 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001337 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1338 Candidates,
1339 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001340 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001341 }
1342
John McCall9aa472c2010-03-19 07:35:19 +00001343 FunctionDecl *Fn = cast<FunctionDecl>(D);
1344 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001345 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001346 }
1347
1348 // Do the resolution.
1349 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001350 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001351 case OR_Success: {
1352 // Got one!
1353 FunctionDecl *FnDecl = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00001354 MarkDeclarationReferenced(StartLoc, FnDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001355 // The first argument is size_t, and the first parameter must be size_t,
1356 // too. This is checked on declaration and can be assumed. (It can't be
1357 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001358 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001359 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1360 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
John McCall60d7b3a2010-08-24 06:29:42 +00001361 ExprResult Result
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001362 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001363 Context,
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001364 FnDecl->getParamDecl(i)),
1365 SourceLocation(),
John McCall3fa5cae2010-10-26 07:05:15 +00001366 Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001367 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001368 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001369
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001370 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001371 }
1372 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001373 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001374 return false;
1375 }
1376
1377 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001378 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001379 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001380 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001381 return true;
1382
1383 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001384 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001385 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001386 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001387 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001388
1389 case OR_Deleted:
1390 Diag(StartLoc, diag::err_ovl_deleted_call)
1391 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00001392 << Name
1393 << Best->Function->getMessageUnavailableAttr(
1394 !Best->Function->isDeleted())
1395 << Range;
John McCall120d63c2010-08-24 20:38:10 +00001396 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001397 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001398 }
1399 assert(false && "Unreachable, bad result from BestViableFunction");
1400 return true;
1401}
1402
1403
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001404/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1405/// delete. These are:
1406/// @code
1407/// void* operator new(std::size_t) throw(std::bad_alloc);
1408/// void* operator new[](std::size_t) throw(std::bad_alloc);
1409/// void operator delete(void *) throw();
1410/// void operator delete[](void *) throw();
1411/// @endcode
1412/// Note that the placement and nothrow forms of new are *not* implicitly
1413/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001414void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001415 if (GlobalNewDeleteDeclared)
1416 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001417
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001418 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001419 // [...] The following allocation and deallocation functions (18.4) are
1420 // implicitly declared in global scope in each translation unit of a
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001421 // program
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001422 //
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001423 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001424 // void* operator new[](std::size_t) throw(std::bad_alloc);
1425 // void operator delete(void*) throw();
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001426 // void operator delete[](void*) throw();
1427 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001428 // These implicit declarations introduce only the function names operator
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001429 // new, operator new[], operator delete, operator delete[].
1430 //
1431 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1432 // "std" or "bad_alloc" as necessary to form the exception specification.
1433 // However, we do not make these implicit declarations visible to name
1434 // lookup.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001435 if (!StdBadAlloc) {
1436 // The "std::bad_alloc" class has not yet been declared, so build it
1437 // implicitly.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001438 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1439 getOrCreateStdNamespace(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001440 SourceLocation(), SourceLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001441 &PP.getIdentifierTable().get("bad_alloc"),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001442 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001443 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001444 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001445
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001446 GlobalNewDeleteDeclared = true;
1447
1448 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1449 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001450 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001451
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001452 DeclareGlobalAllocationFunction(
1453 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001454 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001455 DeclareGlobalAllocationFunction(
1456 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001457 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001458 DeclareGlobalAllocationFunction(
1459 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1460 Context.VoidTy, VoidPtr);
1461 DeclareGlobalAllocationFunction(
1462 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1463 Context.VoidTy, VoidPtr);
1464}
1465
1466/// DeclareGlobalAllocationFunction - Declares a single implicit global
1467/// allocation function if it doesn't already exist.
1468void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001469 QualType Return, QualType Argument,
1470 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001471 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1472
1473 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001474 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001475 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001476 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001477 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001478 // Only look at non-template functions, as it is the predefined,
1479 // non-templated allocation function we are trying to declare here.
1480 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1481 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001482 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001483 Func->getParamDecl(0)->getType().getUnqualifiedType());
1484 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001485 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1486 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001487 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001488 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001489 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001490 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001491 }
1492 }
1493
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001494 QualType BadAllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001495 bool HasBadAllocExceptionSpec
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001496 = (Name.getCXXOverloadedOperator() == OO_New ||
1497 Name.getCXXOverloadedOperator() == OO_Array_New);
1498 if (HasBadAllocExceptionSpec) {
1499 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001500 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001501 }
John McCalle23cf432010-12-14 08:05:40 +00001502
1503 FunctionProtoType::ExtProtoInfo EPI;
John McCalle23cf432010-12-14 08:05:40 +00001504 if (HasBadAllocExceptionSpec) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00001505 EPI.ExceptionSpecType = EST_Dynamic;
John McCalle23cf432010-12-14 08:05:40 +00001506 EPI.NumExceptions = 1;
1507 EPI.Exceptions = &BadAllocType;
Sebastian Redl60618fa2011-03-12 11:50:43 +00001508 } else {
1509 EPI.ExceptionSpecType = EST_DynamicNone;
John McCalle23cf432010-12-14 08:05:40 +00001510 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001511
John McCalle23cf432010-12-14 08:05:40 +00001512 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001513 FunctionDecl *Alloc =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001514 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1515 SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001516 FnType, /*TInfo=*/0, SC_None,
1517 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001518 Alloc->setImplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001519
Nuno Lopesfc284482009-12-16 16:59:22 +00001520 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001521 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001522
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001523 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001524 SourceLocation(), 0,
1525 Argument, /*TInfo=*/0,
1526 SC_None, SC_None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001527 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001528
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001529 // FIXME: Also add this declaration to the IdentifierResolver, but
1530 // make sure it is at the end of the chain to coincide with the
1531 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001532 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001533}
1534
Anders Carlsson78f74552009-11-15 18:45:20 +00001535bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1536 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001537 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001538 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001539 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001540 LookupQualifiedName(Found, RD);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001541
John McCalla24dc2e2009-11-17 02:14:36 +00001542 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001543 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001544
Chandler Carruth23893242010-06-28 00:30:51 +00001545 Found.suppressDiagnostics();
1546
John McCall046a7462010-08-04 00:31:26 +00001547 llvm::SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001548 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1549 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001550 NamedDecl *ND = (*F)->getUnderlyingDecl();
1551
1552 // Ignore template operator delete members from the check for a usual
1553 // deallocation function.
1554 if (isa<FunctionTemplateDecl>(ND))
1555 continue;
1556
1557 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001558 Matches.push_back(F.getPair());
1559 }
1560
1561 // There's exactly one suitable operator; pick it.
1562 if (Matches.size() == 1) {
1563 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1564 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1565 Matches[0]);
1566 return false;
1567
1568 // We found multiple suitable operators; complain about the ambiguity.
1569 } else if (!Matches.empty()) {
1570 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1571 << Name << RD;
1572
1573 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1574 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1575 Diag((*F)->getUnderlyingDecl()->getLocation(),
1576 diag::note_member_declared_here) << Name;
1577 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001578 }
1579
1580 // We did find operator delete/operator delete[] declarations, but
1581 // none of them were suitable.
1582 if (!Found.empty()) {
1583 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1584 << Name << RD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001585
Anders Carlsson78f74552009-11-15 18:45:20 +00001586 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
John McCall046a7462010-08-04 00:31:26 +00001587 F != FEnd; ++F)
1588 Diag((*F)->getUnderlyingDecl()->getLocation(),
1589 diag::note_member_declared_here) << Name;
Anders Carlsson78f74552009-11-15 18:45:20 +00001590
1591 return true;
1592 }
1593
1594 // Look for a global declaration.
1595 DeclareGlobalNewDelete();
1596 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001597
Anders Carlsson78f74552009-11-15 18:45:20 +00001598 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1599 Expr* DeallocArgs[1];
1600 DeallocArgs[0] = &Null;
1601 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1602 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1603 Operator))
1604 return true;
1605
1606 assert(Operator && "Did not find a deallocation function!");
1607 return false;
1608}
1609
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001610/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1611/// @code ::delete ptr; @endcode
1612/// or
1613/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001614ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001615Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John McCall9ae2f072010-08-23 23:25:46 +00001616 bool ArrayForm, Expr *Ex) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001617 // C++ [expr.delete]p1:
1618 // The operand shall have a pointer type, or a class type having a single
1619 // conversion function to a pointer type. The result has type void.
1620 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001621 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1622
Anders Carlssond67c4c32009-08-16 20:29:29 +00001623 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001624 bool ArrayFormAsWritten = ArrayForm;
John McCall6ec278d2011-01-27 09:37:56 +00001625 bool UsualArrayDeleteWantsSize = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001626
Sebastian Redl28507842009-02-26 14:39:58 +00001627 if (!Ex->isTypeDependent()) {
1628 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001629
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001630 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001631 if (RequireCompleteType(StartLoc, Type,
Douglas Gregor254a9422010-07-29 14:44:35 +00001632 PDiag(diag::err_delete_incomplete_class_type)))
1633 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001634
John McCall32daa422010-03-31 01:36:47 +00001635 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1636
Fariborz Jahanian53462782009-09-11 21:44:33 +00001637 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001638 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001639 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001640 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001641 NamedDecl *D = I.getDecl();
1642 if (isa<UsingShadowDecl>(D))
1643 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1644
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001645 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001646 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001647 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001648
John McCall32daa422010-03-31 01:36:47 +00001649 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001650
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001651 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1652 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001653 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001654 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001655 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001656 if (ObjectPtrConversions.size() == 1) {
1657 // We have a single conversion to a pointer-to-object type. Perform
1658 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001659 // TODO: don't redo the conversion calculation.
John McCall32daa422010-03-31 01:36:47 +00001660 if (!PerformImplicitConversion(Ex,
1661 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001662 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001663 Type = Ex->getType();
1664 }
1665 }
1666 else if (ObjectPtrConversions.size() > 1) {
1667 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1668 << Type << Ex->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001669 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1670 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001671 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001672 }
Sebastian Redl28507842009-02-26 14:39:58 +00001673 }
1674
Sebastian Redlf53597f2009-03-15 17:47:39 +00001675 if (!Type->isPointerType())
1676 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1677 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001678
Ted Kremenek6217b802009-07-29 21:53:49 +00001679 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor94a61572010-05-24 17:01:56 +00001680 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001681 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregor94a61572010-05-24 17:01:56 +00001682 // effectively bans deletion of "void*". However, most compilers support
1683 // this, so we treat it as a warning unless we're in a SFINAE context.
1684 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1685 << Type << Ex->getSourceRange();
1686 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001687 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1688 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001689 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001690 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001691 PDiag(diag::warn_delete_incomplete)
1692 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001693 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001694
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001695 // C++ [expr.delete]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001696 // [Note: a pointer to a const type can be the operand of a
1697 // delete-expression; it is not necessary to cast away the constness
1698 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001699 // of the delete-expression. ]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001700 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
John McCall2de56d12010-08-25 11:45:40 +00001701 CK_NoOp);
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001702
1703 if (Pointee->isArrayType() && !ArrayForm) {
1704 Diag(StartLoc, diag::warn_delete_array_type)
1705 << Type << Ex->getSourceRange()
1706 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1707 ArrayForm = true;
1708 }
1709
Anders Carlssond67c4c32009-08-16 20:29:29 +00001710 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1711 ArrayForm ? OO_Array_Delete : OO_Delete);
1712
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001713 QualType PointeeElem = Context.getBaseElementType(Pointee);
1714 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001715 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1716
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001717 if (!UseGlobal &&
Anders Carlsson78f74552009-11-15 18:45:20 +00001718 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001719 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001720
John McCall6ec278d2011-01-27 09:37:56 +00001721 // If we're allocating an array of records, check whether the
1722 // usual operator delete[] has a size_t parameter.
1723 if (ArrayForm) {
1724 // If the user specifically asked to use the global allocator,
1725 // we'll need to do the lookup into the class.
1726 if (UseGlobal)
1727 UsualArrayDeleteWantsSize =
1728 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1729
1730 // Otherwise, the usual operator delete[] should be the
1731 // function we just found.
1732 else if (isa<CXXMethodDecl>(OperatorDelete))
1733 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1734 }
1735
Anders Carlsson78f74552009-11-15 18:45:20 +00001736 if (!RD->hasTrivialDestructor())
Douglas Gregor9b623632010-10-12 23:32:35 +00001737 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001738 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001739 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00001740 DiagnoseUseOfDecl(Dtor, StartLoc);
1741 }
Anders Carlssond67c4c32009-08-16 20:29:29 +00001742 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001743
Anders Carlssond67c4c32009-08-16 20:29:29 +00001744 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001745 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001746 DeclareGlobalNewDelete();
1747 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001748 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001749 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001750 OperatorDelete))
1751 return ExprError();
1752 }
Mike Stump1eb44332009-09-09 15:08:12 +00001753
John McCall9c82afc2010-04-20 02:18:25 +00001754 MarkDeclarationReferenced(StartLoc, OperatorDelete);
John McCall6ec278d2011-01-27 09:37:56 +00001755
Douglas Gregord880f522011-02-01 15:50:11 +00001756 // Check access and ambiguity of operator delete and destructor.
1757 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1758 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1759 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
1760 CheckDestructorAccess(Ex->getExprLoc(), Dtor,
1761 PDiag(diag::err_access_dtor) << PointeeElem);
1762 }
1763 }
1764
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001765 }
1766
Sebastian Redlf53597f2009-03-15 17:47:39 +00001767 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall6ec278d2011-01-27 09:37:56 +00001768 ArrayFormAsWritten,
1769 UsualArrayDeleteWantsSize,
1770 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001771}
1772
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001773/// \brief Check the use of the given variable as a C++ condition in an if,
1774/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001775ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00001776 SourceLocation StmtLoc,
1777 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001778 QualType T = ConditionVar->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001779
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001780 // C++ [stmt.select]p2:
1781 // The declarator shall not specify a function or an array.
1782 if (T->isFunctionType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001783 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001784 diag::err_invalid_use_of_function_type)
1785 << ConditionVar->getSourceRange());
1786 else if (T->isArrayType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001787 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001788 diag::err_invalid_use_of_array_type)
1789 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001790
Douglas Gregor40d96a62011-02-28 21:54:11 +00001791 Expr *Condition = DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1792 ConditionVar,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001793 ConditionVar->getLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00001794 ConditionVar->getType().getNonReferenceType(),
John McCall09431682010-11-18 19:01:18 +00001795 VK_LValue);
Douglas Gregorff331c12010-07-25 18:17:45 +00001796 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
Douglas Gregor586596f2010-05-06 17:25:47 +00001797 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001798
Douglas Gregor586596f2010-05-06 17:25:47 +00001799 return Owned(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001800}
1801
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001802/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1803bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1804 // C++ 6.4p4:
1805 // The value of a condition that is an initialized declaration in a statement
1806 // other than a switch statement is the value of the declared variable
1807 // implicitly converted to type bool. If that conversion is ill-formed, the
1808 // program is ill-formed.
1809 // The value of a condition that is an expression is the value of the
1810 // expression, implicitly converted to bool.
1811 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001812 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001813}
Douglas Gregor77a52232008-09-12 00:47:35 +00001814
1815/// Helper function to determine whether this is the (deprecated) C++
1816/// conversion from a string literal to a pointer to non-const char or
1817/// non-const wchar_t (for narrow and wide string literals,
1818/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001819bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001820Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1821 // Look inside the implicit cast, if it exists.
1822 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1823 From = Cast->getSubExpr();
1824
1825 // A string literal (2.13.4) that is not a wide string literal can
1826 // be converted to an rvalue of type "pointer to char"; a wide
1827 // string literal can be converted to an rvalue of type "pointer
1828 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00001829 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00001830 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001831 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001832 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001833 // This conversion is considered only when there is an
1834 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001835 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001836 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1837 (!StrLit->isWide() &&
1838 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1839 ToPointeeType->getKind() == BuiltinType::Char_S))))
1840 return true;
1841 }
1842
1843 return false;
1844}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001845
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001846static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00001847 SourceLocation CastLoc,
1848 QualType Ty,
1849 CastKind Kind,
1850 CXXMethodDecl *Method,
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001851 NamedDecl *FoundDecl,
John McCall2de56d12010-08-25 11:45:40 +00001852 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001853 switch (Kind) {
1854 default: assert(0 && "Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00001855 case CK_ConstructorConversion: {
John McCallca0408f2010-08-23 06:44:23 +00001856 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001857
Douglas Gregorba70ab62010-04-16 22:17:36 +00001858 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
John McCallf312b1e2010-08-26 23:41:50 +00001859 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00001860 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00001861 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001862
1863 ExprResult Result =
1864 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
John McCall7a1fad32010-08-24 07:32:53 +00001865 move_arg(ConstructorArgs),
Chandler Carruth428edaf2010-10-25 08:47:36 +00001866 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete,
1867 SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00001868 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00001869 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001870
Douglas Gregorba70ab62010-04-16 22:17:36 +00001871 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1872 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001873
John McCall2de56d12010-08-25 11:45:40 +00001874 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001875 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001876
Douglas Gregorba70ab62010-04-16 22:17:36 +00001877 // Create an implicit call expr that calls it.
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001878 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00001879 if (Result.isInvalid())
1880 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001881
Douglas Gregorf2ae5262011-01-20 00:18:04 +00001882 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00001883 }
1884 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001885}
Douglas Gregorba70ab62010-04-16 22:17:36 +00001886
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001887/// PerformImplicitConversion - Perform an implicit conversion of the
1888/// expression From to the type ToType using the pre-computed implicit
1889/// conversion sequence ICS. Returns true if there was an error, false
1890/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001891/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001892/// used in the error message.
1893bool
1894Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1895 const ImplicitConversionSequence &ICS,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001896 AssignmentAction Action, bool CStyle) {
John McCall1d318332010-01-12 00:44:57 +00001897 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001898 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001899 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001900 CStyle))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001901 return true;
1902 break;
1903
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001904 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001905
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001906 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00001907 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001908 QualType BeforeToType;
1909 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00001910 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001911
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001912 // If the user-defined conversion is specified by a conversion function,
1913 // the initial standard conversion sequence converts the source type to
1914 // the implicit object parameter of the conversion function.
1915 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00001916 } else {
1917 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00001918 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001919 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001920 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001921 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001922 // initial standard conversion sequence converts the source type to the
1923 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001924 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1925 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001926 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00001927 // Watch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001928 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001929 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001930 ICS.UserDefined.Before, AA_Converting,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001931 CStyle))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001932 return true;
1933 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001934
1935 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00001936 = BuildCXXCastArgument(*this,
1937 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00001938 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001939 CastKind, cast<CXXMethodDecl>(FD),
1940 ICS.UserDefined.FoundConversionFunction,
John McCall9ae2f072010-08-23 23:25:46 +00001941 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00001942
1943 if (CastArg.isInvalid())
1944 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001945
1946 From = CastArg.takeAs<Expr>();
1947
Eli Friedmand8889622009-11-27 04:41:50 +00001948 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001949 AA_Converting, CStyle);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001950 }
John McCall1d318332010-01-12 00:44:57 +00001951
1952 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00001953 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00001954 PDiag(diag::err_typecheck_ambiguous_condition)
1955 << From->getSourceRange());
1956 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001957
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001958 case ImplicitConversionSequence::EllipsisConversion:
1959 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001960 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001961
1962 case ImplicitConversionSequence::BadConversion:
1963 return true;
1964 }
1965
1966 // Everything went well.
1967 return false;
1968}
1969
1970/// PerformImplicitConversion - Perform an implicit conversion of the
1971/// expression From to the type ToType by following the standard
1972/// conversion sequence SCS. Returns true if there was an error, false
1973/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001974/// expression. Flavor is the context in which we're performing this
1975/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001976bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001977Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001978 const StandardConversionSequence& SCS,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001979 AssignmentAction Action, bool CStyle) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001980 // Overall FIXME: we are recomputing too many types here and doing far too
1981 // much extra work. What this means is that we need to keep track of more
1982 // information that is computed when we try the implicit conversion initially,
1983 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001984 QualType FromType = From->getType();
1985
Douglas Gregor225c41e2008-11-03 19:09:14 +00001986 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001987 // FIXME: When can ToType be a reference type?
1988 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001989 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00001990 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001991 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00001992 MultiExprArg(*this, &From, 1),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001993 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001994 ConstructorArgs))
1995 return true;
John McCall60d7b3a2010-08-24 06:29:42 +00001996 ExprResult FromResult =
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001997 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1998 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00001999 move_arg(ConstructorArgs),
2000 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00002001 CXXConstructExpr::CK_Complete,
2002 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002003 if (FromResult.isInvalid())
2004 return true;
2005 From = FromResult.takeAs<Expr>();
2006 return false;
2007 }
John McCall60d7b3a2010-08-24 06:29:42 +00002008 ExprResult FromResult =
Mike Stump1eb44332009-09-09 15:08:12 +00002009 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2010 ToType, SCS.CopyConstructor,
John McCall7a1fad32010-08-24 07:32:53 +00002011 MultiExprArg(*this, &From, 1),
2012 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00002013 CXXConstructExpr::CK_Complete,
2014 SourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00002015
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002016 if (FromResult.isInvalid())
2017 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002019 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00002020 return false;
2021 }
2022
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002023 // Resolve overloaded function references.
2024 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2025 DeclAccessPair Found;
2026 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2027 true, Found);
2028 if (!Fn)
2029 return true;
2030
2031 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
2032 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002033
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002034 From = FixOverloadedFunctionReference(From, Found, Fn);
2035 FromType = From->getType();
2036 }
2037
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002038 // Perform the first implicit conversion.
2039 switch (SCS.First) {
2040 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002041 // Nothing to do.
2042 break;
2043
John McCallf6a16482010-12-04 03:47:34 +00002044 case ICK_Lvalue_To_Rvalue:
2045 // Should this get its own ICK?
2046 if (From->getObjectKind() == OK_ObjCProperty) {
2047 ConvertPropertyForRValue(From);
John McCall241d5582010-12-07 22:54:16 +00002048 if (!From->isGLValue()) break;
John McCallf6a16482010-12-04 03:47:34 +00002049 }
2050
Chandler Carruth35001ca2011-02-17 21:10:52 +00002051 // Check for trivial buffer overflows.
Ted Kremenek3aea4da2011-03-01 18:41:00 +00002052 CheckArrayAccess(From);
Chandler Carruth35001ca2011-02-17 21:10:52 +00002053
John McCallf6a16482010-12-04 03:47:34 +00002054 FromType = FromType.getUnqualifiedType();
2055 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2056 From, 0, VK_RValue);
2057 break;
2058
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002059 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002060 FromType = Context.getArrayDecayedType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00002061 ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002062 break;
2063
2064 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002065 FromType = Context.getPointerType(FromType);
John McCall2de56d12010-08-25 11:45:40 +00002066 ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002067 break;
2068
2069 default:
2070 assert(false && "Improper first standard conversion");
2071 break;
2072 }
2073
2074 // Perform the second implicit conversion
2075 switch (SCS.Second) {
2076 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002077 // If both sides are functions (or pointers/references to them), there could
2078 // be incompatible exception declarations.
2079 if (CheckExceptionSpecCompatibility(From, ToType))
2080 return true;
2081 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002082 break;
2083
Douglas Gregor43c79c22009-12-09 00:47:37 +00002084 case ICK_NoReturn_Adjustment:
2085 // If both sides are functions (or pointers/references to them), there could
2086 // be incompatible exception declarations.
2087 if (CheckExceptionSpecCompatibility(From, ToType))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002088 return true;
2089
John McCalle6a365d2010-12-19 02:44:49 +00002090 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor43c79c22009-12-09 00:47:37 +00002091 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002092
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002093 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002094 case ICK_Integral_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002095 ImpCastExprToType(From, ToType, CK_IntegralCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002096 break;
2097
2098 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002099 case ICK_Floating_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002100 ImpCastExprToType(From, ToType, CK_FloatingCast);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002101 break;
2102
2103 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00002104 case ICK_Complex_Conversion: {
2105 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2106 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2107 CastKind CK;
2108 if (FromEl->isRealFloatingType()) {
2109 if (ToEl->isRealFloatingType())
2110 CK = CK_FloatingComplexCast;
2111 else
2112 CK = CK_FloatingComplexToIntegralComplex;
2113 } else if (ToEl->isRealFloatingType()) {
2114 CK = CK_IntegralComplexToFloatingComplex;
2115 } else {
2116 CK = CK_IntegralComplexCast;
2117 }
2118 ImpCastExprToType(From, ToType, CK);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002119 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00002120 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002121
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002122 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002123 if (ToType->isRealFloatingType())
John McCall2de56d12010-08-25 11:45:40 +00002124 ImpCastExprToType(From, ToType, CK_IntegralToFloating);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002125 else
John McCall2de56d12010-08-25 11:45:40 +00002126 ImpCastExprToType(From, ToType, CK_FloatingToIntegral);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002127 break;
2128
Douglas Gregorf9201e02009-02-11 23:02:49 +00002129 case ICK_Compatible_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002130 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002131 break;
2132
Anders Carlsson61faec12009-09-12 04:46:44 +00002133 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00002134 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002135 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00002136 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00002137 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00002138 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00002139 << From->getSourceRange();
2140 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002141
John McCalldaa8e4e2010-11-15 09:13:47 +00002142 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002143 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002144 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002145 return true;
John McCall5baba9d2010-08-25 10:28:54 +00002146 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002147 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00002148 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002149
Anders Carlsson61faec12009-09-12 04:46:44 +00002150 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002151 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002152 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002153 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
Anders Carlsson61faec12009-09-12 04:46:44 +00002154 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002155 if (CheckExceptionSpecCompatibility(From, ToType))
2156 return true;
John McCall5baba9d2010-08-25 10:28:54 +00002157 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Anders Carlsson61faec12009-09-12 04:46:44 +00002158 break;
2159 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002160 case ICK_Boolean_Conversion: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002161 CastKind Kind = CK_Invalid;
2162 switch (FromType->getScalarTypeKind()) {
2163 case Type::STK_Pointer: Kind = CK_PointerToBoolean; break;
2164 case Type::STK_MemberPointer: Kind = CK_MemberPointerToBoolean; break;
2165 case Type::STK_Bool: llvm_unreachable("bool -> bool conversion?");
2166 case Type::STK_Integral: Kind = CK_IntegralToBoolean; break;
2167 case Type::STK_Floating: Kind = CK_FloatingToBoolean; break;
2168 case Type::STK_IntegralComplex: Kind = CK_IntegralComplexToBoolean; break;
2169 case Type::STK_FloatingComplex: Kind = CK_FloatingComplexToBoolean; break;
2170 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002171
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002172 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002173 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00002174 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002175
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002176 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002177 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002178 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002179 ToType.getNonReferenceType(),
2180 From->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002181 From->getSourceRange(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002182 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002183 CStyle))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002184 return true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002185
Sebastian Redl906082e2010-07-20 04:20:21 +00002186 ImpCastExprToType(From, ToType.getNonReferenceType(),
John McCall2de56d12010-08-25 11:45:40 +00002187 CK_DerivedToBase, CastCategory(From),
John McCallf871d0c2010-08-07 06:22:56 +00002188 &BasePath);
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002189 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002190 }
2191
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002192 case ICK_Vector_Conversion:
John McCall2de56d12010-08-25 11:45:40 +00002193 ImpCastExprToType(From, ToType, CK_BitCast);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002194 break;
2195
2196 case ICK_Vector_Splat:
John McCall2de56d12010-08-25 11:45:40 +00002197 ImpCastExprToType(From, ToType, CK_VectorSplat);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002198 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002199
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002200 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002201 // Case 1. x -> _Complex y
2202 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2203 QualType ElType = ToComplex->getElementType();
2204 bool isFloatingComplex = ElType->isRealFloatingType();
2205
2206 // x -> y
2207 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2208 // do nothing
2209 } else if (From->getType()->isRealFloatingType()) {
2210 ImpCastExprToType(From, ElType,
2211 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral);
2212 } else {
2213 assert(From->getType()->isIntegerType());
2214 ImpCastExprToType(From, ElType,
2215 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast);
2216 }
2217 // y -> _Complex y
2218 ImpCastExprToType(From, ToType,
2219 isFloatingComplex ? CK_FloatingRealToComplex
2220 : CK_IntegralRealToComplex);
2221
2222 // Case 2. _Complex x -> y
2223 } else {
2224 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2225 assert(FromComplex);
2226
2227 QualType ElType = FromComplex->getElementType();
2228 bool isFloatingComplex = ElType->isRealFloatingType();
2229
2230 // _Complex x -> x
2231 ImpCastExprToType(From, ElType,
2232 isFloatingComplex ? CK_FloatingComplexToReal
2233 : CK_IntegralComplexToReal);
2234
2235 // x -> y
2236 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2237 // do nothing
2238 } else if (ToType->isRealFloatingType()) {
2239 ImpCastExprToType(From, ToType,
2240 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating);
2241 } else {
2242 assert(ToType->isIntegerType());
2243 ImpCastExprToType(From, ToType,
2244 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast);
2245 }
2246 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002247 break;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002248
2249 case ICK_Block_Pointer_Conversion: {
2250 ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast, VK_RValue);
2251 break;
2252 }
2253
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002254 case ICK_Lvalue_To_Rvalue:
2255 case ICK_Array_To_Pointer:
2256 case ICK_Function_To_Pointer:
2257 case ICK_Qualification:
2258 case ICK_Num_Conversion_Kinds:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002259 assert(false && "Improper second standard conversion");
2260 break;
2261 }
2262
2263 switch (SCS.Third) {
2264 case ICK_Identity:
2265 // Nothing to do.
2266 break;
2267
Sebastian Redl906082e2010-07-20 04:20:21 +00002268 case ICK_Qualification: {
2269 // The qualification keeps the category of the inner expression, unless the
2270 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002271 ExprValueKind VK = ToType->isReferenceType() ?
2272 CastCategory(From) : VK_RValue;
Douglas Gregor63982352010-07-13 18:40:04 +00002273 ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
John McCall2de56d12010-08-25 11:45:40 +00002274 CK_NoOp, VK);
Douglas Gregora9bff302010-02-28 18:30:25 +00002275
Douglas Gregor069a6da2011-03-14 16:13:32 +00002276 if (SCS.DeprecatedStringLiteralToCharPtr &&
2277 !getLangOptions().WritableStrings)
Douglas Gregora9bff302010-02-28 18:30:25 +00002278 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2279 << ToType.getNonReferenceType();
2280
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002281 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002282 }
2283
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002284 default:
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002285 assert(false && "Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002286 break;
2287 }
2288
2289 return false;
2290}
2291
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002292ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002293 SourceLocation KWLoc,
2294 ParsedType Ty,
2295 SourceLocation RParen) {
2296 TypeSourceInfo *TSInfo;
2297 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002298
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002299 if (!TSInfo)
2300 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002301 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002302}
2303
Sebastian Redlf8aca862010-09-14 23:40:14 +00002304static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT, QualType T,
2305 SourceLocation KeyLoc) {
Douglas Gregora0506182011-01-27 20:35:44 +00002306 // FIXME: For many of these traits, we need a complete type before we can
2307 // check these properties.
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002308 assert(!T->isDependentType() &&
2309 "Cannot evaluate traits for dependent types.");
2310 ASTContext &C = Self.Context;
2311 switch(UTT) {
2312 default: assert(false && "Unknown type trait or not implemented");
2313 case UTT_IsPOD: return T->isPODType();
2314 case UTT_IsLiteral: return T->isLiteralType();
2315 case UTT_IsClass: // Fallthrough
2316 case UTT_IsUnion:
2317 if (const RecordType *Record = T->getAs<RecordType>()) {
2318 bool Union = Record->getDecl()->isUnion();
2319 return UTT == UTT_IsUnion ? Union : !Union;
2320 }
2321 return false;
2322 case UTT_IsEnum: return T->isEnumeralType();
2323 case UTT_IsPolymorphic:
2324 if (const RecordType *Record = T->getAs<RecordType>()) {
2325 // Type traits are only parsed in C++, so we've got CXXRecords.
2326 return cast<CXXRecordDecl>(Record->getDecl())->isPolymorphic();
2327 }
2328 return false;
2329 case UTT_IsAbstract:
2330 if (const RecordType *RT = T->getAs<RecordType>())
2331 return cast<CXXRecordDecl>(RT->getDecl())->isAbstract();
2332 return false;
2333 case UTT_IsEmpty:
2334 if (const RecordType *Record = T->getAs<RecordType>()) {
2335 return !Record->getDecl()->isUnion()
2336 && cast<CXXRecordDecl>(Record->getDecl())->isEmpty();
2337 }
2338 return false;
2339 case UTT_HasTrivialConstructor:
2340 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2341 // If __is_pod (type) is true then the trait is true, else if type is
2342 // a cv class or union type (or array thereof) with a trivial default
2343 // constructor ([class.ctor]) then the trait is true, else it is false.
2344 if (T->isPODType())
2345 return true;
2346 if (const RecordType *RT =
2347 C.getBaseElementType(T)->getAs<RecordType>())
2348 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialConstructor();
2349 return false;
2350 case UTT_HasTrivialCopy:
2351 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2352 // If __is_pod (type) is true or type is a reference type then
2353 // the trait is true, else if type is a cv class or union type
2354 // with a trivial copy constructor ([class.copy]) then the trait
2355 // is true, else it is false.
2356 if (T->isPODType() || T->isReferenceType())
2357 return true;
2358 if (const RecordType *RT = T->getAs<RecordType>())
2359 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2360 return false;
2361 case UTT_HasTrivialAssign:
2362 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2363 // If type is const qualified or is a reference type then the
2364 // trait is false. Otherwise if __is_pod (type) is true then the
2365 // trait is true, else if type is a cv class or union type with
2366 // a trivial copy assignment ([class.copy]) then the trait is
2367 // true, else it is false.
2368 // Note: the const and reference restrictions are interesting,
2369 // given that const and reference members don't prevent a class
2370 // from having a trivial copy assignment operator (but do cause
2371 // errors if the copy assignment operator is actually used, q.v.
2372 // [class.copy]p12).
2373
2374 if (C.getBaseElementType(T).isConstQualified())
2375 return false;
2376 if (T->isPODType())
2377 return true;
2378 if (const RecordType *RT = T->getAs<RecordType>())
2379 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2380 return false;
2381 case UTT_HasTrivialDestructor:
2382 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2383 // If __is_pod (type) is true or type is a reference type
2384 // then the trait is true, else if type is a cv class or union
2385 // type (or array thereof) with a trivial destructor
2386 // ([class.dtor]) then the trait is true, else it is
2387 // false.
2388 if (T->isPODType() || T->isReferenceType())
2389 return true;
2390 if (const RecordType *RT =
2391 C.getBaseElementType(T)->getAs<RecordType>())
2392 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2393 return false;
2394 // TODO: Propagate nothrowness for implicitly declared special members.
2395 case UTT_HasNothrowAssign:
2396 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2397 // If type is const qualified or is a reference type then the
2398 // trait is false. Otherwise if __has_trivial_assign (type)
2399 // is true then the trait is true, else if type is a cv class
2400 // or union type with copy assignment operators that are known
2401 // not to throw an exception then the trait is true, else it is
2402 // false.
2403 if (C.getBaseElementType(T).isConstQualified())
2404 return false;
2405 if (T->isReferenceType())
2406 return false;
2407 if (T->isPODType())
2408 return true;
2409 if (const RecordType *RT = T->getAs<RecordType>()) {
2410 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2411 if (RD->hasTrivialCopyAssignment())
2412 return true;
2413
2414 bool FoundAssign = false;
2415 bool AllNoThrow = true;
2416 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00002417 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2418 Sema::LookupOrdinaryName);
2419 if (Self.LookupQualifiedName(Res, RD)) {
2420 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2421 Op != OpEnd; ++Op) {
2422 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2423 if (Operator->isCopyAssignmentOperator()) {
2424 FoundAssign = true;
2425 const FunctionProtoType *CPT
2426 = Operator->getType()->getAs<FunctionProtoType>();
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002427 if (!CPT->isNothrow(Self.Context)) {
Sebastian Redlf8aca862010-09-14 23:40:14 +00002428 AllNoThrow = false;
2429 break;
2430 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002431 }
2432 }
2433 }
2434
2435 return FoundAssign && AllNoThrow;
2436 }
2437 return false;
2438 case UTT_HasNothrowCopy:
2439 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2440 // If __has_trivial_copy (type) is true then the trait is true, else
2441 // if type is a cv class or union type with copy constructors that are
2442 // known not to throw an exception then the trait is true, else it is
2443 // false.
2444 if (T->isPODType() || T->isReferenceType())
2445 return true;
2446 if (const RecordType *RT = T->getAs<RecordType>()) {
2447 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2448 if (RD->hasTrivialCopyConstructor())
2449 return true;
2450
2451 bool FoundConstructor = false;
2452 bool AllNoThrow = true;
2453 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002454 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00002455 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002456 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002457 // A template constructor is never a copy constructor.
2458 // FIXME: However, it may actually be selected at the actual overload
2459 // resolution point.
2460 if (isa<FunctionTemplateDecl>(*Con))
2461 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002462 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2463 if (Constructor->isCopyConstructor(FoundTQs)) {
2464 FoundConstructor = true;
2465 const FunctionProtoType *CPT
2466 = Constructor->getType()->getAs<FunctionProtoType>();
Sebastian Redl60618fa2011-03-12 11:50:43 +00002467 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redl751025d2010-09-13 22:02:47 +00002468 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002469 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002470 AllNoThrow = false;
2471 break;
2472 }
2473 }
2474 }
2475
2476 return FoundConstructor && AllNoThrow;
2477 }
2478 return false;
2479 case UTT_HasNothrowConstructor:
2480 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2481 // If __has_trivial_constructor (type) is true then the trait is
2482 // true, else if type is a cv class or union type (or array
2483 // thereof) with a default constructor that is known not to
2484 // throw an exception then the trait is true, else it is false.
2485 if (T->isPODType())
2486 return true;
2487 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2488 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2489 if (RD->hasTrivialConstructor())
2490 return true;
2491
Sebastian Redl751025d2010-09-13 22:02:47 +00002492 DeclContext::lookup_const_iterator Con, ConEnd;
2493 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2494 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002495 // FIXME: In C++0x, a constructor template can be a default constructor.
2496 if (isa<FunctionTemplateDecl>(*Con))
2497 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00002498 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2499 if (Constructor->isDefaultConstructor()) {
2500 const FunctionProtoType *CPT
2501 = Constructor->getType()->getAs<FunctionProtoType>();
2502 // TODO: check whether evaluating default arguments can throw.
2503 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002504 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
Sebastian Redl751025d2010-09-13 22:02:47 +00002505 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002506 }
2507 }
2508 return false;
2509 case UTT_HasVirtualDestructor:
2510 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2511 // If type is a class type with a virtual destructor ([class.dtor])
2512 // then the trait is true, else it is false.
2513 if (const RecordType *Record = T->getAs<RecordType>()) {
2514 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00002515 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002516 return Destructor->isVirtual();
2517 }
2518 return false;
2519 }
2520}
2521
2522ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002523 SourceLocation KWLoc,
2524 TypeSourceInfo *TSInfo,
2525 SourceLocation RParen) {
2526 QualType T = TSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002527
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002528 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
2529 // all traits except __is_class, __is_enum and __is_union require a the type
Sebastian Redl607a1782010-09-08 00:48:43 +00002530 // to be complete, an array of unknown bound, or void.
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002531 if (UTT != UTT_IsClass && UTT != UTT_IsEnum && UTT != UTT_IsUnion) {
Sebastian Redl607a1782010-09-08 00:48:43 +00002532 QualType E = T;
2533 if (T->isIncompleteArrayType())
2534 E = Context.getAsArrayType(T)->getElementType();
2535 if (!T->isVoidType() &&
2536 RequireCompleteType(KWLoc, E,
Anders Carlssond497ba72009-08-26 22:59:12 +00002537 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002538 return ExprError();
2539 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002540
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002541 bool Value = false;
2542 if (!T->isDependentType())
Sebastian Redlf8aca862010-09-14 23:40:14 +00002543 Value = EvaluateUnaryTypeTrait(*this, UTT, T, KWLoc);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002544
2545 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002546 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00002547}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002548
Francois Pichet6ad6f282010-12-07 00:08:36 +00002549ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
2550 SourceLocation KWLoc,
2551 ParsedType LhsTy,
2552 ParsedType RhsTy,
2553 SourceLocation RParen) {
2554 TypeSourceInfo *LhsTSInfo;
2555 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
2556 if (!LhsTSInfo)
2557 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
2558
2559 TypeSourceInfo *RhsTSInfo;
2560 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
2561 if (!RhsTSInfo)
2562 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
2563
2564 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
2565}
2566
2567static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
2568 QualType LhsT, QualType RhsT,
2569 SourceLocation KeyLoc) {
2570 assert((!LhsT->isDependentType() || RhsT->isDependentType()) &&
2571 "Cannot evaluate traits for dependent types.");
2572
2573 switch(BTT) {
John McCalld89d30f2011-01-28 22:02:36 +00002574 case BTT_IsBaseOf: {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002575 // C++0x [meta.rel]p2
John McCalld89d30f2011-01-28 22:02:36 +00002576 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet6ad6f282010-12-07 00:08:36 +00002577 // Base and Derived are not unions and name the same class type without
2578 // regard to cv-qualifiers.
Francois Pichet6ad6f282010-12-07 00:08:36 +00002579
John McCalld89d30f2011-01-28 22:02:36 +00002580 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
2581 if (!lhsRecord) return false;
2582
2583 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
2584 if (!rhsRecord) return false;
2585
2586 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
2587 == (lhsRecord == rhsRecord));
2588
2589 if (lhsRecord == rhsRecord)
2590 return !lhsRecord->getDecl()->isUnion();
2591
2592 // C++0x [meta.rel]p2:
2593 // If Base and Derived are class types and are different types
2594 // (ignoring possible cv-qualifiers) then Derived shall be a
2595 // complete type.
2596 if (Self.RequireCompleteType(KeyLoc, RhsT,
2597 diag::err_incomplete_type_used_in_type_trait_expr))
2598 return false;
2599
2600 return cast<CXXRecordDecl>(rhsRecord->getDecl())
2601 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
2602 }
2603
Francois Pichetf1872372010-12-08 22:35:30 +00002604 case BTT_TypeCompatible:
2605 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
2606 RhsT.getUnqualifiedType());
Douglas Gregor9f361132011-01-27 20:28:01 +00002607
2608 case BTT_IsConvertibleTo: {
2609 // C++0x [meta.rel]p4:
2610 // Given the following function prototype:
2611 //
2612 // template <class T>
2613 // typename add_rvalue_reference<T>::type create();
2614 //
2615 // the predicate condition for a template specialization
2616 // is_convertible<From, To> shall be satisfied if and only if
2617 // the return expression in the following code would be
2618 // well-formed, including any implicit conversions to the return
2619 // type of the function:
2620 //
2621 // To test() {
2622 // return create<From>();
2623 // }
2624 //
2625 // Access checking is performed as if in a context unrelated to To and
2626 // From. Only the validity of the immediate context of the expression
2627 // of the return-statement (including conversions to the return type)
2628 // is considered.
2629 //
2630 // We model the initialization as a copy-initialization of a temporary
2631 // of the appropriate type, which for this expression is identical to the
2632 // return statement (since NRVO doesn't apply).
2633 if (LhsT->isObjectType() || LhsT->isFunctionType())
2634 LhsT = Self.Context.getRValueReferenceType(LhsT);
2635
2636 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorb608b982011-01-28 02:26:04 +00002637 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor9f361132011-01-27 20:28:01 +00002638 Expr::getValueKindForType(LhsT));
2639 Expr *FromPtr = &From;
2640 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
2641 SourceLocation()));
2642
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00002643 // Perform the initialization within a SFINAE trap at translation unit
2644 // scope.
2645 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
2646 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor9f361132011-01-27 20:28:01 +00002647 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
2648 if (Init.getKind() == InitializationSequence::FailedSequence)
2649 return false;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00002650
Douglas Gregor9f361132011-01-27 20:28:01 +00002651 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
2652 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
2653 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00002654 }
2655 llvm_unreachable("Unknown type trait or not implemented");
2656}
2657
2658ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
2659 SourceLocation KWLoc,
2660 TypeSourceInfo *LhsTSInfo,
2661 TypeSourceInfo *RhsTSInfo,
2662 SourceLocation RParen) {
2663 QualType LhsT = LhsTSInfo->getType();
2664 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002665
John McCalld89d30f2011-01-28 22:02:36 +00002666 if (BTT == BTT_TypeCompatible) {
Francois Pichetf1872372010-12-08 22:35:30 +00002667 if (getLangOptions().CPlusPlus) {
2668 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
2669 << SourceRange(KWLoc, RParen);
2670 return ExprError();
2671 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00002672 }
2673
2674 bool Value = false;
2675 if (!LhsT->isDependentType() && !RhsT->isDependentType())
2676 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
2677
Francois Pichetf1872372010-12-08 22:35:30 +00002678 // Select trait result type.
2679 QualType ResultType;
2680 switch (BTT) {
Francois Pichetf1872372010-12-08 22:35:30 +00002681 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
2682 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor9f361132011-01-27 20:28:01 +00002683 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00002684 }
2685
Francois Pichet6ad6f282010-12-07 00:08:36 +00002686 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
2687 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00002688 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00002689}
2690
John McCallf89e55a2010-11-18 06:31:45 +00002691QualType Sema::CheckPointerToMemberOperands(Expr *&lex, Expr *&rex,
2692 ExprValueKind &VK,
2693 SourceLocation Loc,
2694 bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002695 const char *OpSpelling = isIndirect ? "->*" : ".*";
2696 // C++ 5.5p2
2697 // The binary operator .* [p3: ->*] binds its second operand, which shall
2698 // be of type "pointer to member of T" (where T is a completely-defined
2699 // class type) [...]
2700 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002701 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00002702 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002703 Diag(Loc, diag::err_bad_memptr_rhs)
2704 << OpSpelling << RType << rex->getSourceRange();
2705 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00002706 }
Douglas Gregore7450f52009-03-24 19:52:54 +00002707
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002708 QualType Class(MemPtr->getClass(), 0);
2709
Douglas Gregor7d520ba2010-10-13 20:41:14 +00002710 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
2711 // member pointer points must be completely-defined. However, there is no
2712 // reason for this semantic distinction, and the rule is not enforced by
2713 // other compilers. Therefore, we do not check this property, as it is
2714 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00002715
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002716 // C++ 5.5p2
2717 // [...] to its first operand, which shall be of class T or of a class of
2718 // which T is an unambiguous and accessible base class. [p3: a pointer to
2719 // such a class]
2720 QualType LType = lex->getType();
2721 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002722 if (const PointerType *Ptr = LType->getAs<PointerType>())
John McCallf89e55a2010-11-18 06:31:45 +00002723 LType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002724 else {
2725 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00002726 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00002727 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002728 return QualType();
2729 }
2730 }
2731
Douglas Gregora4923eb2009-11-16 21:35:15 +00002732 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00002733 // If we want to check the hierarchy, we need a complete type.
2734 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
2735 << OpSpelling << (int)isIndirect)) {
2736 return QualType();
2737 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002738 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002739 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00002740 // FIXME: Would it be useful to print full ambiguity paths, or is that
2741 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002742 if (!IsDerivedFrom(LType, Class, Paths) ||
2743 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
2744 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00002745 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002746 return QualType();
2747 }
Eli Friedman3005efe2010-01-16 00:00:48 +00002748 // Cast LHS to type of use.
2749 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
John McCall5baba9d2010-08-25 10:28:54 +00002750 ExprValueKind VK =
2751 isIndirect ? VK_RValue : CastCategory(lex);
Sebastian Redl906082e2010-07-20 04:20:21 +00002752
John McCallf871d0c2010-08-07 06:22:56 +00002753 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002754 BuildBasePathArray(Paths, BasePath);
John McCall5baba9d2010-08-25 10:28:54 +00002755 ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002756 }
2757
Douglas Gregored8abf12010-07-08 06:14:04 +00002758 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00002759 // Diagnose use of pointer-to-member type which when used as
2760 // the functional cast in a pointer-to-member expression.
2761 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2762 return QualType();
2763 }
John McCallf89e55a2010-11-18 06:31:45 +00002764
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002765 // C++ 5.5p2
2766 // The result is an object or a function of the type specified by the
2767 // second operand.
2768 // The cv qualifiers are the union of those in the pointer and the left side,
2769 // in accordance with 5.5p5 and 5.2.5.
2770 // FIXME: This returns a dereferenced member function pointer as a normal
2771 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00002772 // calling them. There's also a GCC extension to get a function pointer to the
2773 // thing, which is another complication, because this type - unlike the type
2774 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002775 // argument.
2776 // We probably need a "MemberFunctionClosureType" or something like that.
2777 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00002778 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00002779
Douglas Gregor6b4df912011-01-26 16:40:18 +00002780 // C++0x [expr.mptr.oper]p6:
2781 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002782 // ill-formed if the second operand is a pointer to member function with
2783 // ref-qualifier &. In a ->* expression or in a .* expression whose object
2784 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor6b4df912011-01-26 16:40:18 +00002785 // is a pointer to member function with ref-qualifier &&.
2786 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
2787 switch (Proto->getRefQualifier()) {
2788 case RQ_None:
2789 // Do nothing
2790 break;
2791
2792 case RQ_LValue:
2793 if (!isIndirect && !lex->Classify(Context).isLValue())
2794 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2795 << RType << 1 << lex->getSourceRange();
2796 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002797
Douglas Gregor6b4df912011-01-26 16:40:18 +00002798 case RQ_RValue:
2799 if (isIndirect || !lex->Classify(Context).isRValue())
2800 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2801 << RType << 0 << lex->getSourceRange();
2802 break;
2803 }
2804 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002805
John McCallf89e55a2010-11-18 06:31:45 +00002806 // C++ [expr.mptr.oper]p6:
2807 // The result of a .* expression whose second operand is a pointer
2808 // to a data member is of the same value category as its
2809 // first operand. The result of a .* expression whose second
2810 // operand is a pointer to a member function is a prvalue. The
2811 // result of an ->* expression is an lvalue if its second operand
2812 // is a pointer to data member and a prvalue otherwise.
2813 if (Result->isFunctionType())
2814 VK = VK_RValue;
2815 else if (isIndirect)
2816 VK = VK_LValue;
2817 else
2818 VK = lex->getValueKind();
2819
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002820 return Result;
2821}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002822
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002823/// \brief Try to convert a type to another according to C++0x 5.16p3.
2824///
2825/// This is part of the parameter validation for the ? operator. If either
2826/// value operand is a class type, the two operands are attempted to be
2827/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002828/// It returns true if the program is ill-formed and has already been diagnosed
2829/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002830static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2831 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00002832 bool &HaveConversion,
2833 QualType &ToType) {
2834 HaveConversion = false;
2835 ToType = To->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002836
2837 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00002838 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002839 // C++0x 5.16p3
2840 // The process for determining whether an operand expression E1 of type T1
2841 // can be converted to match an operand expression E2 of type T2 is defined
2842 // as follows:
2843 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00002844 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002845 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002846 // E1 can be converted to match E2 if E1 can be implicitly converted to
2847 // type "lvalue reference to T2", subject to the constraint that in the
2848 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002849 QualType T = Self.Context.getLValueReferenceType(ToType);
2850 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002851
Douglas Gregorb70cf442010-03-26 20:14:36 +00002852 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2853 if (InitSeq.isDirectReferenceBinding()) {
2854 ToType = T;
2855 HaveConversion = true;
2856 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002857 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002858
Douglas Gregorb70cf442010-03-26 20:14:36 +00002859 if (InitSeq.isAmbiguous())
2860 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002861 }
John McCallb1bdc622010-02-25 01:37:24 +00002862
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002863 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2864 // -- if E1 and E2 have class type, and the underlying class types are
2865 // the same or one is a base class of the other:
2866 QualType FTy = From->getType();
2867 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002868 const RecordType *FRec = FTy->getAs<RecordType>();
2869 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002870 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00002871 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002872 if (FRec && TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00002873 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002874 // E1 can be converted to match E2 if the class of T2 is the
2875 // same type as, or a base class of, the class of T1, and
2876 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00002877 if (FRec == TRec || FDerivedFromT) {
2878 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002879 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2880 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2881 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2882 HaveConversion = true;
2883 return false;
2884 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002885
Douglas Gregorb70cf442010-03-26 20:14:36 +00002886 if (InitSeq.isAmbiguous())
2887 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002888 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002889 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002890
Douglas Gregorb70cf442010-03-26 20:14:36 +00002891 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002892 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002893
Douglas Gregorb70cf442010-03-26 20:14:36 +00002894 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2895 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002896 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002897 // an rvalue).
2898 //
2899 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2900 // to the array-to-pointer or function-to-pointer conversions.
2901 if (!TTy->getAs<TagType>())
2902 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002903
Douglas Gregorb70cf442010-03-26 20:14:36 +00002904 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2905 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002906 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002907 ToType = TTy;
2908 if (InitSeq.isAmbiguous())
2909 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2910
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002911 return false;
2912}
2913
2914/// \brief Try to find a common type for two according to C++0x 5.16p5.
2915///
2916/// This is part of the parameter validation for the ? operator. If either
2917/// value operand is a class type, overload resolution is used to find a
2918/// conversion to a common type.
2919static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
Chandler Carruth82214a82011-02-18 23:54:50 +00002920 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002921 Expr *Args[2] = { LHS, RHS };
Chandler Carruth82214a82011-02-18 23:54:50 +00002922 OverloadCandidateSet CandidateSet(QuestionLoc);
2923 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
2924 CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002925
2926 OverloadCandidateSet::iterator Best;
Chandler Carruth82214a82011-02-18 23:54:50 +00002927 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002928 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002929 // We found a match. Perform the conversions on the arguments and move on.
2930 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002931 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002932 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002933 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002934 break;
Chandler Carruth25ca4212011-02-25 19:41:05 +00002935 if (Best->Function)
2936 Self.MarkDeclarationReferenced(QuestionLoc, Best->Function);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002937 return false;
2938
Douglas Gregor20093b42009-12-09 23:02:17 +00002939 case OR_No_Viable_Function:
Chandler Carruth82214a82011-02-18 23:54:50 +00002940
2941 // Emit a better diagnostic if one of the expressions is a null pointer
2942 // constant and the other is a pointer type. In this case, the user most
2943 // likely forgot to take the address of the other expression.
2944 if (Self.DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
2945 return true;
2946
2947 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002948 << LHS->getType() << RHS->getType()
2949 << LHS->getSourceRange() << RHS->getSourceRange();
2950 return true;
2951
Douglas Gregor20093b42009-12-09 23:02:17 +00002952 case OR_Ambiguous:
Chandler Carruth82214a82011-02-18 23:54:50 +00002953 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002954 << LHS->getType() << RHS->getType()
2955 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002956 // FIXME: Print the possible common types by printing the return types of
2957 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002958 break;
2959
Douglas Gregor20093b42009-12-09 23:02:17 +00002960 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002961 assert(false && "Conditional operator has only built-in overloads");
2962 break;
2963 }
2964 return true;
2965}
2966
Sebastian Redl76458502009-04-17 16:30:52 +00002967/// \brief Perform an "extended" implicit conversion as returned by
2968/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002969static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2970 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2971 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2972 SourceLocation());
2973 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
John McCallf312b1e2010-08-26 23:41:50 +00002974 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00002975 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002976 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002977
Douglas Gregorb70cf442010-03-26 20:14:36 +00002978 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002979 return false;
2980}
2981
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002982/// \brief Check the operands of ?: under C++ semantics.
2983///
2984/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2985/// extension. In this case, LHS == Cond. (But they're not aliases.)
2986QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCall56ca35d2011-02-17 10:25:35 +00002987 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002988 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002989 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2990 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002991
2992 // C++0x 5.16p1
2993 // The first expression is contextually converted to bool.
2994 if (!Cond->isTypeDependent()) {
2995 if (CheckCXXBooleanCondition(Cond))
2996 return QualType();
2997 }
2998
John McCallf89e55a2010-11-18 06:31:45 +00002999 // Assume r-value.
3000 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00003001 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00003002
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003003 // Either of the arguments dependent?
3004 if (LHS->isTypeDependent() || RHS->isTypeDependent())
3005 return Context.DependentTy;
3006
3007 // C++0x 5.16p2
3008 // If either the second or the third operand has type (cv) void, ...
3009 QualType LTy = LHS->getType();
3010 QualType RTy = RHS->getType();
3011 bool LVoid = LTy->isVoidType();
3012 bool RVoid = RTy->isVoidType();
3013 if (LVoid || RVoid) {
3014 // ... then the [l2r] conversions are performed on the second and third
3015 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00003016 DefaultFunctionArrayLvalueConversion(LHS);
3017 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003018 LTy = LHS->getType();
3019 RTy = RHS->getType();
3020
3021 // ... and one of the following shall hold:
3022 // -- The second or the third operand (but not both) is a throw-
3023 // expression; the result is of the type of the other and is an rvalue.
3024 bool LThrow = isa<CXXThrowExpr>(LHS);
3025 bool RThrow = isa<CXXThrowExpr>(RHS);
3026 if (LThrow && !RThrow)
3027 return RTy;
3028 if (RThrow && !LThrow)
3029 return LTy;
3030
3031 // -- Both the second and third operands have type void; the result is of
3032 // type void and is an rvalue.
3033 if (LVoid && RVoid)
3034 return Context.VoidTy;
3035
3036 // Neither holds, error.
3037 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3038 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
3039 << LHS->getSourceRange() << RHS->getSourceRange();
3040 return QualType();
3041 }
3042
3043 // Neither is void.
3044
3045 // C++0x 5.16p3
3046 // Otherwise, if the second and third operand have different types, and
3047 // either has (cv) class type, and attempt is made to convert each of those
3048 // operands to the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003049 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003050 (LTy->isRecordType() || RTy->isRecordType())) {
3051 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3052 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003053 QualType L2RType, R2LType;
3054 bool HaveL2R, HaveR2L;
3055 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003056 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00003057 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003058 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003059
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003060 // If both can be converted, [...] the program is ill-formed.
3061 if (HaveL2R && HaveR2L) {
3062 Diag(QuestionLoc, diag::err_conditional_ambiguous)
3063 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
3064 return QualType();
3065 }
3066
3067 // If exactly one conversion is possible, that conversion is applied to
3068 // the chosen operand and the converted operands are used in place of the
3069 // original operands for the remainder of this section.
3070 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003071 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003072 return QualType();
3073 LTy = LHS->getType();
3074 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003075 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003076 return QualType();
3077 RTy = RHS->getType();
3078 }
3079 }
3080
3081 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00003082 // If the second and third operands are glvalues of the same value
3083 // category and have the same type, the result is of that type and
3084 // value category and it is a bit-field if the second or the third
3085 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00003086 // We only extend this to bitfields, not to the crazy other kinds of
3087 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003088 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00003089 if (Same &&
John McCall56ca35d2011-02-17 10:25:35 +00003090 LHS->isGLValue() &&
John McCallf89e55a2010-11-18 06:31:45 +00003091 LHS->getValueKind() == RHS->getValueKind() &&
John McCall56ca35d2011-02-17 10:25:35 +00003092 LHS->isOrdinaryOrBitFieldObject() &&
3093 RHS->isOrdinaryOrBitFieldObject()) {
John McCallf89e55a2010-11-18 06:31:45 +00003094 VK = LHS->getValueKind();
John McCall09431682010-11-18 19:01:18 +00003095 if (LHS->getObjectKind() == OK_BitField ||
3096 RHS->getObjectKind() == OK_BitField)
3097 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00003098 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00003099 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003100
3101 // C++0x 5.16p5
3102 // Otherwise, the result is an rvalue. If the second and third operands
3103 // do not have the same type, and either has (cv) class type, ...
3104 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3105 // ... overload resolution is used to determine the conversions (if any)
3106 // to be applied to the operands. If the overload resolution fails, the
3107 // program is ill-formed.
3108 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3109 return QualType();
3110 }
3111
3112 // C++0x 5.16p6
3113 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3114 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00003115 DefaultFunctionArrayLvalueConversion(LHS);
3116 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003117 LTy = LHS->getType();
3118 RTy = RHS->getType();
3119
3120 // After those conversions, one of the following shall hold:
3121 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00003122 // is of that type. If the operands have class type, the result
3123 // is a prvalue temporary of the result type, which is
3124 // copy-initialized from either the second operand or the third
3125 // operand depending on the value of the first operand.
3126 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3127 if (LTy->isRecordType()) {
3128 // The operands have class type. Make a temporary copy.
3129 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003130 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3131 SourceLocation(),
John McCallf6a16482010-12-04 03:47:34 +00003132 Owned(LHS));
Douglas Gregorb65a4582010-05-19 23:40:50 +00003133 if (LHSCopy.isInvalid())
3134 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003135
3136 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3137 SourceLocation(),
John McCallf6a16482010-12-04 03:47:34 +00003138 Owned(RHS));
Douglas Gregorb65a4582010-05-19 23:40:50 +00003139 if (RHSCopy.isInvalid())
3140 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003141
Douglas Gregorb65a4582010-05-19 23:40:50 +00003142 LHS = LHSCopy.takeAs<Expr>();
3143 RHS = RHSCopy.takeAs<Expr>();
3144 }
3145
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003146 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003147 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003148
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003149 // Extension: conditional operator involving vector types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003150 if (LTy->isVectorType() || RTy->isVectorType())
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003151 return CheckVectorOperands(QuestionLoc, LHS, RHS);
3152
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003153 // -- The second and third operands have arithmetic or enumeration type;
3154 // the usual arithmetic conversions are performed to bring them to a
3155 // common type, and the result is of that type.
3156 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3157 UsualArithmeticConversions(LHS, RHS);
3158 return LHS->getType();
3159 }
3160
3161 // -- The second and third operands have pointer type, or one has pointer
3162 // type and the other is a null pointer constant; pointer conversions
3163 // and qualification conversions are performed to bring them to their
3164 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00003165 // -- The second and third operands have pointer to member type, or one has
3166 // pointer to member type and the other is a null pointer constant;
3167 // pointer to member conversions and qualification conversions are
3168 // performed to bring them to a common type, whose cv-qualification
3169 // shall match the cv-qualification of either the second or the third
3170 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003171 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003172 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003173 isSFINAEContext()? 0 : &NonStandardCompositeType);
3174 if (!Composite.isNull()) {
3175 if (NonStandardCompositeType)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003176 Diag(QuestionLoc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003177 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3178 << LTy << RTy << Composite
3179 << LHS->getSourceRange() << RHS->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003180
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003181 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003182 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003183
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003184 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00003185 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3186 if (!Composite.isNull())
3187 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003188
Chandler Carruth7ef93242011-02-19 00:13:59 +00003189 // Check if we are using a null with a non-pointer type.
3190 if (DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
3191 return QualType();
3192
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003193 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3194 << LHS->getType() << RHS->getType()
3195 << LHS->getSourceRange() << RHS->getSourceRange();
3196 return QualType();
3197}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003198
3199/// \brief Find a merged pointer type and convert the two expressions to it.
3200///
Douglas Gregor20b3e992009-08-24 17:42:35 +00003201/// This finds the composite pointer type (or member pointer type) for @p E1
3202/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3203/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003204/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003205///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003206/// \param Loc The location of the operator requiring these two expressions to
3207/// be converted to the composite pointer type.
3208///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003209/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3210/// a non-standard (but still sane) composite type to which both expressions
3211/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3212/// will be set true.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003213QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003214 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003215 bool *NonStandardCompositeType) {
3216 if (NonStandardCompositeType)
3217 *NonStandardCompositeType = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003218
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003219 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3220 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003221
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00003222 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3223 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00003224 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003225
3226 // C++0x 5.9p2
3227 // Pointer conversions and qualification conversions are performed on
3228 // pointer operands to bring them to their composite pointer type. If
3229 // one operand is a null pointer constant, the composite pointer type is
3230 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00003231 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003232 if (T2->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00003233 ImpCastExprToType(E1, T2, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003234 else
John McCall404cd162010-11-13 01:35:44 +00003235 ImpCastExprToType(E1, T2, CK_NullToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003236 return T2;
3237 }
Douglas Gregorce940492009-09-25 04:25:58 +00003238 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003239 if (T1->isMemberPointerType())
John McCall2de56d12010-08-25 11:45:40 +00003240 ImpCastExprToType(E2, T1, CK_NullToMemberPointer);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003241 else
John McCall404cd162010-11-13 01:35:44 +00003242 ImpCastExprToType(E2, T1, CK_NullToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003243 return T1;
3244 }
Mike Stump1eb44332009-09-09 15:08:12 +00003245
Douglas Gregor20b3e992009-08-24 17:42:35 +00003246 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003247 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3248 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003249 return QualType();
3250
3251 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3252 // the other has type "pointer to cv2 T" and the composite pointer type is
3253 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3254 // Otherwise, the composite pointer type is a pointer type similar to the
3255 // type of one of the operands, with a cv-qualification signature that is
3256 // the union of the cv-qualification signatures of the operand types.
3257 // In practice, the first part here is redundant; it's subsumed by the second.
3258 // What we do here is, we build the two possible composite types, and try the
3259 // conversions in both directions. If only one works, or if the two composite
3260 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00003261 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00003262 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
3263 QualifierVector QualifierUnion;
3264 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
3265 ContainingClassVector;
3266 ContainingClassVector MemberOfClass;
3267 QualType Composite1 = Context.getCanonicalType(T1),
3268 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003269 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00003270 do {
3271 const PointerType *Ptr1, *Ptr2;
3272 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3273 (Ptr2 = Composite2->getAs<PointerType>())) {
3274 Composite1 = Ptr1->getPointeeType();
3275 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003276
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003277 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003278 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003279 if (NonStandardCompositeType &&
3280 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3281 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003282
Douglas Gregor20b3e992009-08-24 17:42:35 +00003283 QualifierUnion.push_back(
3284 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3285 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3286 continue;
3287 }
Mike Stump1eb44332009-09-09 15:08:12 +00003288
Douglas Gregor20b3e992009-08-24 17:42:35 +00003289 const MemberPointerType *MemPtr1, *MemPtr2;
3290 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3291 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3292 Composite1 = MemPtr1->getPointeeType();
3293 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003294
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003295 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003296 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003297 if (NonStandardCompositeType &&
3298 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3299 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003300
Douglas Gregor20b3e992009-08-24 17:42:35 +00003301 QualifierUnion.push_back(
3302 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3303 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3304 MemPtr2->getClass()));
3305 continue;
3306 }
Mike Stump1eb44332009-09-09 15:08:12 +00003307
Douglas Gregor20b3e992009-08-24 17:42:35 +00003308 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00003309
Douglas Gregor20b3e992009-08-24 17:42:35 +00003310 // Cannot unwrap any more types.
3311 break;
3312 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00003313
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003314 if (NeedConstBefore && NonStandardCompositeType) {
3315 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003316 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003317 // requirements of C++ [conv.qual]p4 bullet 3.
3318 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3319 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3320 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3321 *NonStandardCompositeType = true;
3322 }
3323 }
3324 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003325
Douglas Gregor20b3e992009-08-24 17:42:35 +00003326 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003327 ContainingClassVector::reverse_iterator MOC
3328 = MemberOfClass.rbegin();
3329 for (QualifierVector::reverse_iterator
3330 I = QualifierUnion.rbegin(),
3331 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00003332 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00003333 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003334 if (MOC->first && MOC->second) {
3335 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00003336 Composite1 = Context.getMemberPointerType(
3337 Context.getQualifiedType(Composite1, Quals),
3338 MOC->first);
3339 Composite2 = Context.getMemberPointerType(
3340 Context.getQualifiedType(Composite2, Quals),
3341 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003342 } else {
3343 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00003344 Composite1
3345 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3346 Composite2
3347 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00003348 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003349 }
3350
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003351 // Try to convert to the first composite pointer type.
3352 InitializedEntity Entity1
3353 = InitializedEntity::InitializeTemporary(Composite1);
3354 InitializationKind Kind
3355 = InitializationKind::CreateCopy(Loc, SourceLocation());
3356 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3357 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00003358
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003359 if (E1ToC1 && E2ToC1) {
3360 // Conversion to Composite1 is viable.
3361 if (!Context.hasSameType(Composite1, Composite2)) {
3362 // Composite2 is a different type from Composite1. Check whether
3363 // Composite2 is also viable.
3364 InitializedEntity Entity2
3365 = InitializedEntity::InitializeTemporary(Composite2);
3366 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3367 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3368 if (E1ToC2 && E2ToC2) {
3369 // Both Composite1 and Composite2 are viable and are different;
3370 // this is an ambiguity.
3371 return QualType();
3372 }
3373 }
3374
3375 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003376 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00003377 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003378 if (E1Result.isInvalid())
3379 return QualType();
3380 E1 = E1Result.takeAs<Expr>();
3381
3382 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003383 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00003384 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003385 if (E2Result.isInvalid())
3386 return QualType();
3387 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003388
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003389 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003390 }
3391
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003392 // Check whether Composite2 is viable.
3393 InitializedEntity Entity2
3394 = InitializedEntity::InitializeTemporary(Composite2);
3395 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3396 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3397 if (!E1ToC2 || !E2ToC2)
3398 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003399
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003400 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00003401 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00003402 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003403 if (E1Result.isInvalid())
3404 return QualType();
3405 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003406
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003407 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00003408 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00003409 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003410 if (E2Result.isInvalid())
3411 return QualType();
3412 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003413
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003414 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003415}
Anders Carlsson165a0a02009-05-17 18:41:29 +00003416
John McCall60d7b3a2010-08-24 06:29:42 +00003417ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00003418 if (!E)
3419 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003420
Anders Carlsson089c2602009-08-15 23:41:35 +00003421 if (!Context.getLangOptions().CPlusPlus)
3422 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003423
Douglas Gregor51326552009-12-24 18:51:59 +00003424 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
3425
Ted Kremenek6217b802009-07-29 21:53:49 +00003426 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00003427 if (!RT)
3428 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003429
Douglas Gregor5e6fcd42011-02-08 02:14:35 +00003430 // If the result is a glvalue, we shouldn't bind it.
3431 if (E->Classify(Context).isGLValue())
3432 return Owned(E);
John McCall86ff3082010-02-04 22:26:26 +00003433
3434 // That should be enough to guarantee that this type is complete.
3435 // If it has a trivial destructor, we can avoid the extra copy.
Jeffrey Yasskinb7ee2e52011-01-27 19:17:54 +00003436 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall507384f2010-08-12 02:40:37 +00003437 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00003438 return Owned(E);
3439
Douglas Gregordb89f282010-07-01 22:47:18 +00003440 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
Anders Carlsson860306e2009-05-30 21:21:49 +00003441 ExprTemporaries.push_back(Temp);
Douglas Gregordb89f282010-07-01 22:47:18 +00003442 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003443 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00003444 CheckDestructorAccess(E->getExprLoc(), Destructor,
3445 PDiag(diag::err_access_dtor_temp)
3446 << E->getType());
3447 }
Anders Carlssondef11992009-05-30 20:36:53 +00003448 // FIXME: Add the temporary to the temporaries vector.
3449 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
3450}
3451
John McCall4765fa02010-12-06 08:20:24 +00003452Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003453 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00003454
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003455 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3456 assert(ExprTemporaries.size() >= FirstTemporary);
3457 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003458 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003459
John McCall4765fa02010-12-06 08:20:24 +00003460 Expr *E = ExprWithCleanups::Create(Context, SubExpr,
3461 &ExprTemporaries[FirstTemporary],
3462 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003463 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
3464 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00003465
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003466 return E;
3467}
3468
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003469ExprResult
John McCall4765fa02010-12-06 08:20:24 +00003470Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00003471 if (SubExpr.isInvalid())
3472 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003473
John McCall4765fa02010-12-06 08:20:24 +00003474 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00003475}
3476
John McCall4765fa02010-12-06 08:20:24 +00003477Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003478 assert(SubStmt && "sub statement can't be null!");
3479
3480 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3481 assert(ExprTemporaries.size() >= FirstTemporary);
3482 if (ExprTemporaries.size() == FirstTemporary)
3483 return SubStmt;
3484
3485 // FIXME: In order to attach the temporaries, wrap the statement into
3486 // a StmtExpr; currently this is only used for asm statements.
3487 // This is hacky, either create a new CXXStmtWithTemporaries statement or
3488 // a new AsmStmtWithTemporaries.
3489 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
3490 SourceLocation(),
3491 SourceLocation());
3492 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
3493 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00003494 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003495}
3496
John McCall60d7b3a2010-08-24 06:29:42 +00003497ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003498Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00003499 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00003500 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003501 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003502 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003503 if (Result.isInvalid()) return ExprError();
3504 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003505
John McCall9ae2f072010-08-23 23:25:46 +00003506 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00003507 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003508 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00003509 // If we have a pointer to a dependent type and are using the -> operator,
3510 // the object type is the type that the pointer points to. We might still
3511 // have enough information about that type to do something useful.
3512 if (OpKind == tok::arrow)
3513 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3514 BaseType = Ptr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003515
John McCallb3d87482010-08-24 05:47:05 +00003516 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00003517 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00003518 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003519 }
Mike Stump1eb44332009-09-09 15:08:12 +00003520
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003521 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00003522 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003523 // returned, with the original second operand.
3524 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00003525 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00003526 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00003527 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00003528 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003529
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003530 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00003531 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
3532 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003533 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00003534 Base = Result.get();
3535 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00003536 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00003537 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00003538 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00003539 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003540 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00003541 for (unsigned i = 0; i < Locations.size(); i++)
3542 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003543 return ExprError();
3544 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003545 }
Mike Stump1eb44332009-09-09 15:08:12 +00003546
Douglas Gregor31658df2009-11-20 19:58:21 +00003547 if (BaseType->isPointerType())
3548 BaseType = BaseType->getPointeeType();
3549 }
Mike Stump1eb44332009-09-09 15:08:12 +00003550
3551 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003552 // vector types or Objective-C interfaces. Just return early and let
3553 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00003554 if (!BaseType->isRecordType()) {
3555 // C++ [basic.lookup.classref]p2:
3556 // [...] If the type of the object expression is of pointer to scalar
3557 // type, the unqualified-id is looked up in the context of the complete
3558 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00003559 //
3560 // This also indicates that we should be parsing a
3561 // pseudo-destructor-name.
John McCallb3d87482010-08-24 05:47:05 +00003562 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00003563 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00003564 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00003565 }
Mike Stump1eb44332009-09-09 15:08:12 +00003566
Douglas Gregor03c57052009-11-17 05:17:33 +00003567 // The object type must be complete (or dependent).
3568 if (!BaseType->isDependentType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003569 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor03c57052009-11-17 05:17:33 +00003570 PDiag(diag::err_incomplete_member_access)))
3571 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003572
Douglas Gregorc68afe22009-09-03 21:38:09 +00003573 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00003574 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00003575 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00003576 // type C (or of pointer to a class type C), the unqualified-id is looked
3577 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00003578 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00003579 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003580}
3581
John McCall60d7b3a2010-08-24 06:29:42 +00003582ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003583 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00003584 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00003585 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
3586 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00003587 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003588
Douglas Gregor77549082010-02-24 21:29:12 +00003589 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00003590 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00003591 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00003592 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00003593 /*RPLoc*/ ExpectedLParenLoc);
3594}
Douglas Gregord4dca082010-02-24 18:44:31 +00003595
John McCall60d7b3a2010-08-24 06:29:42 +00003596ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00003597 SourceLocation OpLoc,
3598 tok::TokenKind OpKind,
3599 const CXXScopeSpec &SS,
3600 TypeSourceInfo *ScopeTypeInfo,
3601 SourceLocation CCLoc,
3602 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003603 PseudoDestructorTypeStorage Destructed,
John McCall2d9f5fa2011-02-25 05:21:17 +00003604 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003605 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003606
Douglas Gregorb57fb492010-02-24 22:38:50 +00003607 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003608 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregorb57fb492010-02-24 22:38:50 +00003609 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003610 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00003611 QualType ObjectType = Base->getType();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003612 if (OpKind == tok::arrow) {
3613 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3614 ObjectType = Ptr->getPointeeType();
John McCall9ae2f072010-08-23 23:25:46 +00003615 } else if (!Base->isTypeDependent()) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003616 // The user wrote "p->" when she probably meant "p."; fix it.
3617 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3618 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00003619 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00003620 if (isSFINAEContext())
3621 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003622
Douglas Gregorb57fb492010-02-24 22:38:50 +00003623 OpKind = tok::period;
3624 }
3625 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003626
Douglas Gregorb57fb492010-02-24 22:38:50 +00003627 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
3628 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCall9ae2f072010-08-23 23:25:46 +00003629 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003630 return ExprError();
3631 }
3632
3633 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003634 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb57fb492010-02-24 22:38:50 +00003635 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003636 if (DestructedTypeInfo) {
3637 QualType DestructedType = DestructedTypeInfo->getType();
3638 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003639 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003640 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
3641 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
3642 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00003643 << ObjectType << DestructedType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003644 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003645
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003646 // Recover by setting the destructed type to the object type.
3647 DestructedType = ObjectType;
3648 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
3649 DestructedTypeStart);
3650 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3651 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00003652 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003653
Douglas Gregorb57fb492010-02-24 22:38:50 +00003654 // C++ [expr.pseudo]p2:
3655 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
3656 // form
3657 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003658 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb57fb492010-02-24 22:38:50 +00003659 //
3660 // shall designate the same scalar type.
3661 if (ScopeTypeInfo) {
3662 QualType ScopeType = ScopeTypeInfo->getType();
3663 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00003664 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003665
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003666 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00003667 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00003668 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003669 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003670
Douglas Gregorb57fb492010-02-24 22:38:50 +00003671 ScopeType = QualType();
3672 ScopeTypeInfo = 0;
3673 }
3674 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003675
John McCall9ae2f072010-08-23 23:25:46 +00003676 Expr *Result
3677 = new (Context) CXXPseudoDestructorExpr(Context, Base,
3678 OpKind == tok::arrow, OpLoc,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00003679 SS.getWithLocInContext(Context),
John McCall9ae2f072010-08-23 23:25:46 +00003680 ScopeTypeInfo,
3681 CCLoc,
3682 TildeLoc,
3683 Destructed);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003684
Douglas Gregorb57fb492010-02-24 22:38:50 +00003685 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00003686 return Owned(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003687
John McCall9ae2f072010-08-23 23:25:46 +00003688 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00003689}
3690
John McCall60d7b3a2010-08-24 06:29:42 +00003691ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00003692 SourceLocation OpLoc,
3693 tok::TokenKind OpKind,
3694 CXXScopeSpec &SS,
3695 UnqualifiedId &FirstTypeName,
3696 SourceLocation CCLoc,
3697 SourceLocation TildeLoc,
3698 UnqualifiedId &SecondTypeName,
3699 bool HasTrailingLParen) {
Douglas Gregor77549082010-02-24 21:29:12 +00003700 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3701 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3702 "Invalid first type name in pseudo-destructor");
3703 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3704 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3705 "Invalid second type name in pseudo-destructor");
3706
Douglas Gregor77549082010-02-24 21:29:12 +00003707 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003708 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregor77549082010-02-24 21:29:12 +00003709 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003710 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00003711 QualType ObjectType = Base->getType();
Douglas Gregor77549082010-02-24 21:29:12 +00003712 if (OpKind == tok::arrow) {
3713 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3714 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003715 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00003716 // The user wrote "p->" when she probably meant "p."; fix it.
3717 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003718 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00003719 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00003720 if (isSFINAEContext())
3721 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003722
Douglas Gregor77549082010-02-24 21:29:12 +00003723 OpKind = tok::period;
3724 }
3725 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003726
3727 // Compute the object type that we should use for name lookup purposes. Only
3728 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00003729 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003730 if (!SS.isSet()) {
John McCall2d9f5fa2011-02-25 05:21:17 +00003731 if (ObjectType->isRecordType())
3732 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallb3d87482010-08-24 05:47:05 +00003733 else if (ObjectType->isDependentType())
3734 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003735 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003736
3737 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb57fb492010-02-24 22:38:50 +00003738 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00003739 QualType DestructedType;
3740 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003741 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00003742 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003743 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00003744 SecondTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00003745 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003746 if (!T &&
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003747 ((SS.isSet() && !computeDeclContext(SS, false)) ||
3748 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003749 // The name of the type being destroyed is a dependent name, and we
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003750 // couldn't find anything useful in scope. Just store the identifier and
3751 // it's location, and we'll perform (qualified) name lookup again at
3752 // template instantiation time.
3753 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
3754 SecondTypeName.StartLocation);
3755 } else if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003756 Diag(SecondTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00003757 diag::err_pseudo_dtor_destructor_non_type)
3758 << SecondTypeName.Identifier << ObjectType;
3759 if (isSFINAEContext())
3760 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003761
Douglas Gregor77549082010-02-24 21:29:12 +00003762 // Recover by assuming we had the right type all along.
3763 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003764 } else
Douglas Gregor77549082010-02-24 21:29:12 +00003765 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003766 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003767 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003768 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003769 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3770 TemplateId->getTemplateArgs(),
3771 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00003772 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
3773 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003774 TemplateId->TemplateNameLoc,
3775 TemplateId->LAngleLoc,
3776 TemplateArgsPtr,
3777 TemplateId->RAngleLoc);
3778 if (T.isInvalid() || !T.get()) {
3779 // Recover by assuming we had the right type all along.
3780 DestructedType = ObjectType;
3781 } else
3782 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003783 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003784
3785 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb57fb492010-02-24 22:38:50 +00003786 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003787 if (!DestructedType.isNull()) {
3788 if (!DestructedTypeInfo)
3789 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003790 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003791 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3792 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003793
Douglas Gregorb57fb492010-02-24 22:38:50 +00003794 // Convert the name of the scope type (the type prior to '::') into a type.
3795 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00003796 QualType ScopeType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003797 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor77549082010-02-24 21:29:12 +00003798 FirstTypeName.Identifier) {
3799 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003800 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00003801 FirstTypeName.StartLocation,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00003802 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00003803 if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003804 Diag(FirstTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00003805 diag::err_pseudo_dtor_destructor_non_type)
3806 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003807
Douglas Gregorb57fb492010-02-24 22:38:50 +00003808 if (isSFINAEContext())
3809 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003810
Douglas Gregorb57fb492010-02-24 22:38:50 +00003811 // Just drop this type. It's unnecessary anyway.
3812 ScopeType = QualType();
3813 } else
3814 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003815 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003816 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00003817 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00003818 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3819 TemplateId->getTemplateArgs(),
3820 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00003821 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
3822 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00003823 TemplateId->TemplateNameLoc,
3824 TemplateId->LAngleLoc,
3825 TemplateArgsPtr,
3826 TemplateId->RAngleLoc);
3827 if (T.isInvalid() || !T.get()) {
3828 // Recover by dropping this type.
3829 ScopeType = QualType();
3830 } else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003831 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00003832 }
3833 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003834
Douglas Gregorb4a418f2010-02-24 23:02:30 +00003835 if (!ScopeType.isNull() && !ScopeTypeInfo)
3836 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3837 FirstTypeName.StartLocation);
3838
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003839
John McCall9ae2f072010-08-23 23:25:46 +00003840 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00003841 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003842 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00003843}
3844
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003845ExprResult Sema::BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
3846 CXXMethodDecl *Method) {
John McCall6bb80172010-03-30 21:47:33 +00003847 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3848 FoundDecl, Method))
Douglas Gregorf2ae5262011-01-20 00:18:04 +00003849 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00003850
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003851 MemberExpr *ME =
Abramo Bagnara25777432010-08-11 22:01:17 +00003852 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
John McCallf89e55a2010-11-18 06:31:45 +00003853 SourceLocation(), Method->getType(),
3854 VK_RValue, OK_Ordinary);
3855 QualType ResultType = Method->getResultType();
3856 ExprValueKind VK = Expr::getValueKindForType(ResultType);
3857 ResultType = ResultType.getNonLValueExprType(Context);
3858
Douglas Gregor7edfb692009-11-23 12:27:39 +00003859 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3860 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00003861 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
Douglas Gregor7edfb692009-11-23 12:27:39 +00003862 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00003863 return CE;
3864}
3865
Sebastian Redl2e156222010-09-10 20:55:43 +00003866ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
3867 SourceLocation RParen) {
Sebastian Redl2e156222010-09-10 20:55:43 +00003868 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
3869 Operand->CanThrow(Context),
3870 KeyLoc, RParen));
3871}
3872
3873ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
3874 Expr *Operand, SourceLocation RParen) {
3875 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00003876}
3877
John McCallf6a16482010-12-04 03:47:34 +00003878/// Perform the conversions required for an expression used in a
3879/// context that ignores the result.
3880void Sema::IgnoredValueConversions(Expr *&E) {
John McCalla878cda2010-12-02 02:07:15 +00003881 // C99 6.3.2.1:
3882 // [Except in specific positions,] an lvalue that does not have
3883 // array type is converted to the value stored in the
3884 // designated object (and is no longer an lvalue).
John McCallf6a16482010-12-04 03:47:34 +00003885 if (E->isRValue()) return;
John McCalla878cda2010-12-02 02:07:15 +00003886
John McCallf6a16482010-12-04 03:47:34 +00003887 // We always want to do this on ObjC property references.
3888 if (E->getObjectKind() == OK_ObjCProperty) {
3889 ConvertPropertyForRValue(E);
3890 if (E->isRValue()) return;
3891 }
3892
3893 // Otherwise, this rule does not apply in C++, at least not for the moment.
3894 if (getLangOptions().CPlusPlus) return;
3895
3896 // GCC seems to also exclude expressions of incomplete enum type.
3897 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
3898 if (!T->getDecl()->isComplete()) {
3899 // FIXME: stupid workaround for a codegen bug!
3900 ImpCastExprToType(E, Context.VoidTy, CK_ToVoid);
3901 return;
3902 }
3903 }
3904
3905 DefaultFunctionArrayLvalueConversion(E);
John McCall85515d62010-12-04 12:29:11 +00003906 if (!E->getType()->isVoidType())
3907 RequireCompleteType(E->getExprLoc(), E->getType(),
3908 diag::err_incomplete_type);
John McCallf6a16482010-12-04 03:47:34 +00003909}
3910
3911ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003912 if (!FullExpr)
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003913 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00003914
Douglas Gregord0937222010-12-13 22:49:22 +00003915 if (DiagnoseUnexpandedParameterPack(FullExpr))
3916 return ExprError();
3917
Douglas Gregor353ee242011-03-07 02:05:23 +00003918 // 13.4.1 ... An overloaded function name shall not be used without arguments
3919 // in contexts other than those listed [i.e list of targets].
3920 //
3921 // void foo(); void foo(int);
3922 // template<class T> void fooT(); template<class T> void fooT(int);
3923
3924 // Therefore these should error:
3925 // foo;
3926 // fooT<int>;
3927
3928 if (FullExpr->getType() == Context.OverloadTy) {
3929 if (!ResolveSingleFunctionTemplateSpecialization(FullExpr,
3930 /* Complain */ false)) {
3931 OverloadExpr* OvlExpr = OverloadExpr::find(FullExpr).Expression;
3932 Diag(FullExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
3933 << OvlExpr->getName();
3934 NoteAllOverloadCandidates(OvlExpr);
3935 return ExprError();
3936 }
3937 }
3938
3939
John McCallf6a16482010-12-04 03:47:34 +00003940 IgnoredValueConversions(FullExpr);
John McCallb4eb64d2010-10-08 02:01:28 +00003941 CheckImplicitConversions(FullExpr);
Douglas Gregor353ee242011-03-07 02:05:23 +00003942
John McCall4765fa02010-12-06 08:20:24 +00003943 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00003944}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003945
3946StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
3947 if (!FullStmt) return StmtError();
3948
John McCall4765fa02010-12-06 08:20:24 +00003949 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003950}