blob: 98f96bc68daa053df5adbd17ff1fa57adc1a4efb [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"
Richard Smith7a614d82011-06-11 17:19:42 +000020#include "clang/Sema/Scope.h"
John McCall2a7fb272010-08-25 05:32:35 +000021#include "clang/Sema/TemplateDeduction.h"
Steve Naroff210679c2007-08-25 14:02:58 +000022#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000024#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000025#include "clang/AST/ExprCXX.h"
Fariborz Jahaniand4266622010-06-16 18:56:04 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregorb57fb492010-02-24 22:38:50 +000027#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000029#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000030#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Chandler Carruth73e0a912011-05-01 07:23:17 +000032#include "llvm/Support/ErrorHandling.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000034using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000035
John McCallb3d87482010-08-24 05:47:05 +000036ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000037 IdentifierInfo &II,
John McCallb3d87482010-08-24 05:47:05 +000038 SourceLocation NameLoc,
39 Scope *S, CXXScopeSpec &SS,
40 ParsedType ObjectTypePtr,
41 bool EnteringContext) {
Douglas Gregor124b8782010-02-16 19:09:40 +000042 // Determine where to perform name lookup.
43
44 // FIXME: This area of the standard is very messy, and the current
45 // wording is rather unclear about which scopes we search for the
46 // destructor name; see core issues 399 and 555. Issue 399 in
47 // particular shows where the current description of destructor name
48 // lookup is completely out of line with existing practice, e.g.,
49 // this appears to be ill-formed:
50 //
51 // namespace N {
52 // template <typename T> struct S {
53 // ~S();
54 // };
55 // }
56 //
57 // void f(N::S<int>* s) {
58 // s->N::S<int>::~S();
59 // }
60 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000061 // See also PR6358 and PR6359.
Sebastian Redlc0fee502010-07-07 23:17:38 +000062 // For this reason, we're currently only doing the C++03 version of this
63 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregor124b8782010-02-16 19:09:40 +000064 QualType SearchType;
65 DeclContext *LookupCtx = 0;
66 bool isDependent = false;
67 bool LookInScope = false;
68
69 // If we have an object type, it's because we are in a
70 // pseudo-destructor-expression or a member access expression, and
71 // we know what type we're looking for.
72 if (ObjectTypePtr)
73 SearchType = GetTypeFromParser(ObjectTypePtr);
74
75 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000076 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000077
Douglas Gregor93649fd2010-02-23 00:15:22 +000078 bool AlreadySearched = false;
79 bool LookAtPrefix = true;
Sebastian Redlc0fee502010-07-07 23:17:38 +000080 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000081 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redlc0fee502010-07-07 23:17:38 +000082 // the type-names are looked up as types in the scope designated by the
83 // nested-name-specifier. In a qualified-id of the form:
NAKAMURA Takumi00995302011-01-27 07:09:49 +000084 //
85 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redlc0fee502010-07-07 23:17:38 +000086 //
87 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth5e895a82010-02-21 10:19:54 +000088 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +000089 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +000090 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregor124b8782010-02-16 19:09:40 +000091 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000092 // the class-names are looked up as types in the scope designated by
Sebastian Redlc0fee502010-07-07 23:17:38 +000093 // the nested-name-specifier.
Douglas Gregor124b8782010-02-16 19:09:40 +000094 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000095 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000096 // code below is permitted to look at the prefix of the
Sebastian Redlc0fee502010-07-07 23:17:38 +000097 // nested-name-specifier.
98 DeclContext *DC = computeDeclContext(SS, EnteringContext);
99 if (DC && DC->isFileContext()) {
100 AlreadySearched = true;
101 LookupCtx = DC;
102 isDependent = false;
103 } else if (DC && isa<CXXRecordDecl>(DC))
104 LookAtPrefix = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000105
Sebastian Redlc0fee502010-07-07 23:17:38 +0000106 // The second case from the C++03 rules quoted further above.
Douglas Gregor93649fd2010-02-23 00:15:22 +0000107 NestedNameSpecifier *Prefix = 0;
108 if (AlreadySearched) {
109 // Nothing left to do.
110 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
111 CXXScopeSpec PrefixSS;
Douglas Gregor7e384942011-02-25 16:07:42 +0000112 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor93649fd2010-02-23 00:15:22 +0000113 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
114 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000115 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000116 LookupCtx = computeDeclContext(SearchType);
117 isDependent = SearchType->isDependentType();
118 } else {
119 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000120 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000121 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000122
Douglas Gregoredc90502010-02-25 04:46:04 +0000123 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000124 } else if (ObjectTypePtr) {
125 // C++ [basic.lookup.classref]p3:
126 // If the unqualified-id is ~type-name, the type-name is looked up
127 // in the context of the entire postfix-expression. If the type T
128 // of the object expression is of a class type C, the type-name is
129 // also looked up in the scope of class C. At least one of the
130 // lookups shall find a name that refers to (possibly
131 // cv-qualified) T.
132 LookupCtx = computeDeclContext(SearchType);
133 isDependent = SearchType->isDependentType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000134 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregor124b8782010-02-16 19:09:40 +0000135 "Caller should have completed object type");
136
137 LookInScope = true;
138 } else {
139 // Perform lookup into the current scope (only).
140 LookInScope = true;
141 }
142
Douglas Gregor7ec18732011-03-04 22:32:08 +0000143 TypeDecl *NonMatchingTypeDecl = 0;
Douglas Gregor124b8782010-02-16 19:09:40 +0000144 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
145 for (unsigned Step = 0; Step != 2; ++Step) {
146 // Look for the name first in the computed lookup context (if we
Douglas Gregor7ec18732011-03-04 22:32:08 +0000147 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregor124b8782010-02-16 19:09:40 +0000148 // we're allowed to look there).
149 Found.clear();
150 if (Step == 0 && LookupCtx)
151 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000152 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000153 LookupName(Found, S);
154 else
155 continue;
156
157 // FIXME: Should we be suppressing ambiguities here?
158 if (Found.isAmbiguous())
John McCallb3d87482010-08-24 05:47:05 +0000159 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000160
161 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
162 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000163
164 if (SearchType.isNull() || SearchType->isDependentType() ||
165 Context.hasSameUnqualifiedType(T, SearchType)) {
166 // We found our type!
167
John McCallb3d87482010-08-24 05:47:05 +0000168 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000169 }
John Wiegley36784e72011-03-08 08:13:22 +0000170
Douglas Gregor7ec18732011-03-04 22:32:08 +0000171 if (!SearchType.isNull())
172 NonMatchingTypeDecl = Type;
Douglas Gregor124b8782010-02-16 19:09:40 +0000173 }
174
175 // If the name that we found is a class template name, and it is
176 // the same name as the template name in the last part of the
177 // nested-name-specifier (if present) or the object type, then
178 // this is the destructor for that class.
179 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000180 // issue 399, for which there isn't even an obvious direction.
Douglas Gregor124b8782010-02-16 19:09:40 +0000181 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
182 QualType MemberOfType;
183 if (SS.isSet()) {
184 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
185 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000186 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
187 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000188 }
189 }
190 if (MemberOfType.isNull())
191 MemberOfType = SearchType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000192
Douglas Gregor124b8782010-02-16 19:09:40 +0000193 if (MemberOfType.isNull())
194 continue;
195
196 // We're referring into a class template specialization. If the
197 // class template we found is the same as the template being
198 // specialized, we found what we are looking for.
199 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
200 if (ClassTemplateSpecializationDecl *Spec
201 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
202 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
203 Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000204 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000205 }
206
207 continue;
208 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000209
Douglas Gregor124b8782010-02-16 19:09:40 +0000210 // We're referring to an unresolved class template
211 // specialization. Determine whether we class template we found
212 // is the same as the template being specialized or, if we don't
213 // know which template is being specialized, that it at least
214 // has the same name.
215 if (const TemplateSpecializationType *SpecType
216 = MemberOfType->getAs<TemplateSpecializationType>()) {
217 TemplateName SpecName = SpecType->getTemplateName();
218
219 // The class template we found is the same template being
220 // specialized.
221 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
222 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000223 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000224
225 continue;
226 }
227
228 // The class template we found has the same name as the
229 // (dependent) template name being specialized.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000230 if (DependentTemplateName *DepTemplate
Douglas Gregor124b8782010-02-16 19:09:40 +0000231 = SpecName.getAsDependentTemplateName()) {
232 if (DepTemplate->isIdentifier() &&
233 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallb3d87482010-08-24 05:47:05 +0000234 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000235
236 continue;
237 }
238 }
239 }
240 }
241
242 if (isDependent) {
243 // We didn't find our type, but that's okay: it's dependent
244 // anyway.
Douglas Gregore29425b2011-02-28 22:42:13 +0000245
246 // FIXME: What if we have no nested-name-specifier?
247 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
248 SS.getWithLocInContext(Context),
249 II, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000250 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000251 }
252
Douglas Gregor7ec18732011-03-04 22:32:08 +0000253 if (NonMatchingTypeDecl) {
254 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
255 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
256 << T << SearchType;
257 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
258 << T;
259 } else if (ObjectTypePtr)
260 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000261 << &II;
Douglas Gregor124b8782010-02-16 19:09:40 +0000262 else
263 Diag(NameLoc, diag::err_destructor_class_name);
264
John McCallb3d87482010-08-24 05:47:05 +0000265 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000266}
267
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000268/// \brief Build a C++ typeid expression with a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000269ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000270 SourceLocation TypeidLoc,
271 TypeSourceInfo *Operand,
272 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000273 // C++ [expr.typeid]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000274 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000275 // that is the operand of typeid are always ignored.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000276 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000277 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000278 Qualifiers Quals;
279 QualType T
280 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
281 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000282 if (T->getAs<RecordType>() &&
283 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
284 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000285
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000286 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
287 Operand,
288 SourceRange(TypeidLoc, RParenLoc)));
289}
290
291/// \brief Build a C++ typeid expression with an expression operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000292ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000293 SourceLocation TypeidLoc,
294 Expr *E,
295 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000296 bool isUnevaluatedOperand = true;
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000297 if (E && !E->isTypeDependent()) {
298 QualType T = E->getType();
299 if (const RecordType *RecordT = T->getAs<RecordType>()) {
300 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
301 // C++ [expr.typeid]p3:
302 // [...] If the type of the expression is a class type, the class
303 // shall be completely-defined.
304 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
305 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000306
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000307 // C++ [expr.typeid]p3:
Sebastian Redl906082e2010-07-20 04:20:21 +0000308 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000309 // polymorphic class type [...] [the] expression is an unevaluated
310 // operand. [...]
Sebastian Redl906082e2010-07-20 04:20:21 +0000311 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000312 isUnevaluatedOperand = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000313
314 // We require a vtable to query the type at run time.
315 MarkVTableUsed(TypeidLoc, RecordD);
316 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000317 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000318
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000319 // C++ [expr.typeid]p4:
320 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000321 // cv-qualified type, the result of the typeid expression refers to a
322 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000323 // type.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000324 Qualifiers Quals;
325 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
326 if (!Context.hasSameType(T, UnqualT)) {
327 T = UnqualT;
John Wiegley429bb272011-04-08 18:41:53 +0000328 E = ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E)).take();
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000329 }
330 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000331
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000332 // If this is an unevaluated operand, clear out the set of
333 // declaration references we have been computing and eliminate any
334 // temporaries introduced in its computation.
335 if (isUnevaluatedOperand)
336 ExprEvalContexts.back().Context = Unevaluated;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000337
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000338 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCall9ae2f072010-08-23 23:25:46 +0000339 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000340 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000341}
342
343/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCall60d7b3a2010-08-24 06:29:42 +0000344ExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000345Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
346 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000347 // Find the std::type_info type.
Sebastian Redlce0682f2011-03-31 19:29:24 +0000348 if (!getStdNamespace())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000349 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000350
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000351 if (!CXXTypeInfoDecl) {
352 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
353 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
354 LookupQualifiedName(R, getStdNamespace());
355 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
356 if (!CXXTypeInfoDecl)
357 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
358 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000359
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000360 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000361
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000362 if (isType) {
363 // The operand is a type; handle it as such.
364 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +0000365 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
366 &TInfo);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000367 if (T.isNull())
368 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000369
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000370 if (!TInfo)
371 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000372
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000373 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000374 }
Mike Stump1eb44332009-09-09 15:08:12 +0000375
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000376 // The operand is an expression.
John McCall9ae2f072010-08-23 23:25:46 +0000377 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000378}
379
Francois Pichet6915c522010-12-27 01:32:00 +0000380/// Retrieve the UuidAttr associated with QT.
381static UuidAttr *GetUuidAttrOfType(QualType QT) {
382 // Optionally remove one level of pointer, reference or array indirection.
John McCallf4c73712011-01-19 06:33:43 +0000383 const Type *Ty = QT.getTypePtr();;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000384 if (QT->isPointerType() || QT->isReferenceType())
385 Ty = QT->getPointeeType().getTypePtr();
386 else if (QT->isArrayType())
387 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
388
Francois Pichet8db75a22011-05-08 10:02:20 +0000389 // Loop all record redeclaration looking for an uuid attribute.
Francois Pichet6915c522010-12-27 01:32:00 +0000390 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Francois Pichet8db75a22011-05-08 10:02:20 +0000391 for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(),
392 E = RD->redecls_end(); I != E; ++I) {
393 if (UuidAttr *Uuid = I->getAttr<UuidAttr>())
Francois Pichet6915c522010-12-27 01:32:00 +0000394 return Uuid;
Francois Pichet6915c522010-12-27 01:32:00 +0000395 }
Francois Pichet8db75a22011-05-08 10:02:20 +0000396
Francois Pichet6915c522010-12-27 01:32:00 +0000397 return 0;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000398}
399
Francois Pichet01b7c302010-09-08 12:20:18 +0000400/// \brief Build a Microsoft __uuidof expression with a type operand.
401ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
402 SourceLocation TypeidLoc,
403 TypeSourceInfo *Operand,
404 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000405 if (!Operand->getType()->isDependentType()) {
406 if (!GetUuidAttrOfType(Operand->getType()))
407 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
408 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000409
Francois Pichet01b7c302010-09-08 12:20:18 +0000410 // FIXME: add __uuidof semantic analysis for type operand.
411 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
412 Operand,
413 SourceRange(TypeidLoc, RParenLoc)));
414}
415
416/// \brief Build a Microsoft __uuidof expression with an expression operand.
417ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
418 SourceLocation TypeidLoc,
419 Expr *E,
420 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000421 if (!E->getType()->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000422 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichet6915c522010-12-27 01:32:00 +0000423 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
424 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
425 }
426 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet01b7c302010-09-08 12:20:18 +0000427 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
428 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000429 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet01b7c302010-09-08 12:20:18 +0000430}
431
432/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
433ExprResult
434Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
435 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000436 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet01b7c302010-09-08 12:20:18 +0000437 if (!MSVCGuidDecl) {
438 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
439 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
440 LookupQualifiedName(R, Context.getTranslationUnitDecl());
441 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
442 if (!MSVCGuidDecl)
443 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000444 }
445
Francois Pichet01b7c302010-09-08 12:20:18 +0000446 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000447
Francois Pichet01b7c302010-09-08 12:20:18 +0000448 if (isType) {
449 // The operand is a type; handle it as such.
450 TypeSourceInfo *TInfo = 0;
451 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
452 &TInfo);
453 if (T.isNull())
454 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000455
Francois Pichet01b7c302010-09-08 12:20:18 +0000456 if (!TInfo)
457 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
458
459 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
460 }
461
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000462 // The operand is an expression.
Francois Pichet01b7c302010-09-08 12:20:18 +0000463 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
464}
465
Steve Naroff1b273c42007-09-16 14:56:35 +0000466/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCall60d7b3a2010-08-24 06:29:42 +0000467ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000468Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000469 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000470 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000471 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
472 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000473}
Chris Lattner50dd2892008-02-26 00:51:44 +0000474
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000475/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCall60d7b3a2010-08-24 06:29:42 +0000476ExprResult
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000477Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
478 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
479}
480
Chris Lattner50dd2892008-02-26 00:51:44 +0000481/// ActOnCXXThrow - Parse throw expressions.
John McCall60d7b3a2010-08-24 06:29:42 +0000482ExprResult
Douglas Gregorbca01b42011-07-06 22:04:06 +0000483Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
484 bool IsThrownVarInScope = false;
485 if (Ex) {
486 // C++0x [class.copymove]p31:
487 // When certain criteria are met, an implementation is allowed to omit the
488 // copy/move construction of a class object [...]
489 //
490 // - in a throw-expression, when the operand is the name of a
491 // non-volatile automatic object (other than a function or catch-
492 // clause parameter) whose scope does not extend beyond the end of the
493 // innermost enclosing try-block (if there is one), the copy/move
494 // operation from the operand to the exception object (15.1) can be
495 // omitted by constructing the automatic object directly into the
496 // exception object
497 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
498 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
499 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
500 for( ; S; S = S->getParent()) {
501 if (S->isDeclScope(Var)) {
502 IsThrownVarInScope = true;
503 break;
504 }
505
506 if (S->getFlags() &
507 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
508 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
509 Scope::TryScope))
510 break;
511 }
512 }
513 }
514 }
515
516 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
517}
518
519ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
520 bool IsThrownVarInScope) {
Anders Carlsson729b8532011-02-23 03:46:46 +0000521 // Don't report an error if 'throw' is used in system headers.
Anders Carlsson15348ae2011-02-28 02:27:16 +0000522 if (!getLangOptions().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +0000523 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb1fba312011-02-19 21:53:09 +0000524 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Douglas Gregorbca01b42011-07-06 22:04:06 +0000525
John Wiegley429bb272011-04-08 18:41:53 +0000526 if (Ex && !Ex->isTypeDependent()) {
Douglas Gregorbca01b42011-07-06 22:04:06 +0000527 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
John Wiegley429bb272011-04-08 18:41:53 +0000528 if (ExRes.isInvalid())
529 return ExprError();
530 Ex = ExRes.take();
531 }
Douglas Gregorbca01b42011-07-06 22:04:06 +0000532
533 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
534 IsThrownVarInScope));
Sebastian Redl972041f2009-04-27 20:27:31 +0000535}
536
537/// CheckCXXThrowOperand - Validate the operand of a throw.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000538ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
539 bool IsThrownVarInScope) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000540 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000541 // A throw-expression initializes a temporary object, called the exception
542 // object, the type of which is determined by removing any top-level
543 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000544 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor154fe982009-12-23 22:04:40 +0000545 // or "pointer to function returning T", [...]
546 if (E->getType().hasQualifiers())
John Wiegley429bb272011-04-08 18:41:53 +0000547 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
548 CastCategory(E)).take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000549
John Wiegley429bb272011-04-08 18:41:53 +0000550 ExprResult Res = DefaultFunctionArrayConversion(E);
551 if (Res.isInvalid())
552 return ExprError();
553 E = Res.take();
Sebastian Redl972041f2009-04-27 20:27:31 +0000554
555 // If the type of the exception would be an incomplete type or a pointer
556 // to an incomplete type other than (cv) void the program is ill-formed.
557 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000558 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000559 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000560 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000561 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000562 }
563 if (!isPointer || !Ty->isVoidType()) {
564 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000565 PDiag(isPointer ? diag::err_throw_incomplete_ptr
566 : diag::err_throw_incomplete)
567 << E->getSourceRange()))
John Wiegley429bb272011-04-08 18:41:53 +0000568 return ExprError();
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000569
Douglas Gregorbf422f92010-04-15 18:05:39 +0000570 if (RequireNonAbstractType(ThrowLoc, E->getType(),
571 PDiag(diag::err_throw_abstract_type)
572 << E->getSourceRange()))
John Wiegley429bb272011-04-08 18:41:53 +0000573 return ExprError();
Sebastian Redl972041f2009-04-27 20:27:31 +0000574 }
575
John McCallac418162010-04-22 01:10:34 +0000576 // Initialize the exception result. This implicitly weeds out
577 // abstract types or types with inaccessible copy constructors.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000578
579 // C++0x [class.copymove]p31:
580 // When certain criteria are met, an implementation is allowed to omit the
581 // copy/move construction of a class object [...]
582 //
583 // - in a throw-expression, when the operand is the name of a
584 // non-volatile automatic object (other than a function or catch-clause
585 // parameter) whose scope does not extend beyond the end of the
586 // innermost enclosing try-block (if there is one), the copy/move
587 // operation from the operand to the exception object (15.1) can be
588 // omitted by constructing the automatic object directly into the
589 // exception object
590 const VarDecl *NRVOVariable = 0;
591 if (IsThrownVarInScope)
592 NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
593
John McCallac418162010-04-22 01:10:34 +0000594 InitializedEntity Entity =
Douglas Gregor72dfa272011-01-21 22:46:35 +0000595 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
Douglas Gregorbca01b42011-07-06 22:04:06 +0000596 /*NRVO=*/NRVOVariable != 0);
John Wiegley429bb272011-04-08 18:41:53 +0000597 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregorbca01b42011-07-06 22:04:06 +0000598 QualType(), E,
599 IsThrownVarInScope);
John McCallac418162010-04-22 01:10:34 +0000600 if (Res.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000601 return ExprError();
602 E = Res.take();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000603
Eli Friedman5ed9b932010-06-03 20:39:03 +0000604 // If the exception has class type, we need additional handling.
605 const RecordType *RecordTy = Ty->getAs<RecordType>();
606 if (!RecordTy)
John Wiegley429bb272011-04-08 18:41:53 +0000607 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000608 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
609
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000610 // If we are throwing a polymorphic class type or pointer thereof,
611 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000612 MarkVTableUsed(ThrowLoc, RD);
613
Eli Friedman98efb9f2010-10-12 20:32:36 +0000614 // If a pointer is thrown, the referenced object will not be destroyed.
615 if (isPointer)
John Wiegley429bb272011-04-08 18:41:53 +0000616 return Owned(E);
Eli Friedman98efb9f2010-10-12 20:32:36 +0000617
Eli Friedman5ed9b932010-06-03 20:39:03 +0000618 // If the class has a non-trivial destructor, we must be able to call it.
619 if (RD->hasTrivialDestructor())
John Wiegley429bb272011-04-08 18:41:53 +0000620 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000621
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000622 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +0000623 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman5ed9b932010-06-03 20:39:03 +0000624 if (!Destructor)
John Wiegley429bb272011-04-08 18:41:53 +0000625 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000626
627 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
628 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000629 PDiag(diag::err_access_dtor_exception) << Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000630 return Owned(E);
Chris Lattner50dd2892008-02-26 00:51:44 +0000631}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000632
Richard Smith7a614d82011-06-11 17:19:42 +0000633QualType Sema::getAndCaptureCurrentThisType() {
John McCall5808ce42011-02-03 08:15:49 +0000634 // Ignore block scopes: we can capture through them.
635 // Ignore nested enum scopes: we'll diagnose non-constant expressions
636 // where they're invalid, and other uses are legitimate.
637 // Don't ignore nested class scopes: you can't use 'this' in a local class.
John McCall469a1eb2011-02-02 13:00:07 +0000638 DeclContext *DC = CurContext;
Richard Smith7a614d82011-06-11 17:19:42 +0000639 unsigned NumBlocks = 0;
John McCall5808ce42011-02-03 08:15:49 +0000640 while (true) {
Richard Smith7a614d82011-06-11 17:19:42 +0000641 if (isa<BlockDecl>(DC)) {
642 DC = cast<BlockDecl>(DC)->getDeclContext();
643 ++NumBlocks;
644 } else if (isa<EnumDecl>(DC))
645 DC = cast<EnumDecl>(DC)->getDeclContext();
John McCall5808ce42011-02-03 08:15:49 +0000646 else break;
647 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000648
Richard Smith7a614d82011-06-11 17:19:42 +0000649 QualType ThisTy;
650 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
651 if (method && method->isInstance())
652 ThisTy = method->getThisType(Context);
653 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
654 // C++0x [expr.prim]p4:
655 // Otherwise, if a member-declarator declares a non-static data member
656 // of a class X, the expression this is a prvalue of type "pointer to X"
657 // within the optional brace-or-equal-initializer.
658 Scope *S = getScopeForContext(DC);
659 if (!S || S->getFlags() & Scope::ThisScope)
660 ThisTy = Context.getPointerType(Context.getRecordType(RD));
661 }
John McCall469a1eb2011-02-02 13:00:07 +0000662
Richard Smith7a614d82011-06-11 17:19:42 +0000663 // Mark that we're closing on 'this' in all the block scopes we ignored.
664 if (!ThisTy.isNull())
665 for (unsigned idx = FunctionScopes.size() - 1;
666 NumBlocks; --idx, --NumBlocks)
667 cast<BlockScopeInfo>(FunctionScopes[idx])->CapturesCXXThis = true;
John McCall469a1eb2011-02-02 13:00:07 +0000668
Richard Smith7a614d82011-06-11 17:19:42 +0000669 return ThisTy;
John McCall5808ce42011-02-03 08:15:49 +0000670}
671
Richard Smith7a614d82011-06-11 17:19:42 +0000672ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCall5808ce42011-02-03 08:15:49 +0000673 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
674 /// is a non-lvalue expression whose value is the address of the object for
675 /// which the function is called.
676
Richard Smith7a614d82011-06-11 17:19:42 +0000677 QualType ThisTy = getAndCaptureCurrentThisType();
678 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCall5808ce42011-02-03 08:15:49 +0000679
Richard Smith7a614d82011-06-11 17:19:42 +0000680 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000681}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000682
John McCall60d7b3a2010-08-24 06:29:42 +0000683ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000684Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000685 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000686 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000687 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000688 if (!TypeRep)
689 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000690
John McCall9d125032010-01-15 18:39:57 +0000691 TypeSourceInfo *TInfo;
692 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
693 if (!TInfo)
694 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000695
696 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
697}
698
699/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
700/// Can be interpreted either as function-style casting ("int(x)")
701/// or class type construction ("ClassType(x,y,z)")
702/// or creation of a value-initialized type ("int()").
703ExprResult
704Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
705 SourceLocation LParenLoc,
706 MultiExprArg exprs,
707 SourceLocation RParenLoc) {
708 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000709 unsigned NumExprs = exprs.size();
710 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000711 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000712 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
713
Sebastian Redlf53597f2009-03-15 17:47:39 +0000714 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000715 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000716 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Douglas Gregorab6677e2010-09-08 00:15:04 +0000718 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000719 LParenLoc,
720 Exprs, NumExprs,
721 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000722 }
723
Anders Carlssonbb60a502009-08-27 03:53:50 +0000724 if (Ty->isArrayType())
725 return ExprError(Diag(TyBeginLoc,
726 diag::err_value_init_for_array_type) << FullRange);
727 if (!Ty->isVoidType() &&
728 RequireCompleteType(TyBeginLoc, Ty,
729 PDiag(diag::err_invalid_incomplete_type_use)
730 << FullRange))
731 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000732
Anders Carlssonbb60a502009-08-27 03:53:50 +0000733 if (RequireNonAbstractType(TyBeginLoc, Ty,
734 diag::err_allocation_of_abstract_type))
735 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000736
737
Douglas Gregor506ae412009-01-16 18:33:17 +0000738 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000739 // If the expression list is a single expression, the type conversion
740 // expression is equivalent (in definedness, and if defined in meaning) to the
741 // corresponding cast expression.
742 //
743 if (NumExprs == 1) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000744 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +0000745 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +0000746 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +0000747 ExprResult CastExpr =
John McCallf85e1932011-06-15 23:02:42 +0000748 CheckCastTypes(TInfo->getTypeLoc().getBeginLoc(),
749 TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
John Wiegley429bb272011-04-08 18:41:53 +0000750 Kind, VK, BasePath,
751 /*FunctionalStyle=*/true);
752 if (CastExpr.isInvalid())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000753 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +0000754 Exprs[0] = CastExpr.take();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000755
756 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000757
John McCallf871d0c2010-08-07 06:22:56 +0000758 return Owned(CXXFunctionalCastExpr::Create(Context,
Douglas Gregorab6677e2010-09-08 00:15:04 +0000759 Ty.getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +0000760 VK, TInfo, TyBeginLoc, Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000761 Exprs[0], &BasePath,
762 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000763 }
764
Douglas Gregor19311e72010-09-08 21:40:08 +0000765 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
766 InitializationKind Kind
767 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
768 LParenLoc, RParenLoc)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000769 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor19311e72010-09-08 21:40:08 +0000770 LParenLoc, RParenLoc);
771 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
772 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000773
Douglas Gregor19311e72010-09-08 21:40:08 +0000774 // FIXME: Improve AST representation?
775 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000776}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000777
John McCall6ec278d2011-01-27 09:37:56 +0000778/// doesUsualArrayDeleteWantSize - Answers whether the usual
779/// operator delete[] for the given type has a size_t parameter.
780static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
781 QualType allocType) {
782 const RecordType *record =
783 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
784 if (!record) return false;
785
786 // Try to find an operator delete[] in class scope.
787
788 DeclarationName deleteName =
789 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
790 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
791 S.LookupQualifiedName(ops, record->getDecl());
792
793 // We're just doing this for information.
794 ops.suppressDiagnostics();
795
796 // Very likely: there's no operator delete[].
797 if (ops.empty()) return false;
798
799 // If it's ambiguous, it should be illegal to call operator delete[]
800 // on this thing, so it doesn't matter if we allocate extra space or not.
801 if (ops.isAmbiguous()) return false;
802
803 LookupResult::Filter filter = ops.makeFilter();
804 while (filter.hasNext()) {
805 NamedDecl *del = filter.next()->getUnderlyingDecl();
806
807 // C++0x [basic.stc.dynamic.deallocation]p2:
808 // A template instance is never a usual deallocation function,
809 // regardless of its signature.
810 if (isa<FunctionTemplateDecl>(del)) {
811 filter.erase();
812 continue;
813 }
814
815 // C++0x [basic.stc.dynamic.deallocation]p2:
816 // If class T does not declare [an operator delete[] with one
817 // parameter] but does declare a member deallocation function
818 // named operator delete[] with exactly two parameters, the
819 // second of which has type std::size_t, then this function
820 // is a usual deallocation function.
821 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
822 filter.erase();
823 continue;
824 }
825 }
826 filter.done();
827
828 if (!ops.isSingleResult()) return false;
829
830 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
831 return (del->getNumParams() == 2);
832}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000833
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000834/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
835/// @code new (memory) int[size][4] @endcode
836/// or
837/// @code ::new Foo(23, "hello") @endcode
838/// For the interpretation of this heap of arguments, consult the base version.
John McCall60d7b3a2010-08-24 06:29:42 +0000839ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000840Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000841 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000842 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000843 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000844 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000845 SourceLocation ConstructorRParen) {
Richard Smith34b41d92011-02-20 03:19:35 +0000846 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
847
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000848 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000849 // If the specified type is an array, unwrap it and save the expression.
850 if (D.getNumTypeObjects() > 0 &&
851 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
852 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith34b41d92011-02-20 03:19:35 +0000853 if (TypeContainsAuto)
854 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
855 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000856 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000857 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
858 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000859 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000860 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
861 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000862
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000863 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000864 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000865 }
866
Douglas Gregor043cad22009-09-11 00:18:58 +0000867 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000868 if (ArraySize) {
869 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000870 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
871 break;
872
873 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
874 if (Expr *NumElts = (Expr *)Array.NumElts) {
875 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
876 !NumElts->isIntegerConstantExpr(Context)) {
877 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
878 << NumElts->getSourceRange();
879 return ExprError();
880 }
881 }
882 }
883 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000884
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +0000885 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
John McCallbf1a0282010-06-04 23:28:52 +0000886 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000887 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000888 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000889
Mike Stump1eb44332009-09-09 15:08:12 +0000890 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000891 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000892 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000893 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000894 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000895 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000896 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000897 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000898 ConstructorLParen,
899 move(ConstructorArgs),
Richard Smith34b41d92011-02-20 03:19:35 +0000900 ConstructorRParen,
901 TypeContainsAuto);
Douglas Gregor3433cf72009-05-21 00:00:09 +0000902}
903
John McCall60d7b3a2010-08-24 06:29:42 +0000904ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000905Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
906 SourceLocation PlacementLParen,
907 MultiExprArg PlacementArgs,
908 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000909 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000910 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000911 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000912 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000913 SourceLocation ConstructorLParen,
914 MultiExprArg ConstructorArgs,
Richard Smith34b41d92011-02-20 03:19:35 +0000915 SourceLocation ConstructorRParen,
916 bool TypeMayContainAuto) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000917 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000918
Richard Smith34b41d92011-02-20 03:19:35 +0000919 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
920 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
921 if (ConstructorArgs.size() == 0)
922 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
923 << AllocType << TypeRange);
924 if (ConstructorArgs.size() != 1) {
925 Expr *FirstBad = ConstructorArgs.get()[1];
926 return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
927 diag::err_auto_new_ctor_multiple_expressions)
928 << AllocType << TypeRange);
929 }
Richard Smitha085da82011-03-17 16:11:59 +0000930 TypeSourceInfo *DeducedType = 0;
931 if (!DeduceAutoType(AllocTypeInfo, ConstructorArgs.get()[0], DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +0000932 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
933 << AllocType
934 << ConstructorArgs.get()[0]->getType()
935 << TypeRange
936 << ConstructorArgs.get()[0]->getSourceRange());
Richard Smitha085da82011-03-17 16:11:59 +0000937 if (!DeducedType)
938 return ExprError();
Richard Smith34b41d92011-02-20 03:19:35 +0000939
Richard Smitha085da82011-03-17 16:11:59 +0000940 AllocTypeInfo = DeducedType;
941 AllocType = AllocTypeInfo->getType();
Richard Smith34b41d92011-02-20 03:19:35 +0000942 }
943
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000944 // Per C++0x [expr.new]p5, the type being constructed may be a
945 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +0000946 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000947 if (const ConstantArrayType *Array
948 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000949 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
950 Context.getSizeType(),
951 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000952 AllocType = Array->getElementType();
953 }
954 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000955
Douglas Gregora0750762010-10-06 16:00:31 +0000956 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
957 return ExprError();
958
John McCallf85e1932011-06-15 23:02:42 +0000959 // In ARC, infer 'retaining' for the allocated
960 if (getLangOptions().ObjCAutoRefCount &&
961 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
962 AllocType->isObjCLifetimeType()) {
963 AllocType = Context.getLifetimeQualifiedType(AllocType,
964 AllocType->getObjCARCImplicitLifetime());
965 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000966
John McCallf85e1932011-06-15 23:02:42 +0000967 QualType ResultType = Context.getPointerType(AllocType);
968
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000969 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
970 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000971 if (ArraySize && !ArraySize->isTypeDependent()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000972
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000973 QualType SizeType = ArraySize->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000974
John McCall60d7b3a2010-08-24 06:29:42 +0000975 ExprResult ConvertedSize
John McCall9ae2f072010-08-23 23:25:46 +0000976 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000977 PDiag(diag::err_array_size_not_integral),
978 PDiag(diag::err_array_size_incomplete_type)
979 << ArraySize->getSourceRange(),
980 PDiag(diag::err_array_size_explicit_conversion),
981 PDiag(diag::note_array_size_conversion),
982 PDiag(diag::err_array_size_ambiguous_conversion),
983 PDiag(diag::note_array_size_conversion),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000984 PDiag(getLangOptions().CPlusPlus0x? 0
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000985 : diag::ext_array_size_conversion));
986 if (ConvertedSize.isInvalid())
987 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000988
John McCall9ae2f072010-08-23 23:25:46 +0000989 ArraySize = ConvertedSize.take();
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000990 SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000991 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000992 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000993
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000994 // Let's see if this is a constant < 0. If so, we reject it out of hand.
995 // We don't care about special rules, so we tell the machinery it's not
996 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000997 if (!ArraySize->isValueDependent()) {
998 llvm::APSInt Value;
999 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
1000 if (Value < llvm::APSInt(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001001 llvm::APInt::getNullValue(Value.getBitWidth()),
Anders Carlssonac18b2e2009-09-23 00:37:25 +00001002 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +00001003 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +00001004 diag::err_typecheck_negative_array_size)
Sebastian Redlf53597f2009-03-15 17:47:39 +00001005 << ArraySize->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001006
Douglas Gregor2767ce22010-08-18 00:39:00 +00001007 if (!AllocType->isDependentType()) {
1008 unsigned ActiveSizeBits
1009 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1010 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001011 Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +00001012 diag::err_array_too_large)
1013 << Value.toString(10)
1014 << ArraySize->getSourceRange();
1015 return ExprError();
1016 }
1017 }
Douglas Gregor4bd40312010-07-13 15:54:32 +00001018 } else if (TypeIdParens.isValid()) {
1019 // Can't have dynamic array size when the type-id is in parentheses.
1020 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1021 << ArraySize->getSourceRange()
1022 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1023 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001024
Douglas Gregor4bd40312010-07-13 15:54:32 +00001025 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +00001026 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001027 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001028
John McCallf85e1932011-06-15 23:02:42 +00001029 // ARC: warn about ABI issues.
1030 if (getLangOptions().ObjCAutoRefCount) {
1031 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1032 if (BaseAllocType.hasStrongOrWeakObjCLifetime())
1033 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1034 << 0 << BaseAllocType;
1035 }
1036
John McCall7d166272011-05-15 07:14:44 +00001037 // Note that we do *not* convert the argument in any way. It can
1038 // be signed, larger than size_t, whatever.
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001039 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001040
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001041 FunctionDecl *OperatorNew = 0;
1042 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001043 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
1044 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001045
Sebastian Redl28507842009-02-26 14:39:58 +00001046 if (!AllocType->isDependentType() &&
1047 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
1048 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +00001049 SourceRange(PlacementLParen, PlacementRParen),
1050 UseGlobal, AllocType, ArraySize, PlaceArgs,
1051 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +00001052 return ExprError();
John McCall6ec278d2011-01-27 09:37:56 +00001053
1054 // If this is an array allocation, compute whether the usual array
1055 // deallocation function for the type has a size_t parameter.
1056 bool UsualArrayDeleteWantsSize = false;
1057 if (ArraySize && !AllocType->isDependentType())
1058 UsualArrayDeleteWantsSize
1059 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1060
Chris Lattner5f9e2722011-07-23 10:55:15 +00001061 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001062 if (OperatorNew) {
1063 // Add default arguments, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001064 const FunctionProtoType *Proto =
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001065 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001066 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00001067 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001068
Anders Carlsson28e94832010-05-03 02:07:56 +00001069 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001070 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlsson28e94832010-05-03 02:07:56 +00001071 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001072 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001073
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001074 NumPlaceArgs = AllPlaceArgs.size();
1075 if (NumPlaceArgs > 0)
1076 PlaceArgs = &AllPlaceArgs[0];
1077 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001078
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001079 bool Init = ConstructorLParen.isValid();
1080 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001081 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001082 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
1083 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +00001084 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +00001085
Anders Carlsson48c95012010-05-03 15:45:23 +00001086 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +00001087 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +00001088 SourceRange InitRange(ConsArgs[0]->getLocStart(),
1089 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001090
Anders Carlsson48c95012010-05-03 15:45:23 +00001091 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1092 return ExprError();
1093 }
1094
Douglas Gregor99a2e602009-12-16 01:38:02 +00001095 if (!AllocType->isDependentType() &&
1096 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
1097 // C++0x [expr.new]p15:
1098 // A new-expression that creates an object of type T initializes that
1099 // object as follows:
1100 InitializationKind Kind
1101 // - If the new-initializer is omitted, the object is default-
1102 // initialized (8.5); if no initialization is performed,
1103 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001104 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001105 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor99a2e602009-12-16 01:38:02 +00001106 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001107 : InitializationKind::CreateDirect(TypeRange.getBegin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001108 ConstructorLParen,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001109 ConstructorRParen);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001110
Douglas Gregor99a2e602009-12-16 01:38:02 +00001111 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00001112 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001113 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001114 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001115 move(ConstructorArgs));
1116 if (FullInit.isInvalid())
1117 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001118
1119 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor99a2e602009-12-16 01:38:02 +00001120 // constructor call, which CXXNewExpr handles directly.
1121 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1122 if (CXXBindTemporaryExpr *Binder
1123 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1124 FullInitExpr = Binder->getSubExpr();
1125 if (CXXConstructExpr *Construct
1126 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1127 Constructor = Construct->getConstructor();
1128 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1129 AEnd = Construct->arg_end();
1130 A != AEnd; ++A)
John McCall3fa5cae2010-10-26 07:05:15 +00001131 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001132 } else {
1133 // Take the converted initializer.
1134 ConvertedConstructorArgs.push_back(FullInit.release());
1135 }
1136 } else {
1137 // No initialization required.
1138 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001139
Douglas Gregor99a2e602009-12-16 01:38:02 +00001140 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001141 NumConsArgs = ConvertedConstructorArgs.size();
1142 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001143 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001144
Douglas Gregor6d908702010-02-26 05:06:18 +00001145 // Mark the new and delete operators as referenced.
1146 if (OperatorNew)
1147 MarkDeclarationReferenced(StartLoc, OperatorNew);
1148 if (OperatorDelete)
1149 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1150
John McCall84ff0fc2011-07-13 20:12:57 +00001151 // C++0x [expr.new]p17:
1152 // If the new expression creates an array of objects of class type,
1153 // access and ambiguity control are done for the destructor.
1154 if (ArraySize && Constructor) {
1155 if (CXXDestructorDecl *dtor = LookupDestructor(Constructor->getParent())) {
1156 MarkDeclarationReferenced(StartLoc, dtor);
1157 CheckDestructorAccess(StartLoc, dtor,
1158 PDiag(diag::err_access_dtor)
1159 << Context.getBaseElementType(AllocType));
1160 }
1161 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001162
Sebastian Redlf53597f2009-03-15 17:47:39 +00001163 PlacementArgs.release();
1164 ConstructorArgs.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001165
Ted Kremenekad7fe862010-02-11 22:51:03 +00001166 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001167 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001168 ArraySize, Constructor, Init,
1169 ConsArgs, NumConsArgs, OperatorDelete,
John McCall6ec278d2011-01-27 09:37:56 +00001170 UsualArrayDeleteWantsSize,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001171 ResultType, AllocTypeInfo,
1172 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001173 Init ? ConstructorRParen :
Chandler Carruth428edaf2010-10-25 08:47:36 +00001174 TypeRange.getEnd(),
1175 ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001176}
1177
1178/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1179/// in a new-expression.
1180/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +00001181bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00001182 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001183 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1184 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +00001185 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001186 return Diag(Loc, diag::err_bad_new_type)
1187 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001188 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001189 return Diag(Loc, diag::err_bad_new_type)
1190 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001191 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +00001192 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001193 PDiag(diag::err_new_incomplete_type)
1194 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001195 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +00001196 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +00001197 diag::err_allocation_of_abstract_type))
1198 return true;
Douglas Gregora0750762010-10-06 16:00:31 +00001199 else if (AllocType->isVariablyModifiedType())
1200 return Diag(Loc, diag::err_variably_modified_new_type)
1201 << AllocType;
Douglas Gregor5666d362011-04-15 19:46:20 +00001202 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1203 return Diag(Loc, diag::err_address_space_qualified_new)
1204 << AllocType.getUnqualifiedType() << AddressSpace;
John McCallf85e1932011-06-15 23:02:42 +00001205 else if (getLangOptions().ObjCAutoRefCount) {
1206 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1207 QualType BaseAllocType = Context.getBaseElementType(AT);
1208 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1209 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001210 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001211 << BaseAllocType;
1212 }
1213 }
Douglas Gregor5666d362011-04-15 19:46:20 +00001214
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001215 return false;
1216}
1217
Douglas Gregor6d908702010-02-26 05:06:18 +00001218/// \brief Determine whether the given function is a non-placement
1219/// deallocation function.
1220static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1221 if (FD->isInvalidDecl())
1222 return false;
1223
1224 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1225 return Method->isUsualDeallocationFunction();
1226
1227 return ((FD->getOverloadedOperator() == OO_Delete ||
1228 FD->getOverloadedOperator() == OO_Array_Delete) &&
1229 FD->getNumParams() == 1);
1230}
1231
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001232/// FindAllocationFunctions - Finds the overloads of operator new and delete
1233/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001234bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1235 bool UseGlobal, QualType AllocType,
1236 bool IsArray, Expr **PlaceArgs,
1237 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001238 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +00001239 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001240 // --- Choosing an allocation function ---
1241 // C++ 5.3.4p8 - 14 & 18
1242 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1243 // in the scope of the allocated class.
1244 // 2) If an array size is given, look for operator new[], else look for
1245 // operator new.
1246 // 3) The first argument is always size_t. Append the arguments from the
1247 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001248
Chris Lattner5f9e2722011-07-23 10:55:15 +00001249 SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001250 // We don't care about the actual value of this argument.
1251 // FIXME: Should the Sema create the expression and embed it in the syntax
1252 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001253 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001254 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssond67c4c32009-08-16 20:29:29 +00001255 Context.getSizeType(),
1256 SourceLocation());
1257 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001258 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1259
Douglas Gregor6d908702010-02-26 05:06:18 +00001260 // C++ [expr.new]p8:
1261 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001262 // function's name is operator new and the deallocation function's
Douglas Gregor6d908702010-02-26 05:06:18 +00001263 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001264 // type, the allocation function's name is operator new[] and the
1265 // deallocation function's name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001266 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1267 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001268 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1269 IsArray ? OO_Array_Delete : OO_Delete);
1270
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001271 QualType AllocElemType = Context.getBaseElementType(AllocType);
1272
1273 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001274 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001275 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001276 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001277 AllocArgs.size(), Record, /*AllowMissing=*/true,
1278 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001279 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001280 }
1281 if (!OperatorNew) {
1282 // Didn't find a member overload. Look for a global one.
1283 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001284 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001285 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001286 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1287 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001288 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001289 }
1290
John McCall9c82afc2010-04-20 02:18:25 +00001291 // We don't need an operator delete if we're running under
1292 // -fno-exceptions.
1293 if (!getLangOptions().Exceptions) {
1294 OperatorDelete = 0;
1295 return false;
1296 }
1297
Anders Carlssond9583892009-05-31 20:26:12 +00001298 // FindAllocationOverload can change the passed in arguments, so we need to
1299 // copy them back.
1300 if (NumPlaceArgs > 0)
1301 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001302
Douglas Gregor6d908702010-02-26 05:06:18 +00001303 // C++ [expr.new]p19:
1304 //
1305 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001306 // deallocation function's name is looked up in the global
Douglas Gregor6d908702010-02-26 05:06:18 +00001307 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001308 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6d908702010-02-26 05:06:18 +00001309 // the scope of T. If this lookup fails to find the name, or if
1310 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001311 // deallocation function's name is looked up in the global scope.
Douglas Gregor6d908702010-02-26 05:06:18 +00001312 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001313 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001314 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001315 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001316 LookupQualifiedName(FoundDelete, RD);
1317 }
John McCall90c8c572010-03-18 08:19:33 +00001318 if (FoundDelete.isAmbiguous())
1319 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001320
1321 if (FoundDelete.empty()) {
1322 DeclareGlobalNewDelete();
1323 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1324 }
1325
1326 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001327
Chris Lattner5f9e2722011-07-23 10:55:15 +00001328 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCall9aa472c2010-03-19 07:35:19 +00001329
John McCalledeb6c92010-09-14 21:34:24 +00001330 // Whether we're looking for a placement operator delete is dictated
1331 // by whether we selected a placement operator new, not by whether
1332 // we had explicit placement arguments. This matters for things like
1333 // struct A { void *operator new(size_t, int = 0); ... };
1334 // A *a = new A()
1335 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1336
1337 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001338 // C++ [expr.new]p20:
1339 // A declaration of a placement deallocation function matches the
1340 // declaration of a placement allocation function if it has the
1341 // same number of parameters and, after parameter transformations
1342 // (8.3.5), all parameter types except the first are
1343 // identical. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001344 //
Douglas Gregor6d908702010-02-26 05:06:18 +00001345 // To perform this comparison, we compute the function type that
1346 // the deallocation function should have, and use that type both
1347 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001348 //
1349 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001350 QualType ExpectedFunctionType;
1351 {
1352 const FunctionProtoType *Proto
1353 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001354
Chris Lattner5f9e2722011-07-23 10:55:15 +00001355 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001356 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6d908702010-02-26 05:06:18 +00001357 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1358 ArgTypes.push_back(Proto->getArgType(I));
1359
John McCalle23cf432010-12-14 08:05:40 +00001360 FunctionProtoType::ExtProtoInfo EPI;
1361 EPI.Variadic = Proto->isVariadic();
1362
Douglas Gregor6d908702010-02-26 05:06:18 +00001363 ExpectedFunctionType
1364 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalle23cf432010-12-14 08:05:40 +00001365 ArgTypes.size(), EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001366 }
1367
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001368 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001369 DEnd = FoundDelete.end();
1370 D != DEnd; ++D) {
1371 FunctionDecl *Fn = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001372 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6d908702010-02-26 05:06:18 +00001373 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1374 // Perform template argument deduction to try to match the
1375 // expected function type.
1376 TemplateDeductionInfo Info(Context, StartLoc);
1377 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1378 continue;
1379 } else
1380 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1381
1382 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001383 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001384 }
1385 } else {
1386 // C++ [expr.new]p20:
1387 // [...] Any non-placement deallocation function matches a
1388 // non-placement allocation function. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001389 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001390 DEnd = FoundDelete.end();
1391 D != DEnd; ++D) {
1392 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1393 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001394 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001395 }
1396 }
1397
1398 // C++ [expr.new]p20:
1399 // [...] If the lookup finds a single matching deallocation
1400 // function, that function will be called; otherwise, no
1401 // deallocation function will be called.
1402 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001403 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001404
1405 // C++0x [expr.new]p20:
1406 // If the lookup finds the two-parameter form of a usual
1407 // deallocation function (3.7.4.2) and that function, considered
1408 // as a placement deallocation function, would have been
1409 // selected as a match for the allocation function, the program
1410 // is ill-formed.
1411 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1412 isNonPlacementDeallocationFunction(OperatorDelete)) {
1413 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001414 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001415 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1416 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1417 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001418 } else {
1419 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001420 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001421 }
1422 }
1423
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001424 return false;
1425}
1426
Sebastian Redl7f662392008-12-04 22:20:51 +00001427/// FindAllocationOverload - Find an fitting overload for the allocation
1428/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001429bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1430 DeclarationName Name, Expr** Args,
1431 unsigned NumArgs, DeclContext *Ctx,
Sean Hunt2be7e902011-05-12 22:46:29 +00001432 bool AllowMissing, FunctionDecl *&Operator,
1433 bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001434 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1435 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001436 if (R.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001437 if (AllowMissing || !Diagnose)
Sebastian Redl7f662392008-12-04 22:20:51 +00001438 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001439 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001440 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001441 }
1442
John McCall90c8c572010-03-18 08:19:33 +00001443 if (R.isAmbiguous())
1444 return true;
1445
1446 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001447
John McCall5769d612010-02-08 23:07:23 +00001448 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001449 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001450 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001451 // Even member operator new/delete are implicitly treated as
1452 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001453 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001454
John McCall9aa472c2010-03-19 07:35:19 +00001455 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1456 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001457 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1458 Candidates,
1459 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001460 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001461 }
1462
John McCall9aa472c2010-03-19 07:35:19 +00001463 FunctionDecl *Fn = cast<FunctionDecl>(D);
1464 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001465 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001466 }
1467
1468 // Do the resolution.
1469 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001470 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001471 case OR_Success: {
1472 // Got one!
1473 FunctionDecl *FnDecl = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00001474 MarkDeclarationReferenced(StartLoc, FnDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001475 // The first argument is size_t, and the first parameter must be size_t,
1476 // too. This is checked on declaration and can be assumed. (It can't be
1477 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001478 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001479 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1480 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001481 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1482 FnDecl->getParamDecl(i));
1483
1484 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1485 return true;
1486
John McCall60d7b3a2010-08-24 06:29:42 +00001487 ExprResult Result
Sean Hunt2be7e902011-05-12 22:46:29 +00001488 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001489 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001490 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001491
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001492 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001493 }
1494 Operator = FnDecl;
Sean Hunt2be7e902011-05-12 22:46:29 +00001495 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl,
1496 Diagnose);
Sebastian Redl7f662392008-12-04 22:20:51 +00001497 return false;
1498 }
1499
1500 case OR_No_Viable_Function:
Chandler Carruth361d3802011-06-08 10:26:03 +00001501 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001502 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1503 << Name << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001504 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1505 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001506 return true;
1507
1508 case OR_Ambiguous:
Chandler Carruth361d3802011-06-08 10:26:03 +00001509 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001510 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1511 << Name << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001512 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
1513 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001514 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001515
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001516 case OR_Deleted: {
Chandler Carruth361d3802011-06-08 10:26:03 +00001517 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001518 Diag(StartLoc, diag::err_ovl_deleted_call)
1519 << Best->Function->isDeleted()
1520 << Name
1521 << getDeletedOrUnavailableSuffix(Best->Function)
1522 << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001523 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1524 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001525 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001526 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001527 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001528 assert(false && "Unreachable, bad result from BestViableFunction");
1529 return true;
1530}
1531
1532
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001533/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1534/// delete. These are:
1535/// @code
Sebastian Redl8999fe12011-03-14 18:08:30 +00001536/// // C++03:
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001537/// void* operator new(std::size_t) throw(std::bad_alloc);
1538/// void* operator new[](std::size_t) throw(std::bad_alloc);
1539/// void operator delete(void *) throw();
1540/// void operator delete[](void *) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001541/// // C++0x:
1542/// void* operator new(std::size_t);
1543/// void* operator new[](std::size_t);
1544/// void operator delete(void *);
1545/// void operator delete[](void *);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001546/// @endcode
Sebastian Redl8999fe12011-03-14 18:08:30 +00001547/// C++0x operator delete is implicitly noexcept.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001548/// Note that the placement and nothrow forms of new are *not* implicitly
1549/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001550void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001551 if (GlobalNewDeleteDeclared)
1552 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001553
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001554 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001555 // [...] The following allocation and deallocation functions (18.4) are
1556 // implicitly declared in global scope in each translation unit of a
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001557 // program
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001558 //
Sebastian Redl8999fe12011-03-14 18:08:30 +00001559 // C++03:
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001560 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001561 // void* operator new[](std::size_t) throw(std::bad_alloc);
1562 // void operator delete(void*) throw();
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001563 // void operator delete[](void*) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001564 // C++0x:
1565 // void* operator new(std::size_t);
1566 // void* operator new[](std::size_t);
1567 // void operator delete(void*);
1568 // void operator delete[](void*);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001569 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001570 // These implicit declarations introduce only the function names operator
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001571 // new, operator new[], operator delete, operator delete[].
1572 //
1573 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1574 // "std" or "bad_alloc" as necessary to form the exception specification.
1575 // However, we do not make these implicit declarations visible to name
1576 // lookup.
Sebastian Redl8999fe12011-03-14 18:08:30 +00001577 // Note that the C++0x versions of operator delete are deallocation functions,
1578 // and thus are implicitly noexcept.
1579 if (!StdBadAlloc && !getLangOptions().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001580 // The "std::bad_alloc" class has not yet been declared, so build it
1581 // implicitly.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001582 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1583 getOrCreateStdNamespace(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001584 SourceLocation(), SourceLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001585 &PP.getIdentifierTable().get("bad_alloc"),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001586 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001587 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001588 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001589
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001590 GlobalNewDeleteDeclared = true;
1591
1592 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1593 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001594 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001595
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001596 DeclareGlobalAllocationFunction(
1597 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001598 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001599 DeclareGlobalAllocationFunction(
1600 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001601 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001602 DeclareGlobalAllocationFunction(
1603 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1604 Context.VoidTy, VoidPtr);
1605 DeclareGlobalAllocationFunction(
1606 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1607 Context.VoidTy, VoidPtr);
1608}
1609
1610/// DeclareGlobalAllocationFunction - Declares a single implicit global
1611/// allocation function if it doesn't already exist.
1612void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001613 QualType Return, QualType Argument,
1614 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001615 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1616
1617 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001618 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001619 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001620 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001621 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001622 // Only look at non-template functions, as it is the predefined,
1623 // non-templated allocation function we are trying to declare here.
1624 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1625 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001626 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001627 Func->getParamDecl(0)->getType().getUnqualifiedType());
1628 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001629 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1630 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001631 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001632 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001633 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001634 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001635 }
1636 }
1637
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001638 QualType BadAllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001639 bool HasBadAllocExceptionSpec
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001640 = (Name.getCXXOverloadedOperator() == OO_New ||
1641 Name.getCXXOverloadedOperator() == OO_Array_New);
Sebastian Redl8999fe12011-03-14 18:08:30 +00001642 if (HasBadAllocExceptionSpec && !getLangOptions().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001643 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001644 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001645 }
John McCalle23cf432010-12-14 08:05:40 +00001646
1647 FunctionProtoType::ExtProtoInfo EPI;
John McCalle23cf432010-12-14 08:05:40 +00001648 if (HasBadAllocExceptionSpec) {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001649 if (!getLangOptions().CPlusPlus0x) {
1650 EPI.ExceptionSpecType = EST_Dynamic;
1651 EPI.NumExceptions = 1;
1652 EPI.Exceptions = &BadAllocType;
1653 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00001654 } else {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001655 EPI.ExceptionSpecType = getLangOptions().CPlusPlus0x ?
1656 EST_BasicNoexcept : EST_DynamicNone;
John McCalle23cf432010-12-14 08:05:40 +00001657 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001658
John McCalle23cf432010-12-14 08:05:40 +00001659 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001660 FunctionDecl *Alloc =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001661 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1662 SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001663 FnType, /*TInfo=*/0, SC_None,
1664 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001665 Alloc->setImplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001666
Nuno Lopesfc284482009-12-16 16:59:22 +00001667 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001668 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001669
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001670 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001671 SourceLocation(), 0,
1672 Argument, /*TInfo=*/0,
1673 SC_None, SC_None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001674 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001675
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001676 // FIXME: Also add this declaration to the IdentifierResolver, but
1677 // make sure it is at the end of the chain to coincide with the
1678 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001679 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001680}
1681
Anders Carlsson78f74552009-11-15 18:45:20 +00001682bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1683 DeclarationName Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001684 FunctionDecl* &Operator, bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001685 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001686 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001687 LookupQualifiedName(Found, RD);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001688
John McCalla24dc2e2009-11-17 02:14:36 +00001689 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001690 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001691
Chandler Carruth23893242010-06-28 00:30:51 +00001692 Found.suppressDiagnostics();
1693
Chris Lattner5f9e2722011-07-23 10:55:15 +00001694 SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001695 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1696 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001697 NamedDecl *ND = (*F)->getUnderlyingDecl();
1698
1699 // Ignore template operator delete members from the check for a usual
1700 // deallocation function.
1701 if (isa<FunctionTemplateDecl>(ND))
1702 continue;
1703
1704 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001705 Matches.push_back(F.getPair());
1706 }
1707
1708 // There's exactly one suitable operator; pick it.
1709 if (Matches.size() == 1) {
1710 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
Sean Hunt2be7e902011-05-12 22:46:29 +00001711
1712 if (Operator->isDeleted()) {
1713 if (Diagnose) {
1714 Diag(StartLoc, diag::err_deleted_function_use);
1715 Diag(Operator->getLocation(), diag::note_unavailable_here) << true;
1716 }
1717 return true;
1718 }
1719
John McCall046a7462010-08-04 00:31:26 +00001720 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Sean Hunt2be7e902011-05-12 22:46:29 +00001721 Matches[0], Diagnose);
John McCall046a7462010-08-04 00:31:26 +00001722 return false;
1723
1724 // We found multiple suitable operators; complain about the ambiguity.
1725 } else if (!Matches.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001726 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001727 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1728 << Name << RD;
John McCall046a7462010-08-04 00:31:26 +00001729
Chris Lattner5f9e2722011-07-23 10:55:15 +00001730 for (SmallVectorImpl<DeclAccessPair>::iterator
Sean Huntcb45a0f2011-05-12 22:46:25 +00001731 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1732 Diag((*F)->getUnderlyingDecl()->getLocation(),
1733 diag::note_member_declared_here) << Name;
1734 }
John McCall046a7462010-08-04 00:31:26 +00001735 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001736 }
1737
1738 // We did find operator delete/operator delete[] declarations, but
1739 // none of them were suitable.
1740 if (!Found.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001741 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001742 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1743 << Name << RD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001744
Sean Huntcb45a0f2011-05-12 22:46:25 +00001745 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1746 F != FEnd; ++F)
1747 Diag((*F)->getUnderlyingDecl()->getLocation(),
1748 diag::note_member_declared_here) << Name;
1749 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001750 return true;
1751 }
1752
1753 // Look for a global declaration.
1754 DeclareGlobalNewDelete();
1755 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001756
Anders Carlsson78f74552009-11-15 18:45:20 +00001757 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1758 Expr* DeallocArgs[1];
1759 DeallocArgs[0] = &Null;
1760 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001761 DeallocArgs, 1, TUDecl, !Diagnose,
1762 Operator, Diagnose))
Anders Carlsson78f74552009-11-15 18:45:20 +00001763 return true;
1764
1765 assert(Operator && "Did not find a deallocation function!");
1766 return false;
1767}
1768
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001769/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1770/// @code ::delete ptr; @endcode
1771/// or
1772/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001773ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001774Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley429bb272011-04-08 18:41:53 +00001775 bool ArrayForm, Expr *ExE) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001776 // C++ [expr.delete]p1:
1777 // The operand shall have a pointer type, or a class type having a single
1778 // conversion function to a pointer type. The result has type void.
1779 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001780 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1781
John Wiegley429bb272011-04-08 18:41:53 +00001782 ExprResult Ex = Owned(ExE);
Anders Carlssond67c4c32009-08-16 20:29:29 +00001783 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001784 bool ArrayFormAsWritten = ArrayForm;
John McCall6ec278d2011-01-27 09:37:56 +00001785 bool UsualArrayDeleteWantsSize = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001786
John Wiegley429bb272011-04-08 18:41:53 +00001787 if (!Ex.get()->isTypeDependent()) {
1788 QualType Type = Ex.get()->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001789
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001790 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001791 if (RequireCompleteType(StartLoc, Type,
Douglas Gregor254a9422010-07-29 14:44:35 +00001792 PDiag(diag::err_delete_incomplete_class_type)))
1793 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001794
Chris Lattner5f9e2722011-07-23 10:55:15 +00001795 SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
John McCall32daa422010-03-31 01:36:47 +00001796
Fariborz Jahanian53462782009-09-11 21:44:33 +00001797 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001798 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001799 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001800 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001801 NamedDecl *D = I.getDecl();
1802 if (isa<UsingShadowDecl>(D))
1803 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1804
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001805 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001806 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001807 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001808
John McCall32daa422010-03-31 01:36:47 +00001809 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001810
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001811 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1812 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001813 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001814 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001815 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001816 if (ObjectPtrConversions.size() == 1) {
1817 // We have a single conversion to a pointer-to-object type. Perform
1818 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001819 // TODO: don't redo the conversion calculation.
John Wiegley429bb272011-04-08 18:41:53 +00001820 ExprResult Res =
1821 PerformImplicitConversion(Ex.get(),
John McCall32daa422010-03-31 01:36:47 +00001822 ObjectPtrConversions.front()->getConversionType(),
John Wiegley429bb272011-04-08 18:41:53 +00001823 AA_Converting);
1824 if (Res.isUsable()) {
1825 Ex = move(Res);
1826 Type = Ex.get()->getType();
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001827 }
1828 }
1829 else if (ObjectPtrConversions.size() > 1) {
1830 Diag(StartLoc, diag::err_ambiguous_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001831 << Type << Ex.get()->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001832 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1833 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001834 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001835 }
Sebastian Redl28507842009-02-26 14:39:58 +00001836 }
1837
Sebastian Redlf53597f2009-03-15 17:47:39 +00001838 if (!Type->isPointerType())
1839 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001840 << Type << Ex.get()->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001841
Ted Kremenek6217b802009-07-29 21:53:49 +00001842 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmane52c9142011-07-26 22:25:31 +00001843 QualType PointeeElem = Context.getBaseElementType(Pointee);
1844
1845 if (unsigned AddressSpace = Pointee.getAddressSpace())
1846 return Diag(Ex.get()->getLocStart(),
1847 diag::err_address_space_qualified_delete)
1848 << Pointee.getUnqualifiedType() << AddressSpace;
1849
1850 CXXRecordDecl *PointeeRD = 0;
Douglas Gregor94a61572010-05-24 17:01:56 +00001851 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001852 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregor94a61572010-05-24 17:01:56 +00001853 // effectively bans deletion of "void*". However, most compilers support
1854 // this, so we treat it as a warning unless we're in a SFINAE context.
1855 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001856 << Type << Ex.get()->getSourceRange();
Eli Friedmane52c9142011-07-26 22:25:31 +00001857 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00001858 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001859 << Type << Ex.get()->getSourceRange());
Eli Friedmane52c9142011-07-26 22:25:31 +00001860 } else if (!Pointee->isDependentType()) {
1861 if (!RequireCompleteType(StartLoc, Pointee,
1862 PDiag(diag::warn_delete_incomplete)
1863 << Ex.get()->getSourceRange())) {
1864 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
1865 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
1866 }
1867 }
1868
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001869 // C++ [expr.delete]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001870 // [Note: a pointer to a const type can be the operand of a
1871 // delete-expression; it is not necessary to cast away the constness
1872 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001873 // of the delete-expression. ]
John McCallf85e1932011-06-15 23:02:42 +00001874 if (!Context.hasSameType(Ex.get()->getType(), Context.VoidPtrTy))
1875 Ex = Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy, CK_NoOp,
1876 Ex.take(), 0, VK_RValue));
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001877
1878 if (Pointee->isArrayType() && !ArrayForm) {
1879 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley429bb272011-04-08 18:41:53 +00001880 << Type << Ex.get()->getSourceRange()
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001881 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1882 ArrayForm = true;
1883 }
1884
Anders Carlssond67c4c32009-08-16 20:29:29 +00001885 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1886 ArrayForm ? OO_Array_Delete : OO_Delete);
1887
Eli Friedmane52c9142011-07-26 22:25:31 +00001888 if (PointeeRD) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001889 if (!UseGlobal &&
Eli Friedmane52c9142011-07-26 22:25:31 +00001890 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
1891 OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001892 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001893
John McCall6ec278d2011-01-27 09:37:56 +00001894 // If we're allocating an array of records, check whether the
1895 // usual operator delete[] has a size_t parameter.
1896 if (ArrayForm) {
1897 // If the user specifically asked to use the global allocator,
1898 // we'll need to do the lookup into the class.
1899 if (UseGlobal)
1900 UsualArrayDeleteWantsSize =
1901 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1902
1903 // Otherwise, the usual operator delete[] should be the
1904 // function we just found.
1905 else if (isa<CXXMethodDecl>(OperatorDelete))
1906 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1907 }
1908
Eli Friedmane52c9142011-07-26 22:25:31 +00001909 if (!PointeeRD->hasTrivialDestructor())
1910 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001911 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001912 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00001913 DiagnoseUseOfDecl(Dtor, StartLoc);
1914 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00001915
1916 // C++ [expr.delete]p3:
1917 // In the first alternative (delete object), if the static type of the
1918 // object to be deleted is different from its dynamic type, the static
1919 // type shall be a base class of the dynamic type of the object to be
1920 // deleted and the static type shall have a virtual destructor or the
1921 // behavior is undefined.
1922 //
1923 // Note: a final class cannot be derived from, no issue there
Eli Friedmanef8c79c2011-07-26 23:27:24 +00001924 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
Eli Friedmane52c9142011-07-26 22:25:31 +00001925 CXXDestructorDecl *dtor = PointeeRD->getDestructor();
Eli Friedmanef8c79c2011-07-26 23:27:24 +00001926 if (dtor && !dtor->isVirtual()) {
1927 if (PointeeRD->isAbstract()) {
1928 // If the class is abstract, we warn by default, because we're
1929 // sure the code has undefined behavior.
1930 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
1931 << PointeeElem;
1932 } else if (!ArrayForm) {
1933 // Otherwise, if this is not an array delete, it's a bit suspect,
1934 // but not necessarily wrong.
1935 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
1936 }
1937 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00001938 }
John McCallf85e1932011-06-15 23:02:42 +00001939
1940 } else if (getLangOptions().ObjCAutoRefCount &&
1941 PointeeElem->isObjCLifetimeType() &&
1942 (PointeeElem.getObjCLifetime() == Qualifiers::OCL_Strong ||
1943 PointeeElem.getObjCLifetime() == Qualifiers::OCL_Weak) &&
1944 ArrayForm) {
1945 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1946 << 1 << PointeeElem;
Anders Carlssond67c4c32009-08-16 20:29:29 +00001947 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001948
Anders Carlssond67c4c32009-08-16 20:29:29 +00001949 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001950 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001951 DeclareGlobalNewDelete();
1952 DeclContext *TUDecl = Context.getTranslationUnitDecl();
John Wiegley429bb272011-04-08 18:41:53 +00001953 Expr *Arg = Ex.get();
Mike Stump1eb44332009-09-09 15:08:12 +00001954 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
John Wiegley429bb272011-04-08 18:41:53 +00001955 &Arg, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001956 OperatorDelete))
1957 return ExprError();
1958 }
Mike Stump1eb44332009-09-09 15:08:12 +00001959
John McCall9c82afc2010-04-20 02:18:25 +00001960 MarkDeclarationReferenced(StartLoc, OperatorDelete);
John McCall6ec278d2011-01-27 09:37:56 +00001961
Douglas Gregord880f522011-02-01 15:50:11 +00001962 // Check access and ambiguity of operator delete and destructor.
Eli Friedmane52c9142011-07-26 22:25:31 +00001963 if (PointeeRD) {
1964 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
John Wiegley429bb272011-04-08 18:41:53 +00001965 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregord880f522011-02-01 15:50:11 +00001966 PDiag(diag::err_access_dtor) << PointeeElem);
1967 }
1968 }
1969
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001970 }
1971
Sebastian Redlf53597f2009-03-15 17:47:39 +00001972 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall6ec278d2011-01-27 09:37:56 +00001973 ArrayFormAsWritten,
1974 UsualArrayDeleteWantsSize,
John Wiegley429bb272011-04-08 18:41:53 +00001975 OperatorDelete, Ex.take(), StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001976}
1977
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001978/// \brief Check the use of the given variable as a C++ condition in an if,
1979/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001980ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00001981 SourceLocation StmtLoc,
1982 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001983 QualType T = ConditionVar->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001984
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001985 // C++ [stmt.select]p2:
1986 // The declarator shall not specify a function or an array.
1987 if (T->isFunctionType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001988 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001989 diag::err_invalid_use_of_function_type)
1990 << ConditionVar->getSourceRange());
1991 else if (T->isArrayType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001992 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001993 diag::err_invalid_use_of_array_type)
1994 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001995
John Wiegley429bb272011-04-08 18:41:53 +00001996 ExprResult Condition =
1997 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
Douglas Gregor40d96a62011-02-28 21:54:11 +00001998 ConditionVar,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001999 ConditionVar->getLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00002000 ConditionVar->getType().getNonReferenceType(),
John Wiegley429bb272011-04-08 18:41:53 +00002001 VK_LValue));
2002 if (ConvertToBoolean) {
2003 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
2004 if (Condition.isInvalid())
2005 return ExprError();
2006 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002007
John Wiegley429bb272011-04-08 18:41:53 +00002008 return move(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002009}
2010
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002011/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley429bb272011-04-08 18:41:53 +00002012ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002013 // C++ 6.4p4:
2014 // The value of a condition that is an initialized declaration in a statement
2015 // other than a switch statement is the value of the declared variable
2016 // implicitly converted to type bool. If that conversion is ill-formed, the
2017 // program is ill-formed.
2018 // The value of a condition that is an expression is the value of the
2019 // expression, implicitly converted to bool.
2020 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002021 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002022}
Douglas Gregor77a52232008-09-12 00:47:35 +00002023
2024/// Helper function to determine whether this is the (deprecated) C++
2025/// conversion from a string literal to a pointer to non-const char or
2026/// non-const wchar_t (for narrow and wide string literals,
2027/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00002028bool
Douglas Gregor77a52232008-09-12 00:47:35 +00002029Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2030 // Look inside the implicit cast, if it exists.
2031 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2032 From = Cast->getSubExpr();
2033
2034 // A string literal (2.13.4) that is not a wide string literal can
2035 // be converted to an rvalue of type "pointer to char"; a wide
2036 // string literal can be converted to an rvalue of type "pointer
2037 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00002038 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00002039 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00002040 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00002041 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00002042 // This conversion is considered only when there is an
2043 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregor5cee1192011-07-27 05:40:30 +00002044 if (!ToPtrType->getPointeeType().hasQualifiers()) {
2045 switch (StrLit->getKind()) {
2046 case StringLiteral::UTF8:
2047 case StringLiteral::UTF16:
2048 case StringLiteral::UTF32:
2049 // We don't allow UTF literals to be implicitly converted
2050 break;
2051 case StringLiteral::Ascii:
2052 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2053 ToPointeeType->getKind() == BuiltinType::Char_S);
2054 case StringLiteral::Wide:
2055 return ToPointeeType->isWideCharType();
2056 }
2057 }
Douglas Gregor77a52232008-09-12 00:47:35 +00002058 }
2059
2060 return false;
2061}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002062
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002063static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00002064 SourceLocation CastLoc,
2065 QualType Ty,
2066 CastKind Kind,
2067 CXXMethodDecl *Method,
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002068 NamedDecl *FoundDecl,
John McCall2de56d12010-08-25 11:45:40 +00002069 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002070 switch (Kind) {
2071 default: assert(0 && "Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00002072 case CK_ConstructorConversion: {
John McCallca0408f2010-08-23 06:44:23 +00002073 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002074
Douglas Gregorba70ab62010-04-16 22:17:36 +00002075 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
John McCallf312b1e2010-08-26 23:41:50 +00002076 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00002077 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00002078 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002079
2080 ExprResult Result =
2081 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
John McCall7a1fad32010-08-24 07:32:53 +00002082 move_arg(ConstructorArgs),
Chandler Carruth428edaf2010-10-25 08:47:36 +00002083 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete,
2084 SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002085 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00002086 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002087
Douglas Gregorba70ab62010-04-16 22:17:36 +00002088 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2089 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002090
John McCall2de56d12010-08-25 11:45:40 +00002091 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002092 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002093
Douglas Gregorba70ab62010-04-16 22:17:36 +00002094 // Create an implicit call expr that calls it.
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002095 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002096 if (Result.isInvalid())
2097 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002098
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002099 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002100 }
2101 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002102}
Douglas Gregorba70ab62010-04-16 22:17:36 +00002103
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002104/// PerformImplicitConversion - Perform an implicit conversion of the
2105/// expression From to the type ToType using the pre-computed implicit
John Wiegley429bb272011-04-08 18:41:53 +00002106/// conversion sequence ICS. Returns the converted
Douglas Gregor68647482009-12-16 03:45:30 +00002107/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002108/// used in the error message.
John Wiegley429bb272011-04-08 18:41:53 +00002109ExprResult
2110Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002111 const ImplicitConversionSequence &ICS,
John McCallf85e1932011-06-15 23:02:42 +00002112 AssignmentAction Action,
2113 CheckedConversionKind CCK) {
John McCall1d318332010-01-12 00:44:57 +00002114 switch (ICS.getKind()) {
John Wiegley429bb272011-04-08 18:41:53 +00002115 case ImplicitConversionSequence::StandardConversion: {
2116 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
John McCallf85e1932011-06-15 23:02:42 +00002117 Action, CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002118 if (Res.isInvalid())
2119 return ExprError();
2120 From = Res.take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002121 break;
John Wiegley429bb272011-04-08 18:41:53 +00002122 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002123
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002124 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002125
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00002126 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00002127 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002128 QualType BeforeToType;
2129 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00002130 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002131
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002132 // If the user-defined conversion is specified by a conversion function,
2133 // the initial standard conversion sequence converts the source type to
2134 // the implicit object parameter of the conversion function.
2135 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00002136 } else {
2137 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00002138 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002139 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00002140 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002141 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002142 // initial standard conversion sequence converts the source type to the
2143 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00002144 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2145 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002146 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00002147 // Watch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00002148 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley429bb272011-04-08 18:41:53 +00002149 ExprResult Res =
2150 PerformImplicitConversion(From, BeforeToType,
2151 ICS.UserDefined.Before, AA_Converting,
John McCallf85e1932011-06-15 23:02:42 +00002152 CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002153 if (Res.isInvalid())
2154 return ExprError();
2155 From = Res.take();
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002156 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002157
2158 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00002159 = BuildCXXCastArgument(*this,
2160 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00002161 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002162 CastKind, cast<CXXMethodDecl>(FD),
2163 ICS.UserDefined.FoundConversionFunction,
John McCall9ae2f072010-08-23 23:25:46 +00002164 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002165
2166 if (CastArg.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00002167 return ExprError();
Eli Friedmand8889622009-11-27 04:41:50 +00002168
John Wiegley429bb272011-04-08 18:41:53 +00002169 From = CastArg.take();
Eli Friedmand8889622009-11-27 04:41:50 +00002170
Eli Friedmand8889622009-11-27 04:41:50 +00002171 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
John McCallf85e1932011-06-15 23:02:42 +00002172 AA_Converting, CCK);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00002173 }
John McCall1d318332010-01-12 00:44:57 +00002174
2175 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00002176 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00002177 PDiag(diag::err_typecheck_ambiguous_condition)
2178 << From->getSourceRange());
John Wiegley429bb272011-04-08 18:41:53 +00002179 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002180
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002181 case ImplicitConversionSequence::EllipsisConversion:
2182 assert(false && "Cannot perform an ellipsis conversion");
John Wiegley429bb272011-04-08 18:41:53 +00002183 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002184
2185 case ImplicitConversionSequence::BadConversion:
John Wiegley429bb272011-04-08 18:41:53 +00002186 return ExprError();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002187 }
2188
2189 // Everything went well.
John Wiegley429bb272011-04-08 18:41:53 +00002190 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002191}
2192
2193/// PerformImplicitConversion - Perform an implicit conversion of the
2194/// expression From to the type ToType by following the standard
John Wiegley429bb272011-04-08 18:41:53 +00002195/// conversion sequence SCS. Returns the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00002196/// expression. Flavor is the context in which we're performing this
2197/// conversion, for use in error messages.
John Wiegley429bb272011-04-08 18:41:53 +00002198ExprResult
2199Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00002200 const StandardConversionSequence& SCS,
John McCallf85e1932011-06-15 23:02:42 +00002201 AssignmentAction Action,
2202 CheckedConversionKind CCK) {
2203 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2204
Mike Stump390b4cc2009-05-16 07:39:55 +00002205 // Overall FIXME: we are recomputing too many types here and doing far too
2206 // much extra work. What this means is that we need to keep track of more
2207 // information that is computed when we try the implicit conversion initially,
2208 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002209 QualType FromType = From->getType();
John McCallf85e1932011-06-15 23:02:42 +00002210
Douglas Gregor225c41e2008-11-03 19:09:14 +00002211 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00002212 // FIXME: When can ToType be a reference type?
2213 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002214 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00002215 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002216 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00002217 MultiExprArg(*this, &From, 1),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002218 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002219 ConstructorArgs))
John Wiegley429bb272011-04-08 18:41:53 +00002220 return ExprError();
2221 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2222 ToType, SCS.CopyConstructor,
2223 move_arg(ConstructorArgs),
2224 /*ZeroInit*/ false,
2225 CXXConstructExpr::CK_Complete,
2226 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002227 }
John Wiegley429bb272011-04-08 18:41:53 +00002228 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2229 ToType, SCS.CopyConstructor,
2230 MultiExprArg(*this, &From, 1),
2231 /*ZeroInit*/ false,
2232 CXXConstructExpr::CK_Complete,
2233 SourceRange());
Douglas Gregor225c41e2008-11-03 19:09:14 +00002234 }
2235
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002236 // Resolve overloaded function references.
2237 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2238 DeclAccessPair Found;
2239 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2240 true, Found);
2241 if (!Fn)
John Wiegley429bb272011-04-08 18:41:53 +00002242 return ExprError();
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002243
2244 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
John Wiegley429bb272011-04-08 18:41:53 +00002245 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002246
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002247 From = FixOverloadedFunctionReference(From, Found, Fn);
2248 FromType = From->getType();
2249 }
2250
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002251 // Perform the first implicit conversion.
2252 switch (SCS.First) {
2253 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002254 // Nothing to do.
2255 break;
2256
John McCallf6a16482010-12-04 03:47:34 +00002257 case ICK_Lvalue_To_Rvalue:
2258 // Should this get its own ICK?
2259 if (From->getObjectKind() == OK_ObjCProperty) {
John Wiegley429bb272011-04-08 18:41:53 +00002260 ExprResult FromRes = ConvertPropertyForRValue(From);
2261 if (FromRes.isInvalid())
2262 return ExprError();
2263 From = FromRes.take();
John McCall241d5582010-12-07 22:54:16 +00002264 if (!From->isGLValue()) break;
John McCallf6a16482010-12-04 03:47:34 +00002265 }
2266
2267 FromType = FromType.getUnqualifiedType();
2268 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2269 From, 0, VK_RValue);
2270 break;
2271
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002272 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002273 FromType = Context.getArrayDecayedType(FromType);
John McCallf85e1932011-06-15 23:02:42 +00002274 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2275 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002276 break;
2277
2278 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002279 FromType = Context.getPointerType(FromType);
John McCallf85e1932011-06-15 23:02:42 +00002280 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2281 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002282 break;
2283
2284 default:
2285 assert(false && "Improper first standard conversion");
2286 break;
2287 }
2288
2289 // Perform the second implicit conversion
2290 switch (SCS.Second) {
2291 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002292 // If both sides are functions (or pointers/references to them), there could
2293 // be incompatible exception declarations.
2294 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002295 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002296 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002297 break;
2298
Douglas Gregor43c79c22009-12-09 00:47:37 +00002299 case ICK_NoReturn_Adjustment:
2300 // If both sides are functions (or pointers/references to them), there could
2301 // be incompatible exception declarations.
2302 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002303 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002304
John McCallf85e1932011-06-15 23:02:42 +00002305 From = ImpCastExprToType(From, ToType, CK_NoOp,
2306 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor43c79c22009-12-09 00:47:37 +00002307 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002308
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002309 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002310 case ICK_Integral_Conversion:
John McCallf85e1932011-06-15 23:02:42 +00002311 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2312 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002313 break;
2314
2315 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002316 case ICK_Floating_Conversion:
John McCallf85e1932011-06-15 23:02:42 +00002317 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2318 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002319 break;
2320
2321 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00002322 case ICK_Complex_Conversion: {
2323 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2324 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2325 CastKind CK;
2326 if (FromEl->isRealFloatingType()) {
2327 if (ToEl->isRealFloatingType())
2328 CK = CK_FloatingComplexCast;
2329 else
2330 CK = CK_FloatingComplexToIntegralComplex;
2331 } else if (ToEl->isRealFloatingType()) {
2332 CK = CK_IntegralComplexToFloatingComplex;
2333 } else {
2334 CK = CK_IntegralComplexCast;
2335 }
John McCallf85e1932011-06-15 23:02:42 +00002336 From = ImpCastExprToType(From, ToType, CK,
2337 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002338 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00002339 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002340
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002341 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002342 if (ToType->isRealFloatingType())
John McCallf85e1932011-06-15 23:02:42 +00002343 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2344 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002345 else
John McCallf85e1932011-06-15 23:02:42 +00002346 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2347 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002348 break;
2349
Douglas Gregorf9201e02009-02-11 23:02:49 +00002350 case ICK_Compatible_Conversion:
John McCallf85e1932011-06-15 23:02:42 +00002351 From = ImpCastExprToType(From, ToType, CK_NoOp,
2352 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002353 break;
2354
John McCallf85e1932011-06-15 23:02:42 +00002355 case ICK_Writeback_Conversion:
Anders Carlsson61faec12009-09-12 04:46:44 +00002356 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00002357 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002358 // Diagnose incompatible Objective-C conversions
Douglas Gregor8cf0d222011-06-11 04:42:12 +00002359 if (Action == AA_Initializing || Action == AA_Assigning)
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002360 Diag(From->getSourceRange().getBegin(),
2361 diag::ext_typecheck_convert_incompatible_pointer)
2362 << ToType << From->getType() << Action
Anna Zaks67221552011-07-28 19:51:27 +00002363 << From->getSourceRange() << 0;
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002364 else
2365 Diag(From->getSourceRange().getBegin(),
2366 diag::ext_typecheck_convert_incompatible_pointer)
2367 << From->getType() << ToType << Action
Anna Zaks67221552011-07-28 19:51:27 +00002368 << From->getSourceRange() << 0;
John McCallf85e1932011-06-15 23:02:42 +00002369
Douglas Gregor926df6c2011-06-11 01:09:30 +00002370 if (From->getType()->isObjCObjectPointerType() &&
2371 ToType->isObjCObjectPointerType())
2372 EmitRelatedResultTypeNote(From);
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002373 }
2374 else if (getLangOptions().ObjCAutoRefCount &&
2375 !CheckObjCARCUnavailableWeakConversion(ToType,
2376 From->getType())) {
John McCall7f3a6d32011-09-09 06:12:06 +00002377 if (Action == AA_Initializing)
2378 Diag(From->getSourceRange().getBegin(),
2379 diag::err_arc_weak_unavailable_assign);
2380 else
2381 Diag(From->getSourceRange().getBegin(),
2382 diag::err_arc_convesion_of_weak_unavailable)
2383 << (Action == AA_Casting) << From->getType() << ToType
2384 << From->getSourceRange();
2385 }
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002386
John McCalldaa8e4e2010-11-15 09:13:47 +00002387 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002388 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002389 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002390 return ExprError();
John McCalldc05b112011-09-10 01:16:55 +00002391
2392 // Make sure we extend blocks if necessary.
2393 // FIXME: doing this here is really ugly.
2394 if (Kind == CK_BlockPointerToObjCPointerCast) {
2395 ExprResult E = From;
2396 (void) PrepareCastToObjCObjectPointer(E);
2397 From = E.take();
2398 }
2399
John McCallf85e1932011-06-15 23:02:42 +00002400 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2401 .take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002402 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00002403 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002404
Anders Carlsson61faec12009-09-12 04:46:44 +00002405 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002406 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002407 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002408 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002409 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002410 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002411 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00002412 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2413 .take();
Anders Carlsson61faec12009-09-12 04:46:44 +00002414 break;
2415 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002416
Abramo Bagnara737d5442011-04-07 09:26:19 +00002417 case ICK_Boolean_Conversion:
John Wiegley429bb272011-04-08 18:41:53 +00002418 From = ImpCastExprToType(From, Context.BoolTy,
John McCallf85e1932011-06-15 23:02:42 +00002419 ScalarTypeToBooleanCastKind(FromType),
2420 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002421 break;
2422
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002423 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002424 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002425 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002426 ToType.getNonReferenceType(),
2427 From->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002428 From->getSourceRange(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002429 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002430 CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002431 return ExprError();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002432
John Wiegley429bb272011-04-08 18:41:53 +00002433 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
John McCall2de56d12010-08-25 11:45:40 +00002434 CK_DerivedToBase, CastCategory(From),
John McCallf85e1932011-06-15 23:02:42 +00002435 &BasePath, CCK).take();
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002436 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002437 }
2438
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002439 case ICK_Vector_Conversion:
John McCallf85e1932011-06-15 23:02:42 +00002440 From = ImpCastExprToType(From, ToType, CK_BitCast,
2441 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002442 break;
2443
2444 case ICK_Vector_Splat:
John McCallf85e1932011-06-15 23:02:42 +00002445 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2446 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002447 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002448
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002449 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002450 // Case 1. x -> _Complex y
2451 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2452 QualType ElType = ToComplex->getElementType();
2453 bool isFloatingComplex = ElType->isRealFloatingType();
2454
2455 // x -> y
2456 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2457 // do nothing
2458 } else if (From->getType()->isRealFloatingType()) {
John Wiegley429bb272011-04-08 18:41:53 +00002459 From = ImpCastExprToType(From, ElType,
2460 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002461 } else {
2462 assert(From->getType()->isIntegerType());
John Wiegley429bb272011-04-08 18:41:53 +00002463 From = ImpCastExprToType(From, ElType,
2464 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002465 }
2466 // y -> _Complex y
John Wiegley429bb272011-04-08 18:41:53 +00002467 From = ImpCastExprToType(From, ToType,
John McCalldaa8e4e2010-11-15 09:13:47 +00002468 isFloatingComplex ? CK_FloatingRealToComplex
John Wiegley429bb272011-04-08 18:41:53 +00002469 : CK_IntegralRealToComplex).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002470
2471 // Case 2. _Complex x -> y
2472 } else {
2473 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2474 assert(FromComplex);
2475
2476 QualType ElType = FromComplex->getElementType();
2477 bool isFloatingComplex = ElType->isRealFloatingType();
2478
2479 // _Complex x -> x
John Wiegley429bb272011-04-08 18:41:53 +00002480 From = ImpCastExprToType(From, ElType,
John McCalldaa8e4e2010-11-15 09:13:47 +00002481 isFloatingComplex ? CK_FloatingComplexToReal
John McCallf85e1932011-06-15 23:02:42 +00002482 : CK_IntegralComplexToReal,
2483 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002484
2485 // x -> y
2486 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2487 // do nothing
2488 } else if (ToType->isRealFloatingType()) {
John Wiegley429bb272011-04-08 18:41:53 +00002489 From = ImpCastExprToType(From, ToType,
John McCallf85e1932011-06-15 23:02:42 +00002490 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2491 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002492 } else {
2493 assert(ToType->isIntegerType());
John Wiegley429bb272011-04-08 18:41:53 +00002494 From = ImpCastExprToType(From, ToType,
John McCallf85e1932011-06-15 23:02:42 +00002495 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2496 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002497 }
2498 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002499 break;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002500
2501 case ICK_Block_Pointer_Conversion: {
John McCallf85e1932011-06-15 23:02:42 +00002502 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2503 VK_RValue, /*BasePath=*/0, CCK).take();
2504 break;
2505 }
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002506
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002507 case ICK_TransparentUnionConversion: {
John Wiegley429bb272011-04-08 18:41:53 +00002508 ExprResult FromRes = Owned(From);
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002509 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002510 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2511 if (FromRes.isInvalid())
2512 return ExprError();
2513 From = FromRes.take();
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002514 assert ((ConvTy == Sema::Compatible) &&
2515 "Improper transparent union conversion");
2516 (void)ConvTy;
2517 break;
2518 }
2519
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002520 case ICK_Lvalue_To_Rvalue:
2521 case ICK_Array_To_Pointer:
2522 case ICK_Function_To_Pointer:
2523 case ICK_Qualification:
2524 case ICK_Num_Conversion_Kinds:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002525 assert(false && "Improper second standard conversion");
2526 break;
2527 }
2528
2529 switch (SCS.Third) {
2530 case ICK_Identity:
2531 // Nothing to do.
2532 break;
2533
Sebastian Redl906082e2010-07-20 04:20:21 +00002534 case ICK_Qualification: {
2535 // The qualification keeps the category of the inner expression, unless the
2536 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002537 ExprValueKind VK = ToType->isReferenceType() ?
2538 CastCategory(From) : VK_RValue;
John Wiegley429bb272011-04-08 18:41:53 +00002539 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
John McCallf85e1932011-06-15 23:02:42 +00002540 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
Douglas Gregora9bff302010-02-28 18:30:25 +00002541
Douglas Gregor069a6da2011-03-14 16:13:32 +00002542 if (SCS.DeprecatedStringLiteralToCharPtr &&
2543 !getLangOptions().WritableStrings)
Douglas Gregora9bff302010-02-28 18:30:25 +00002544 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2545 << ToType.getNonReferenceType();
2546
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002547 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002548 }
2549
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002550 default:
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002551 assert(false && "Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002552 break;
2553 }
2554
John Wiegley429bb272011-04-08 18:41:53 +00002555 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002556}
2557
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002558ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002559 SourceLocation KWLoc,
2560 ParsedType Ty,
2561 SourceLocation RParen) {
2562 TypeSourceInfo *TSInfo;
2563 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002564
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002565 if (!TSInfo)
2566 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002567 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002568}
2569
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002570/// \brief Check the completeness of a type in a unary type trait.
2571///
2572/// If the particular type trait requires a complete type, tries to complete
2573/// it. If completing the type fails, a diagnostic is emitted and false
2574/// returned. If completing the type succeeds or no completion was required,
2575/// returns true.
2576static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2577 UnaryTypeTrait UTT,
2578 SourceLocation Loc,
2579 QualType ArgTy) {
2580 // C++0x [meta.unary.prop]p3:
2581 // For all of the class templates X declared in this Clause, instantiating
2582 // that template with a template argument that is a class template
2583 // specialization may result in the implicit instantiation of the template
2584 // argument if and only if the semantics of X require that the argument
2585 // must be a complete type.
2586 // We apply this rule to all the type trait expressions used to implement
2587 // these class templates. We also try to follow any GCC documented behavior
2588 // in these expressions to ensure portability of standard libraries.
2589 switch (UTT) {
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002590 // is_complete_type somewhat obviously cannot require a complete type.
2591 case UTT_IsCompleteType:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002592 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002593
2594 // These traits are modeled on the type predicates in C++0x
2595 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2596 // requiring a complete type, as whether or not they return true cannot be
2597 // impacted by the completeness of the type.
2598 case UTT_IsVoid:
2599 case UTT_IsIntegral:
2600 case UTT_IsFloatingPoint:
2601 case UTT_IsArray:
2602 case UTT_IsPointer:
2603 case UTT_IsLvalueReference:
2604 case UTT_IsRvalueReference:
2605 case UTT_IsMemberFunctionPointer:
2606 case UTT_IsMemberObjectPointer:
2607 case UTT_IsEnum:
2608 case UTT_IsUnion:
2609 case UTT_IsClass:
2610 case UTT_IsFunction:
2611 case UTT_IsReference:
2612 case UTT_IsArithmetic:
2613 case UTT_IsFundamental:
2614 case UTT_IsObject:
2615 case UTT_IsScalar:
2616 case UTT_IsCompound:
2617 case UTT_IsMemberPointer:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002618 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002619
2620 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2621 // which requires some of its traits to have the complete type. However,
2622 // the completeness of the type cannot impact these traits' semantics, and
2623 // so they don't require it. This matches the comments on these traits in
2624 // Table 49.
2625 case UTT_IsConst:
2626 case UTT_IsVolatile:
2627 case UTT_IsSigned:
2628 case UTT_IsUnsigned:
2629 return true;
2630
2631 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002632 // applied to a complete type.
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002633 case UTT_IsTrivial:
Sean Huntfeb375d2011-05-13 00:31:07 +00002634 case UTT_IsTriviallyCopyable:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002635 case UTT_IsStandardLayout:
2636 case UTT_IsPOD:
2637 case UTT_IsLiteral:
2638 case UTT_IsEmpty:
2639 case UTT_IsPolymorphic:
2640 case UTT_IsAbstract:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002641 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002642
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002643 // These trait expressions are designed to help implement predicates in
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002644 // [meta.unary.prop] despite not being named the same. They are specified
2645 // by both GCC and the Embarcadero C++ compiler, and require the complete
2646 // type due to the overarching C++0x type predicates being implemented
2647 // requiring the complete type.
2648 case UTT_HasNothrowAssign:
2649 case UTT_HasNothrowConstructor:
2650 case UTT_HasNothrowCopy:
2651 case UTT_HasTrivialAssign:
Sean Hunt023df372011-05-09 18:22:59 +00002652 case UTT_HasTrivialDefaultConstructor:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002653 case UTT_HasTrivialCopy:
2654 case UTT_HasTrivialDestructor:
2655 case UTT_HasVirtualDestructor:
2656 // Arrays of unknown bound are expressly allowed.
2657 QualType ElTy = ArgTy;
2658 if (ArgTy->isIncompleteArrayType())
2659 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2660
2661 // The void type is expressly allowed.
2662 if (ElTy->isVoidType())
2663 return true;
2664
2665 return !S.RequireCompleteType(
2666 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleycf566412011-04-28 02:06:46 +00002667 }
Chandler Carruth73e0a912011-05-01 07:23:17 +00002668 llvm_unreachable("Type trait not handled by switch");
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002669}
2670
2671static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2672 SourceLocation KeyLoc, QualType T) {
Chandler Carruthd064c702011-05-01 08:41:10 +00002673 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleycf566412011-04-28 02:06:46 +00002674
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002675 ASTContext &C = Self.Context;
2676 switch(UTT) {
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002677 // Type trait expressions corresponding to the primary type category
2678 // predicates in C++0x [meta.unary.cat].
2679 case UTT_IsVoid:
2680 return T->isVoidType();
2681 case UTT_IsIntegral:
2682 return T->isIntegralType(C);
2683 case UTT_IsFloatingPoint:
2684 return T->isFloatingType();
2685 case UTT_IsArray:
2686 return T->isArrayType();
2687 case UTT_IsPointer:
2688 return T->isPointerType();
2689 case UTT_IsLvalueReference:
2690 return T->isLValueReferenceType();
2691 case UTT_IsRvalueReference:
2692 return T->isRValueReferenceType();
2693 case UTT_IsMemberFunctionPointer:
2694 return T->isMemberFunctionPointerType();
2695 case UTT_IsMemberObjectPointer:
2696 return T->isMemberDataPointerType();
2697 case UTT_IsEnum:
2698 return T->isEnumeralType();
Chandler Carruth28eeb382011-05-01 06:11:03 +00002699 case UTT_IsUnion:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002700 return T->isUnionType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002701 case UTT_IsClass:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002702 return T->isClassType() || T->isStructureType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002703 case UTT_IsFunction:
2704 return T->isFunctionType();
2705
2706 // Type trait expressions which correspond to the convenient composition
2707 // predicates in C++0x [meta.unary.comp].
2708 case UTT_IsReference:
2709 return T->isReferenceType();
2710 case UTT_IsArithmetic:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002711 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002712 case UTT_IsFundamental:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002713 return T->isFundamentalType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002714 case UTT_IsObject:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002715 return T->isObjectType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002716 case UTT_IsScalar:
John McCallf85e1932011-06-15 23:02:42 +00002717 // Note: semantic analysis depends on Objective-C lifetime types to be
2718 // considered scalar types. However, such types do not actually behave
2719 // like scalar types at run time (since they may require retain/release
2720 // operations), so we report them as non-scalar.
2721 if (T->isObjCLifetimeType()) {
2722 switch (T.getObjCLifetime()) {
2723 case Qualifiers::OCL_None:
2724 case Qualifiers::OCL_ExplicitNone:
2725 return true;
2726
2727 case Qualifiers::OCL_Strong:
2728 case Qualifiers::OCL_Weak:
2729 case Qualifiers::OCL_Autoreleasing:
2730 return false;
2731 }
2732 }
2733
Chandler Carruthcec0ced2011-05-01 09:29:55 +00002734 return T->isScalarType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002735 case UTT_IsCompound:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002736 return T->isCompoundType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002737 case UTT_IsMemberPointer:
2738 return T->isMemberPointerType();
2739
2740 // Type trait expressions which correspond to the type property predicates
2741 // in C++0x [meta.unary.prop].
2742 case UTT_IsConst:
2743 return T.isConstQualified();
2744 case UTT_IsVolatile:
2745 return T.isVolatileQualified();
2746 case UTT_IsTrivial:
John McCallf85e1932011-06-15 23:02:42 +00002747 return T.isTrivialType(Self.Context);
Sean Huntfeb375d2011-05-13 00:31:07 +00002748 case UTT_IsTriviallyCopyable:
John McCallf85e1932011-06-15 23:02:42 +00002749 return T.isTriviallyCopyableType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002750 case UTT_IsStandardLayout:
2751 return T->isStandardLayoutType();
2752 case UTT_IsPOD:
John McCallf85e1932011-06-15 23:02:42 +00002753 return T.isPODType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002754 case UTT_IsLiteral:
2755 return T->isLiteralType();
2756 case UTT_IsEmpty:
2757 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2758 return !RD->isUnion() && RD->isEmpty();
2759 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002760 case UTT_IsPolymorphic:
Chandler Carruth28eeb382011-05-01 06:11:03 +00002761 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2762 return RD->isPolymorphic();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002763 return false;
2764 case UTT_IsAbstract:
Chandler Carruth28eeb382011-05-01 06:11:03 +00002765 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2766 return RD->isAbstract();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002767 return false;
John Wiegley20c0da72011-04-27 23:09:49 +00002768 case UTT_IsSigned:
2769 return T->isSignedIntegerType();
John Wiegley20c0da72011-04-27 23:09:49 +00002770 case UTT_IsUnsigned:
2771 return T->isUnsignedIntegerType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002772
2773 // Type trait expressions which query classes regarding their construction,
2774 // destruction, and copying. Rather than being based directly on the
2775 // related type predicates in the standard, they are specified by both
2776 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
2777 // specifications.
2778 //
2779 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
2780 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Sean Hunt023df372011-05-09 18:22:59 +00002781 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002782 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2783 // If __is_pod (type) is true then the trait is true, else if type is
2784 // a cv class or union type (or array thereof) with a trivial default
2785 // constructor ([class.ctor]) then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002786 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002787 return true;
2788 if (const RecordType *RT =
2789 C.getBaseElementType(T)->getAs<RecordType>())
Sean Hunt023df372011-05-09 18:22:59 +00002790 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002791 return false;
2792 case UTT_HasTrivialCopy:
2793 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2794 // If __is_pod (type) is true or type is a reference type then
2795 // the trait is true, else if type is a cv class or union type
2796 // with a trivial copy constructor ([class.copy]) then the trait
2797 // is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002798 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002799 return true;
2800 if (const RecordType *RT = T->getAs<RecordType>())
2801 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2802 return false;
2803 case UTT_HasTrivialAssign:
2804 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2805 // If type is const qualified or is a reference type then the
2806 // trait is false. Otherwise if __is_pod (type) is true then the
2807 // trait is true, else if type is a cv class or union type with
2808 // a trivial copy assignment ([class.copy]) then the trait is
2809 // true, else it is false.
2810 // Note: the const and reference restrictions are interesting,
2811 // given that const and reference members don't prevent a class
2812 // from having a trivial copy assignment operator (but do cause
2813 // errors if the copy assignment operator is actually used, q.v.
2814 // [class.copy]p12).
2815
2816 if (C.getBaseElementType(T).isConstQualified())
2817 return false;
John McCallf85e1932011-06-15 23:02:42 +00002818 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002819 return true;
2820 if (const RecordType *RT = T->getAs<RecordType>())
2821 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2822 return false;
2823 case UTT_HasTrivialDestructor:
2824 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2825 // If __is_pod (type) is true or type is a reference type
2826 // then the trait is true, else if type is a cv class or union
2827 // type (or array thereof) with a trivial destructor
2828 // ([class.dtor]) then the trait is true, else it is
2829 // false.
John McCallf85e1932011-06-15 23:02:42 +00002830 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002831 return true;
John McCallf85e1932011-06-15 23:02:42 +00002832
2833 // Objective-C++ ARC: autorelease types don't require destruction.
2834 if (T->isObjCLifetimeType() &&
2835 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
2836 return true;
2837
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002838 if (const RecordType *RT =
2839 C.getBaseElementType(T)->getAs<RecordType>())
2840 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2841 return false;
2842 // TODO: Propagate nothrowness for implicitly declared special members.
2843 case UTT_HasNothrowAssign:
2844 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2845 // If type is const qualified or is a reference type then the
2846 // trait is false. Otherwise if __has_trivial_assign (type)
2847 // is true then the trait is true, else if type is a cv class
2848 // or union type with copy assignment operators that are known
2849 // not to throw an exception then the trait is true, else it is
2850 // false.
2851 if (C.getBaseElementType(T).isConstQualified())
2852 return false;
2853 if (T->isReferenceType())
2854 return false;
John McCallf85e1932011-06-15 23:02:42 +00002855 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
2856 return true;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002857 if (const RecordType *RT = T->getAs<RecordType>()) {
2858 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2859 if (RD->hasTrivialCopyAssignment())
2860 return true;
2861
2862 bool FoundAssign = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002863 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00002864 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2865 Sema::LookupOrdinaryName);
2866 if (Self.LookupQualifiedName(Res, RD)) {
2867 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2868 Op != OpEnd; ++Op) {
2869 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2870 if (Operator->isCopyAssignmentOperator()) {
2871 FoundAssign = true;
2872 const FunctionProtoType *CPT
2873 = Operator->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00002874 if (CPT->getExceptionSpecType() == EST_Delayed)
2875 return false;
2876 if (!CPT->isNothrow(Self.Context))
2877 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002878 }
2879 }
2880 }
2881
Richard Smith7a614d82011-06-11 17:19:42 +00002882 return FoundAssign;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002883 }
2884 return false;
2885 case UTT_HasNothrowCopy:
2886 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2887 // If __has_trivial_copy (type) is true then the trait is true, else
2888 // if type is a cv class or union type with copy constructors that are
2889 // known not to throw an exception then the trait is true, else it is
2890 // false.
John McCallf85e1932011-06-15 23:02:42 +00002891 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002892 return true;
2893 if (const RecordType *RT = T->getAs<RecordType>()) {
2894 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2895 if (RD->hasTrivialCopyConstructor())
2896 return true;
2897
2898 bool FoundConstructor = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002899 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002900 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00002901 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002902 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002903 // A template constructor is never a copy constructor.
2904 // FIXME: However, it may actually be selected at the actual overload
2905 // resolution point.
2906 if (isa<FunctionTemplateDecl>(*Con))
2907 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002908 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2909 if (Constructor->isCopyConstructor(FoundTQs)) {
2910 FoundConstructor = true;
2911 const FunctionProtoType *CPT
2912 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00002913 if (CPT->getExceptionSpecType() == EST_Delayed)
2914 return false;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002915 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redl751025d2010-09-13 22:02:47 +00002916 // For now, we'll be conservative and assume that they can throw.
Richard Smith7a614d82011-06-11 17:19:42 +00002917 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
2918 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002919 }
2920 }
2921
Richard Smith7a614d82011-06-11 17:19:42 +00002922 return FoundConstructor;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002923 }
2924 return false;
2925 case UTT_HasNothrowConstructor:
2926 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2927 // If __has_trivial_constructor (type) is true then the trait is
2928 // true, else if type is a cv class or union type (or array
2929 // thereof) with a default constructor that is known not to
2930 // throw an exception then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002931 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002932 return true;
2933 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2934 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Hunt023df372011-05-09 18:22:59 +00002935 if (RD->hasTrivialDefaultConstructor())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002936 return true;
2937
Sebastian Redl751025d2010-09-13 22:02:47 +00002938 DeclContext::lookup_const_iterator Con, ConEnd;
2939 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2940 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002941 // FIXME: In C++0x, a constructor template can be a default constructor.
2942 if (isa<FunctionTemplateDecl>(*Con))
2943 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00002944 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2945 if (Constructor->isDefaultConstructor()) {
2946 const FunctionProtoType *CPT
2947 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00002948 if (CPT->getExceptionSpecType() == EST_Delayed)
2949 return false;
Sebastian Redl751025d2010-09-13 22:02:47 +00002950 // TODO: check whether evaluating default arguments can throw.
2951 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002952 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
Sebastian Redl751025d2010-09-13 22:02:47 +00002953 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002954 }
2955 }
2956 return false;
2957 case UTT_HasVirtualDestructor:
2958 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2959 // If type is a class type with a virtual destructor ([class.dtor])
2960 // then the trait is true, else it is false.
2961 if (const RecordType *Record = T->getAs<RecordType>()) {
2962 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00002963 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002964 return Destructor->isVirtual();
2965 }
2966 return false;
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002967
2968 // These type trait expressions are modeled on the specifications for the
2969 // Embarcadero C++0x type trait functions:
2970 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
2971 case UTT_IsCompleteType:
2972 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
2973 // Returns True if and only if T is a complete type at the point of the
2974 // function call.
2975 return !T->isIncompleteType();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002976 }
Chandler Carruth83f563c2011-05-01 07:44:17 +00002977 llvm_unreachable("Type trait not covered by switch");
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002978}
2979
2980ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002981 SourceLocation KWLoc,
2982 TypeSourceInfo *TSInfo,
2983 SourceLocation RParen) {
2984 QualType T = TSInfo->getType();
Chandler Carrutheb65a102011-04-30 10:07:32 +00002985 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
2986 return ExprError();
Sebastian Redl64b45f72009-01-05 20:52:13 +00002987
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002988 bool Value = false;
2989 if (!T->isDependentType())
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002990 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002991
2992 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002993 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00002994}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002995
Francois Pichet6ad6f282010-12-07 00:08:36 +00002996ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
2997 SourceLocation KWLoc,
2998 ParsedType LhsTy,
2999 ParsedType RhsTy,
3000 SourceLocation RParen) {
3001 TypeSourceInfo *LhsTSInfo;
3002 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3003 if (!LhsTSInfo)
3004 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3005
3006 TypeSourceInfo *RhsTSInfo;
3007 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3008 if (!RhsTSInfo)
3009 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3010
3011 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3012}
3013
3014static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3015 QualType LhsT, QualType RhsT,
3016 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003017 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3018 "Cannot evaluate traits of dependent types");
Francois Pichet6ad6f282010-12-07 00:08:36 +00003019
3020 switch(BTT) {
John McCalld89d30f2011-01-28 22:02:36 +00003021 case BTT_IsBaseOf: {
Francois Pichet6ad6f282010-12-07 00:08:36 +00003022 // C++0x [meta.rel]p2
John McCalld89d30f2011-01-28 22:02:36 +00003023 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet6ad6f282010-12-07 00:08:36 +00003024 // Base and Derived are not unions and name the same class type without
3025 // regard to cv-qualifiers.
Francois Pichet6ad6f282010-12-07 00:08:36 +00003026
John McCalld89d30f2011-01-28 22:02:36 +00003027 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3028 if (!lhsRecord) return false;
3029
3030 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3031 if (!rhsRecord) return false;
3032
3033 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3034 == (lhsRecord == rhsRecord));
3035
3036 if (lhsRecord == rhsRecord)
3037 return !lhsRecord->getDecl()->isUnion();
3038
3039 // C++0x [meta.rel]p2:
3040 // If Base and Derived are class types and are different types
3041 // (ignoring possible cv-qualifiers) then Derived shall be a
3042 // complete type.
3043 if (Self.RequireCompleteType(KeyLoc, RhsT,
3044 diag::err_incomplete_type_used_in_type_trait_expr))
3045 return false;
3046
3047 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3048 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3049 }
John Wiegley20c0da72011-04-27 23:09:49 +00003050 case BTT_IsSame:
3051 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichetf1872372010-12-08 22:35:30 +00003052 case BTT_TypeCompatible:
3053 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3054 RhsT.getUnqualifiedType());
John Wiegley20c0da72011-04-27 23:09:49 +00003055 case BTT_IsConvertible:
Douglas Gregor9f361132011-01-27 20:28:01 +00003056 case BTT_IsConvertibleTo: {
3057 // C++0x [meta.rel]p4:
3058 // Given the following function prototype:
3059 //
3060 // template <class T>
3061 // typename add_rvalue_reference<T>::type create();
3062 //
3063 // the predicate condition for a template specialization
3064 // is_convertible<From, To> shall be satisfied if and only if
3065 // the return expression in the following code would be
3066 // well-formed, including any implicit conversions to the return
3067 // type of the function:
3068 //
3069 // To test() {
3070 // return create<From>();
3071 // }
3072 //
3073 // Access checking is performed as if in a context unrelated to To and
3074 // From. Only the validity of the immediate context of the expression
3075 // of the return-statement (including conversions to the return type)
3076 // is considered.
3077 //
3078 // We model the initialization as a copy-initialization of a temporary
3079 // of the appropriate type, which for this expression is identical to the
3080 // return statement (since NRVO doesn't apply).
3081 if (LhsT->isObjectType() || LhsT->isFunctionType())
3082 LhsT = Self.Context.getRValueReferenceType(LhsT);
3083
3084 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorb608b982011-01-28 02:26:04 +00003085 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor9f361132011-01-27 20:28:01 +00003086 Expr::getValueKindForType(LhsT));
3087 Expr *FromPtr = &From;
3088 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3089 SourceLocation()));
3090
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003091 // Perform the initialization within a SFINAE trap at translation unit
3092 // scope.
3093 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3094 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor9f361132011-01-27 20:28:01 +00003095 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003096 if (Init.Failed())
Douglas Gregor9f361132011-01-27 20:28:01 +00003097 return false;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003098
Douglas Gregor9f361132011-01-27 20:28:01 +00003099 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
3100 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3101 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003102 }
3103 llvm_unreachable("Unknown type trait or not implemented");
3104}
3105
3106ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3107 SourceLocation KWLoc,
3108 TypeSourceInfo *LhsTSInfo,
3109 TypeSourceInfo *RhsTSInfo,
3110 SourceLocation RParen) {
3111 QualType LhsT = LhsTSInfo->getType();
3112 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003113
John McCalld89d30f2011-01-28 22:02:36 +00003114 if (BTT == BTT_TypeCompatible) {
Francois Pichetf1872372010-12-08 22:35:30 +00003115 if (getLangOptions().CPlusPlus) {
3116 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3117 << SourceRange(KWLoc, RParen);
3118 return ExprError();
3119 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003120 }
3121
3122 bool Value = false;
3123 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3124 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3125
Francois Pichetf1872372010-12-08 22:35:30 +00003126 // Select trait result type.
3127 QualType ResultType;
3128 switch (BTT) {
Francois Pichetf1872372010-12-08 22:35:30 +00003129 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
John Wiegley20c0da72011-04-27 23:09:49 +00003130 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3131 case BTT_IsSame: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003132 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor9f361132011-01-27 20:28:01 +00003133 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003134 }
3135
Francois Pichet6ad6f282010-12-07 00:08:36 +00003136 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3137 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00003138 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00003139}
3140
John Wiegley21ff2e52011-04-28 00:16:57 +00003141ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3142 SourceLocation KWLoc,
3143 ParsedType Ty,
3144 Expr* DimExpr,
3145 SourceLocation RParen) {
3146 TypeSourceInfo *TSInfo;
3147 QualType T = GetTypeFromParser(Ty, &TSInfo);
3148 if (!TSInfo)
3149 TSInfo = Context.getTrivialTypeSourceInfo(T);
3150
3151 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3152}
3153
3154static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3155 QualType T, Expr *DimExpr,
3156 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003157 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley21ff2e52011-04-28 00:16:57 +00003158
3159 switch(ATT) {
3160 case ATT_ArrayRank:
3161 if (T->isArrayType()) {
3162 unsigned Dim = 0;
3163 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3164 ++Dim;
3165 T = AT->getElementType();
3166 }
3167 return Dim;
John Wiegley21ff2e52011-04-28 00:16:57 +00003168 }
John Wiegleycf566412011-04-28 02:06:46 +00003169 return 0;
3170
John Wiegley21ff2e52011-04-28 00:16:57 +00003171 case ATT_ArrayExtent: {
3172 llvm::APSInt Value;
3173 uint64_t Dim;
John Wiegleycf566412011-04-28 02:06:46 +00003174 if (DimExpr->isIntegerConstantExpr(Value, Self.Context, 0, false)) {
3175 if (Value < llvm::APSInt(Value.getBitWidth(), Value.isUnsigned())) {
3176 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3177 DimExpr->getSourceRange();
3178 return false;
3179 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003180 Dim = Value.getLimitedValue();
John Wiegleycf566412011-04-28 02:06:46 +00003181 } else {
3182 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3183 DimExpr->getSourceRange();
3184 return false;
3185 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003186
3187 if (T->isArrayType()) {
3188 unsigned D = 0;
3189 bool Matched = false;
3190 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3191 if (Dim == D) {
3192 Matched = true;
3193 break;
3194 }
3195 ++D;
3196 T = AT->getElementType();
3197 }
3198
John Wiegleycf566412011-04-28 02:06:46 +00003199 if (Matched && T->isArrayType()) {
3200 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3201 return CAT->getSize().getLimitedValue();
3202 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003203 }
John Wiegleycf566412011-04-28 02:06:46 +00003204 return 0;
John Wiegley21ff2e52011-04-28 00:16:57 +00003205 }
3206 }
3207 llvm_unreachable("Unknown type trait or not implemented");
3208}
3209
3210ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3211 SourceLocation KWLoc,
3212 TypeSourceInfo *TSInfo,
3213 Expr* DimExpr,
3214 SourceLocation RParen) {
3215 QualType T = TSInfo->getType();
John Wiegley21ff2e52011-04-28 00:16:57 +00003216
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003217 // FIXME: This should likely be tracked as an APInt to remove any host
3218 // assumptions about the width of size_t on the target.
Chandler Carruthd064c702011-05-01 08:41:10 +00003219 uint64_t Value = 0;
3220 if (!T->isDependentType())
3221 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3222
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003223 // While the specification for these traits from the Embarcadero C++
3224 // compiler's documentation says the return type is 'unsigned int', Clang
3225 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3226 // compiler, there is no difference. On several other platforms this is an
3227 // important distinction.
John Wiegley21ff2e52011-04-28 00:16:57 +00003228 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
Chandler Carruth06207f62011-05-01 07:49:26 +00003229 DimExpr, RParen,
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003230 Context.getSizeType()));
John Wiegley21ff2e52011-04-28 00:16:57 +00003231}
3232
John Wiegley55262202011-04-25 06:54:41 +00003233ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003234 SourceLocation KWLoc,
3235 Expr *Queried,
3236 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003237 // If error parsing the expression, ignore.
3238 if (!Queried)
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003239 return ExprError();
John Wiegley55262202011-04-25 06:54:41 +00003240
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003241 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegley55262202011-04-25 06:54:41 +00003242
3243 return move(Result);
3244}
3245
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003246static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3247 switch (ET) {
3248 case ET_IsLValueExpr: return E->isLValue();
3249 case ET_IsRValueExpr: return E->isRValue();
3250 }
3251 llvm_unreachable("Expression trait not covered by switch");
3252}
3253
John Wiegley55262202011-04-25 06:54:41 +00003254ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003255 SourceLocation KWLoc,
3256 Expr *Queried,
3257 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003258 if (Queried->isTypeDependent()) {
3259 // Delay type-checking for type-dependent expressions.
3260 } else if (Queried->getType()->isPlaceholderType()) {
3261 ExprResult PE = CheckPlaceholderExpr(Queried);
3262 if (PE.isInvalid()) return ExprError();
3263 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3264 }
3265
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003266 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf7ef0002011-05-01 08:48:19 +00003267
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003268 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3269 RParen, Context.BoolTy));
John Wiegley55262202011-04-25 06:54:41 +00003270}
3271
Richard Trieudd225092011-09-15 21:56:47 +00003272QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCallf89e55a2010-11-18 06:31:45 +00003273 ExprValueKind &VK,
3274 SourceLocation Loc,
3275 bool isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003276 assert(!LHS.get()->getType()->isPlaceholderType() &&
3277 !RHS.get()->getType()->isPlaceholderType() &&
John McCallea4aba02011-06-30 17:15:34 +00003278 "placeholders should have been weeded out by now");
3279
3280 // The LHS undergoes lvalue conversions if this is ->*.
3281 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003282 LHS = DefaultLvalueConversion(LHS.take());
3283 if (LHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003284 }
3285
3286 // The RHS always undergoes lvalue conversions.
Richard Trieudd225092011-09-15 21:56:47 +00003287 RHS = DefaultLvalueConversion(RHS.take());
3288 if (RHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003289
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003290 const char *OpSpelling = isIndirect ? "->*" : ".*";
3291 // C++ 5.5p2
3292 // The binary operator .* [p3: ->*] binds its second operand, which shall
3293 // be of type "pointer to member of T" (where T is a completely-defined
3294 // class type) [...]
Richard Trieudd225092011-09-15 21:56:47 +00003295 QualType RHSType = RHS.get()->getType();
3296 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00003297 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003298 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieudd225092011-09-15 21:56:47 +00003299 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003300 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00003301 }
Douglas Gregore7450f52009-03-24 19:52:54 +00003302
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003303 QualType Class(MemPtr->getClass(), 0);
3304
Douglas Gregor7d520ba2010-10-13 20:41:14 +00003305 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3306 // member pointer points must be completely-defined. However, there is no
3307 // reason for this semantic distinction, and the rule is not enforced by
3308 // other compilers. Therefore, we do not check this property, as it is
3309 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00003310
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003311 // C++ 5.5p2
3312 // [...] to its first operand, which shall be of class T or of a class of
3313 // which T is an unambiguous and accessible base class. [p3: a pointer to
3314 // such a class]
Richard Trieudd225092011-09-15 21:56:47 +00003315 QualType LHSType = LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003316 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003317 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
3318 LHSType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003319 else {
3320 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieudd225092011-09-15 21:56:47 +00003321 << OpSpelling << 1 << LHSType
Douglas Gregor849b2432010-03-31 17:46:05 +00003322 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003323 return QualType();
3324 }
3325 }
3326
Richard Trieudd225092011-09-15 21:56:47 +00003327 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00003328 // If we want to check the hierarchy, we need a complete type.
Richard Trieudd225092011-09-15 21:56:47 +00003329 if (RequireCompleteType(Loc, LHSType, PDiag(diag::err_bad_memptr_lhs)
Sebastian Redl17e1d352010-04-23 17:18:26 +00003330 << OpSpelling << (int)isIndirect)) {
3331 return QualType();
3332 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003333 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00003334 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00003335 // FIXME: Would it be useful to print full ambiguity paths, or is that
3336 // overkill?
Richard Trieudd225092011-09-15 21:56:47 +00003337 if (!IsDerivedFrom(LHSType, Class, Paths) ||
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003338 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3339 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieudd225092011-09-15 21:56:47 +00003340 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003341 return QualType();
3342 }
Eli Friedman3005efe2010-01-16 00:00:48 +00003343 // Cast LHS to type of use.
3344 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
John McCall5baba9d2010-08-25 10:28:54 +00003345 ExprValueKind VK =
Richard Trieudd225092011-09-15 21:56:47 +00003346 isIndirect ? VK_RValue : CastCategory(LHS.get());
Sebastian Redl906082e2010-07-20 04:20:21 +00003347
John McCallf871d0c2010-08-07 06:22:56 +00003348 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003349 BuildBasePathArray(Paths, BasePath);
Richard Trieudd225092011-09-15 21:56:47 +00003350 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
3351 &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003352 }
3353
Richard Trieudd225092011-09-15 21:56:47 +00003354 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00003355 // Diagnose use of pointer-to-member type which when used as
3356 // the functional cast in a pointer-to-member expression.
3357 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3358 return QualType();
3359 }
John McCallf89e55a2010-11-18 06:31:45 +00003360
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003361 // C++ 5.5p2
3362 // The result is an object or a function of the type specified by the
3363 // second operand.
3364 // The cv qualifiers are the union of those in the pointer and the left side,
3365 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003366 QualType Result = MemPtr->getPointeeType();
Richard Trieudd225092011-09-15 21:56:47 +00003367 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00003368
Douglas Gregor6b4df912011-01-26 16:40:18 +00003369 // C++0x [expr.mptr.oper]p6:
3370 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003371 // ill-formed if the second operand is a pointer to member function with
3372 // ref-qualifier &. In a ->* expression or in a .* expression whose object
3373 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor6b4df912011-01-26 16:40:18 +00003374 // is a pointer to member function with ref-qualifier &&.
3375 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3376 switch (Proto->getRefQualifier()) {
3377 case RQ_None:
3378 // Do nothing
3379 break;
3380
3381 case RQ_LValue:
Richard Trieudd225092011-09-15 21:56:47 +00003382 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003383 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003384 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003385 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003386
Douglas Gregor6b4df912011-01-26 16:40:18 +00003387 case RQ_RValue:
Richard Trieudd225092011-09-15 21:56:47 +00003388 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003389 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003390 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003391 break;
3392 }
3393 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003394
John McCallf89e55a2010-11-18 06:31:45 +00003395 // C++ [expr.mptr.oper]p6:
3396 // The result of a .* expression whose second operand is a pointer
3397 // to a data member is of the same value category as its
3398 // first operand. The result of a .* expression whose second
3399 // operand is a pointer to a member function is a prvalue. The
3400 // result of an ->* expression is an lvalue if its second operand
3401 // is a pointer to data member and a prvalue otherwise.
John McCall864c0412011-04-26 20:42:42 +00003402 if (Result->isFunctionType()) {
John McCallf89e55a2010-11-18 06:31:45 +00003403 VK = VK_RValue;
John McCall864c0412011-04-26 20:42:42 +00003404 return Context.BoundMemberTy;
3405 } else if (isIndirect) {
John McCallf89e55a2010-11-18 06:31:45 +00003406 VK = VK_LValue;
John McCall864c0412011-04-26 20:42:42 +00003407 } else {
Richard Trieudd225092011-09-15 21:56:47 +00003408 VK = LHS.get()->getValueKind();
John McCall864c0412011-04-26 20:42:42 +00003409 }
John McCallf89e55a2010-11-18 06:31:45 +00003410
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003411 return Result;
3412}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003413
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003414/// \brief Try to convert a type to another according to C++0x 5.16p3.
3415///
3416/// This is part of the parameter validation for the ? operator. If either
3417/// value operand is a class type, the two operands are attempted to be
3418/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003419/// It returns true if the program is ill-formed and has already been diagnosed
3420/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003421static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3422 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00003423 bool &HaveConversion,
3424 QualType &ToType) {
3425 HaveConversion = false;
3426 ToType = To->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003427
3428 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003429 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003430 // C++0x 5.16p3
3431 // The process for determining whether an operand expression E1 of type T1
3432 // can be converted to match an operand expression E2 of type T2 is defined
3433 // as follows:
3434 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00003435 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003436 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003437 // E1 can be converted to match E2 if E1 can be implicitly converted to
3438 // type "lvalue reference to T2", subject to the constraint that in the
3439 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003440 QualType T = Self.Context.getLValueReferenceType(ToType);
3441 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003442
Douglas Gregorb70cf442010-03-26 20:14:36 +00003443 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3444 if (InitSeq.isDirectReferenceBinding()) {
3445 ToType = T;
3446 HaveConversion = true;
3447 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003448 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003449
Douglas Gregorb70cf442010-03-26 20:14:36 +00003450 if (InitSeq.isAmbiguous())
3451 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003452 }
John McCallb1bdc622010-02-25 01:37:24 +00003453
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003454 // -- If E2 is an rvalue, or if the conversion above cannot be done:
3455 // -- if E1 and E2 have class type, and the underlying class types are
3456 // the same or one is a base class of the other:
3457 QualType FTy = From->getType();
3458 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003459 const RecordType *FRec = FTy->getAs<RecordType>();
3460 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003461 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003462 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003463 if (FRec && TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003464 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003465 // E1 can be converted to match E2 if the class of T2 is the
3466 // same type as, or a base class of, the class of T1, and
3467 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00003468 if (FRec == TRec || FDerivedFromT) {
3469 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003470 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3471 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003472 if (InitSeq) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003473 HaveConversion = true;
3474 return false;
3475 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003476
Douglas Gregorb70cf442010-03-26 20:14:36 +00003477 if (InitSeq.isAmbiguous())
3478 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003479 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003480 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003481
Douglas Gregorb70cf442010-03-26 20:14:36 +00003482 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003483 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003484
Douglas Gregorb70cf442010-03-26 20:14:36 +00003485 // -- Otherwise: E1 can be converted to match E2 if E1 can be
3486 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003487 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003488 // an rvalue).
3489 //
3490 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3491 // to the array-to-pointer or function-to-pointer conversions.
3492 if (!TTy->getAs<TagType>())
3493 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003494
Douglas Gregorb70cf442010-03-26 20:14:36 +00003495 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3496 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003497 HaveConversion = !InitSeq.Failed();
Douglas Gregorb70cf442010-03-26 20:14:36 +00003498 ToType = TTy;
3499 if (InitSeq.isAmbiguous())
3500 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3501
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003502 return false;
3503}
3504
3505/// \brief Try to find a common type for two according to C++0x 5.16p5.
3506///
3507/// This is part of the parameter validation for the ? operator. If either
3508/// value operand is a class type, overload resolution is used to find a
3509/// conversion to a common type.
John Wiegley429bb272011-04-08 18:41:53 +00003510static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth82214a82011-02-18 23:54:50 +00003511 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00003512 Expr *Args[2] = { LHS.get(), RHS.get() };
Chandler Carruth82214a82011-02-18 23:54:50 +00003513 OverloadCandidateSet CandidateSet(QuestionLoc);
3514 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3515 CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003516
3517 OverloadCandidateSet::iterator Best;
Chandler Carruth82214a82011-02-18 23:54:50 +00003518 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley429bb272011-04-08 18:41:53 +00003519 case OR_Success: {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003520 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley429bb272011-04-08 18:41:53 +00003521 ExprResult LHSRes =
3522 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3523 Best->Conversions[0], Sema::AA_Converting);
3524 if (LHSRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003525 break;
John Wiegley429bb272011-04-08 18:41:53 +00003526 LHS = move(LHSRes);
3527
3528 ExprResult RHSRes =
3529 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3530 Best->Conversions[1], Sema::AA_Converting);
3531 if (RHSRes.isInvalid())
3532 break;
3533 RHS = move(RHSRes);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003534 if (Best->Function)
3535 Self.MarkDeclarationReferenced(QuestionLoc, Best->Function);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003536 return false;
John Wiegley429bb272011-04-08 18:41:53 +00003537 }
3538
Douglas Gregor20093b42009-12-09 23:02:17 +00003539 case OR_No_Viable_Function:
Chandler Carruth82214a82011-02-18 23:54:50 +00003540
3541 // Emit a better diagnostic if one of the expressions is a null pointer
3542 // constant and the other is a pointer type. In this case, the user most
3543 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00003544 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00003545 return true;
3546
3547 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003548 << LHS.get()->getType() << RHS.get()->getType()
3549 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003550 return true;
3551
Douglas Gregor20093b42009-12-09 23:02:17 +00003552 case OR_Ambiguous:
Chandler Carruth82214a82011-02-18 23:54:50 +00003553 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley429bb272011-04-08 18:41:53 +00003554 << LHS.get()->getType() << RHS.get()->getType()
3555 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00003556 // FIXME: Print the possible common types by printing the return types of
3557 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003558 break;
3559
Douglas Gregor20093b42009-12-09 23:02:17 +00003560 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003561 assert(false && "Conditional operator has only built-in overloads");
3562 break;
3563 }
3564 return true;
3565}
3566
Sebastian Redl76458502009-04-17 16:30:52 +00003567/// \brief Perform an "extended" implicit conversion as returned by
3568/// TryClassUnification.
John Wiegley429bb272011-04-08 18:41:53 +00003569static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003570 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley429bb272011-04-08 18:41:53 +00003571 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003572 SourceLocation());
John Wiegley429bb272011-04-08 18:41:53 +00003573 Expr *Arg = E.take();
3574 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
3575 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00003576 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00003577 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003578
John Wiegley429bb272011-04-08 18:41:53 +00003579 E = Result;
Sebastian Redl76458502009-04-17 16:30:52 +00003580 return false;
3581}
3582
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003583/// \brief Check the operands of ?: under C++ semantics.
3584///
3585/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
3586/// extension. In this case, LHS == Cond. (But they're not aliases.)
John Wiegley429bb272011-04-08 18:41:53 +00003587QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCall56ca35d2011-02-17 10:25:35 +00003588 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003589 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00003590 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
3591 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003592
3593 // C++0x 5.16p1
3594 // The first expression is contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00003595 if (!Cond.get()->isTypeDependent()) {
3596 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
3597 if (CondRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003598 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003599 Cond = move(CondRes);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003600 }
3601
John McCallf89e55a2010-11-18 06:31:45 +00003602 // Assume r-value.
3603 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00003604 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00003605
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003606 // Either of the arguments dependent?
John Wiegley429bb272011-04-08 18:41:53 +00003607 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003608 return Context.DependentTy;
3609
3610 // C++0x 5.16p2
3611 // If either the second or the third operand has type (cv) void, ...
John Wiegley429bb272011-04-08 18:41:53 +00003612 QualType LTy = LHS.get()->getType();
3613 QualType RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003614 bool LVoid = LTy->isVoidType();
3615 bool RVoid = RTy->isVoidType();
3616 if (LVoid || RVoid) {
3617 // ... then the [l2r] conversions are performed on the second and third
3618 // operands ...
John Wiegley429bb272011-04-08 18:41:53 +00003619 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3620 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3621 if (LHS.isInvalid() || RHS.isInvalid())
3622 return QualType();
3623 LTy = LHS.get()->getType();
3624 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003625
3626 // ... and one of the following shall hold:
3627 // -- The second or the third operand (but not both) is a throw-
3628 // expression; the result is of the type of the other and is an rvalue.
John Wiegley429bb272011-04-08 18:41:53 +00003629 bool LThrow = isa<CXXThrowExpr>(LHS.get());
3630 bool RThrow = isa<CXXThrowExpr>(RHS.get());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003631 if (LThrow && !RThrow)
3632 return RTy;
3633 if (RThrow && !LThrow)
3634 return LTy;
3635
3636 // -- Both the second and third operands have type void; the result is of
3637 // type void and is an rvalue.
3638 if (LVoid && RVoid)
3639 return Context.VoidTy;
3640
3641 // Neither holds, error.
3642 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3643 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley429bb272011-04-08 18:41:53 +00003644 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003645 return QualType();
3646 }
3647
3648 // Neither is void.
3649
3650 // C++0x 5.16p3
3651 // Otherwise, if the second and third operand have different types, and
3652 // either has (cv) class type, and attempt is made to convert each of those
3653 // operands to the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003654 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003655 (LTy->isRecordType() || RTy->isRecordType())) {
3656 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3657 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003658 QualType L2RType, R2LType;
3659 bool HaveL2R, HaveR2L;
John Wiegley429bb272011-04-08 18:41:53 +00003660 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003661 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003662 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003663 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003664
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003665 // If both can be converted, [...] the program is ill-formed.
3666 if (HaveL2R && HaveR2L) {
3667 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley429bb272011-04-08 18:41:53 +00003668 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003669 return QualType();
3670 }
3671
3672 // If exactly one conversion is possible, that conversion is applied to
3673 // the chosen operand and the converted operands are used in place of the
3674 // original operands for the remainder of this section.
3675 if (HaveL2R) {
John Wiegley429bb272011-04-08 18:41:53 +00003676 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003677 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003678 LTy = LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003679 } else if (HaveR2L) {
John Wiegley429bb272011-04-08 18:41:53 +00003680 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003681 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003682 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003683 }
3684 }
3685
3686 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00003687 // If the second and third operands are glvalues of the same value
3688 // category and have the same type, the result is of that type and
3689 // value category and it is a bit-field if the second or the third
3690 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00003691 // We only extend this to bitfields, not to the crazy other kinds of
3692 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003693 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00003694 if (Same &&
John Wiegley429bb272011-04-08 18:41:53 +00003695 LHS.get()->isGLValue() &&
3696 LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
3697 LHS.get()->isOrdinaryOrBitFieldObject() &&
3698 RHS.get()->isOrdinaryOrBitFieldObject()) {
3699 VK = LHS.get()->getValueKind();
3700 if (LHS.get()->getObjectKind() == OK_BitField ||
3701 RHS.get()->getObjectKind() == OK_BitField)
John McCall09431682010-11-18 19:01:18 +00003702 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00003703 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00003704 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003705
3706 // C++0x 5.16p5
3707 // Otherwise, the result is an rvalue. If the second and third operands
3708 // do not have the same type, and either has (cv) class type, ...
3709 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3710 // ... overload resolution is used to determine the conversions (if any)
3711 // to be applied to the operands. If the overload resolution fails, the
3712 // program is ill-formed.
3713 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3714 return QualType();
3715 }
3716
3717 // C++0x 5.16p6
3718 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3719 // conversions are performed on the second and third operands.
John Wiegley429bb272011-04-08 18:41:53 +00003720 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3721 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3722 if (LHS.isInvalid() || RHS.isInvalid())
3723 return QualType();
3724 LTy = LHS.get()->getType();
3725 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003726
3727 // After those conversions, one of the following shall hold:
3728 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00003729 // is of that type. If the operands have class type, the result
3730 // is a prvalue temporary of the result type, which is
3731 // copy-initialized from either the second operand or the third
3732 // operand depending on the value of the first operand.
3733 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3734 if (LTy->isRecordType()) {
3735 // The operands have class type. Make a temporary copy.
3736 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003737 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3738 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00003739 LHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00003740 if (LHSCopy.isInvalid())
3741 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003742
3743 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3744 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00003745 RHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00003746 if (RHSCopy.isInvalid())
3747 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003748
John Wiegley429bb272011-04-08 18:41:53 +00003749 LHS = LHSCopy;
3750 RHS = RHSCopy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003751 }
3752
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003753 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003754 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003755
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003756 // Extension: conditional operator involving vector types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003757 if (LTy->isVectorType() || RTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00003758 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003759
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003760 // -- The second and third operands have arithmetic or enumeration type;
3761 // the usual arithmetic conversions are performed to bring them to a
3762 // common type, and the result is of that type.
3763 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3764 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00003765 if (LHS.isInvalid() || RHS.isInvalid())
3766 return QualType();
3767 return LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003768 }
3769
3770 // -- The second and third operands have pointer type, or one has pointer
3771 // type and the other is a null pointer constant; pointer conversions
3772 // and qualification conversions are performed to bring them to their
3773 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00003774 // -- The second and third operands have pointer to member type, or one has
3775 // pointer to member type and the other is a null pointer constant;
3776 // pointer to member conversions and qualification conversions are
3777 // performed to bring them to a common type, whose cv-qualification
3778 // shall match the cv-qualification of either the second or the third
3779 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003780 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003781 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003782 isSFINAEContext()? 0 : &NonStandardCompositeType);
3783 if (!Composite.isNull()) {
3784 if (NonStandardCompositeType)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003785 Diag(QuestionLoc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003786 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3787 << LTy << RTy << Composite
John Wiegley429bb272011-04-08 18:41:53 +00003788 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003789
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003790 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003791 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003792
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003793 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00003794 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3795 if (!Composite.isNull())
3796 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003797
Chandler Carruth7ef93242011-02-19 00:13:59 +00003798 // Check if we are using a null with a non-pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00003799 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth7ef93242011-02-19 00:13:59 +00003800 return QualType();
3801
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003802 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003803 << LHS.get()->getType() << RHS.get()->getType()
3804 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003805 return QualType();
3806}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003807
3808/// \brief Find a merged pointer type and convert the two expressions to it.
3809///
Douglas Gregor20b3e992009-08-24 17:42:35 +00003810/// This finds the composite pointer type (or member pointer type) for @p E1
3811/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3812/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003813/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003814///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003815/// \param Loc The location of the operator requiring these two expressions to
3816/// be converted to the composite pointer type.
3817///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003818/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3819/// a non-standard (but still sane) composite type to which both expressions
3820/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3821/// will be set true.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003822QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003823 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003824 bool *NonStandardCompositeType) {
3825 if (NonStandardCompositeType)
3826 *NonStandardCompositeType = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003827
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003828 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3829 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003830
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00003831 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3832 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00003833 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003834
3835 // C++0x 5.9p2
3836 // Pointer conversions and qualification conversions are performed on
3837 // pointer operands to bring them to their composite pointer type. If
3838 // one operand is a null pointer constant, the composite pointer type is
3839 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00003840 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003841 if (T2->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00003842 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003843 else
John Wiegley429bb272011-04-08 18:41:53 +00003844 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003845 return T2;
3846 }
Douglas Gregorce940492009-09-25 04:25:58 +00003847 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003848 if (T1->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00003849 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003850 else
John Wiegley429bb272011-04-08 18:41:53 +00003851 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003852 return T1;
3853 }
Mike Stump1eb44332009-09-09 15:08:12 +00003854
Douglas Gregor20b3e992009-08-24 17:42:35 +00003855 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003856 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3857 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003858 return QualType();
3859
3860 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3861 // the other has type "pointer to cv2 T" and the composite pointer type is
3862 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3863 // Otherwise, the composite pointer type is a pointer type similar to the
3864 // type of one of the operands, with a cv-qualification signature that is
3865 // the union of the cv-qualification signatures of the operand types.
3866 // In practice, the first part here is redundant; it's subsumed by the second.
3867 // What we do here is, we build the two possible composite types, and try the
3868 // conversions in both directions. If only one works, or if the two composite
3869 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00003870 // FIXME: extended qualifiers?
Chris Lattner5f9e2722011-07-23 10:55:15 +00003871 typedef SmallVector<unsigned, 4> QualifierVector;
Sebastian Redla439e6f2009-11-16 21:03:45 +00003872 QualifierVector QualifierUnion;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003873 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
Sebastian Redla439e6f2009-11-16 21:03:45 +00003874 ContainingClassVector;
3875 ContainingClassVector MemberOfClass;
3876 QualType Composite1 = Context.getCanonicalType(T1),
3877 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003878 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00003879 do {
3880 const PointerType *Ptr1, *Ptr2;
3881 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3882 (Ptr2 = Composite2->getAs<PointerType>())) {
3883 Composite1 = Ptr1->getPointeeType();
3884 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003885
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003886 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003887 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003888 if (NonStandardCompositeType &&
3889 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3890 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003891
Douglas Gregor20b3e992009-08-24 17:42:35 +00003892 QualifierUnion.push_back(
3893 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3894 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3895 continue;
3896 }
Mike Stump1eb44332009-09-09 15:08:12 +00003897
Douglas Gregor20b3e992009-08-24 17:42:35 +00003898 const MemberPointerType *MemPtr1, *MemPtr2;
3899 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3900 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3901 Composite1 = MemPtr1->getPointeeType();
3902 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003903
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003904 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003905 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003906 if (NonStandardCompositeType &&
3907 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3908 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003909
Douglas Gregor20b3e992009-08-24 17:42:35 +00003910 QualifierUnion.push_back(
3911 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3912 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3913 MemPtr2->getClass()));
3914 continue;
3915 }
Mike Stump1eb44332009-09-09 15:08:12 +00003916
Douglas Gregor20b3e992009-08-24 17:42:35 +00003917 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00003918
Douglas Gregor20b3e992009-08-24 17:42:35 +00003919 // Cannot unwrap any more types.
3920 break;
3921 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00003922
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003923 if (NeedConstBefore && NonStandardCompositeType) {
3924 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003925 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003926 // requirements of C++ [conv.qual]p4 bullet 3.
3927 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3928 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3929 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3930 *NonStandardCompositeType = true;
3931 }
3932 }
3933 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003934
Douglas Gregor20b3e992009-08-24 17:42:35 +00003935 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003936 ContainingClassVector::reverse_iterator MOC
3937 = MemberOfClass.rbegin();
3938 for (QualifierVector::reverse_iterator
3939 I = QualifierUnion.rbegin(),
3940 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00003941 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00003942 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003943 if (MOC->first && MOC->second) {
3944 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00003945 Composite1 = Context.getMemberPointerType(
3946 Context.getQualifiedType(Composite1, Quals),
3947 MOC->first);
3948 Composite2 = Context.getMemberPointerType(
3949 Context.getQualifiedType(Composite2, Quals),
3950 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003951 } else {
3952 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00003953 Composite1
3954 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3955 Composite2
3956 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00003957 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003958 }
3959
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003960 // Try to convert to the first composite pointer type.
3961 InitializedEntity Entity1
3962 = InitializedEntity::InitializeTemporary(Composite1);
3963 InitializationKind Kind
3964 = InitializationKind::CreateCopy(Loc, SourceLocation());
3965 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3966 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00003967
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003968 if (E1ToC1 && E2ToC1) {
3969 // Conversion to Composite1 is viable.
3970 if (!Context.hasSameType(Composite1, Composite2)) {
3971 // Composite2 is a different type from Composite1. Check whether
3972 // Composite2 is also viable.
3973 InitializedEntity Entity2
3974 = InitializedEntity::InitializeTemporary(Composite2);
3975 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3976 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3977 if (E1ToC2 && E2ToC2) {
3978 // Both Composite1 and Composite2 are viable and are different;
3979 // this is an ambiguity.
3980 return QualType();
3981 }
3982 }
3983
3984 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003985 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00003986 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003987 if (E1Result.isInvalid())
3988 return QualType();
3989 E1 = E1Result.takeAs<Expr>();
3990
3991 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003992 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00003993 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003994 if (E2Result.isInvalid())
3995 return QualType();
3996 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003997
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003998 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003999 }
4000
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004001 // Check whether Composite2 is viable.
4002 InitializedEntity Entity2
4003 = InitializedEntity::InitializeTemporary(Composite2);
4004 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4005 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4006 if (!E1ToC2 || !E2ToC2)
4007 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004008
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004009 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004010 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004011 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004012 if (E1Result.isInvalid())
4013 return QualType();
4014 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004015
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004016 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004017 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004018 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004019 if (E2Result.isInvalid())
4020 return QualType();
4021 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004022
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004023 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004024}
Anders Carlsson165a0a02009-05-17 18:41:29 +00004025
John McCall60d7b3a2010-08-24 06:29:42 +00004026ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00004027 if (!E)
4028 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004029
John McCallf85e1932011-06-15 23:02:42 +00004030 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4031
4032 // If the result is a glvalue, we shouldn't bind it.
4033 if (!E->isRValue())
Anders Carlsson089c2602009-08-15 23:41:35 +00004034 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004035
John McCallf85e1932011-06-15 23:02:42 +00004036 // In ARC, calls that return a retainable type can return retained,
4037 // in which case we have to insert a consuming cast.
4038 if (getLangOptions().ObjCAutoRefCount &&
4039 E->getType()->isObjCRetainableType()) {
4040
4041 bool ReturnsRetained;
4042
4043 // For actual calls, we compute this by examining the type of the
4044 // called value.
4045 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4046 Expr *Callee = Call->getCallee()->IgnoreParens();
4047 QualType T = Callee->getType();
4048
4049 if (T == Context.BoundMemberTy) {
4050 // Handle pointer-to-members.
4051 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4052 T = BinOp->getRHS()->getType();
4053 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4054 T = Mem->getMemberDecl()->getType();
4055 }
4056
4057 if (const PointerType *Ptr = T->getAs<PointerType>())
4058 T = Ptr->getPointeeType();
4059 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4060 T = Ptr->getPointeeType();
4061 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4062 T = MemPtr->getPointeeType();
4063
4064 const FunctionType *FTy = T->getAs<FunctionType>();
4065 assert(FTy && "call to value not of function type?");
4066 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4067
4068 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4069 // type always produce a +1 object.
4070 } else if (isa<StmtExpr>(E)) {
4071 ReturnsRetained = true;
4072
4073 // For message sends and property references, we try to find an
4074 // actual method. FIXME: we should infer retention by selector in
4075 // cases where we don't have an actual method.
4076 } else {
John McCallfc4b1912011-08-03 07:02:44 +00004077 ObjCMethodDecl *D = 0;
John McCallf85e1932011-06-15 23:02:42 +00004078 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4079 D = Send->getMethodDecl();
4080 } else {
4081 CastExpr *CE = cast<CastExpr>(E);
John McCallf85e1932011-06-15 23:02:42 +00004082 assert(CE->getCastKind() == CK_GetObjCProperty);
4083 const ObjCPropertyRefExpr *PRE = CE->getSubExpr()->getObjCProperty();
4084 D = (PRE->isImplicitProperty() ? PRE->getImplicitPropertyGetter() : 0);
4085 }
4086
4087 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCallfc4b1912011-08-03 07:02:44 +00004088
4089 // Don't do reclaims on performSelector calls; despite their
4090 // return type, the invoked method doesn't necessarily actually
4091 // return an object.
4092 if (!ReturnsRetained &&
4093 D && D->getMethodFamily() == OMF_performSelector)
4094 return Owned(E);
John McCallf85e1932011-06-15 23:02:42 +00004095 }
4096
John McCall7e5e5f42011-07-07 06:58:02 +00004097 ExprNeedsCleanups = true;
4098
John McCall33e56f32011-09-10 06:18:15 +00004099 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4100 : CK_ARCReclaimReturnedObject);
John McCall7e5e5f42011-07-07 06:58:02 +00004101 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4102 VK_RValue));
John McCallf85e1932011-06-15 23:02:42 +00004103 }
4104
4105 if (!getLangOptions().CPlusPlus)
4106 return Owned(E);
Douglas Gregor51326552009-12-24 18:51:59 +00004107
Ted Kremenek6217b802009-07-29 21:53:49 +00004108 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00004109 if (!RT)
4110 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004111
John McCall86ff3082010-02-04 22:26:26 +00004112 // That should be enough to guarantee that this type is complete.
4113 // If it has a trivial destructor, we can avoid the extra copy.
Jeffrey Yasskinb7ee2e52011-01-27 19:17:54 +00004114 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall507384f2010-08-12 02:40:37 +00004115 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00004116 return Owned(E);
4117
John McCallf85e1932011-06-15 23:02:42 +00004118 CXXDestructorDecl *Destructor = LookupDestructor(RD);
4119
4120 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
4121 if (Destructor) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00004122 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00004123 CheckDestructorAccess(E->getExprLoc(), Destructor,
4124 PDiag(diag::err_access_dtor_temp)
4125 << E->getType());
John McCallf85e1932011-06-15 23:02:42 +00004126
4127 ExprTemporaries.push_back(Temp);
4128 ExprNeedsCleanups = true;
John McCallc91cc662010-04-07 00:41:46 +00004129 }
Anders Carlssondef11992009-05-30 20:36:53 +00004130 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
4131}
4132
John McCall4765fa02010-12-06 08:20:24 +00004133Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00004134 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00004135
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00004136 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
4137 assert(ExprTemporaries.size() >= FirstTemporary);
John McCallf85e1932011-06-15 23:02:42 +00004138 assert(ExprNeedsCleanups || ExprTemporaries.size() == FirstTemporary);
4139 if (!ExprNeedsCleanups)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00004140 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00004141
John McCall4765fa02010-12-06 08:20:24 +00004142 Expr *E = ExprWithCleanups::Create(Context, SubExpr,
John McCallf85e1932011-06-15 23:02:42 +00004143 ExprTemporaries.begin() + FirstTemporary,
John McCall4765fa02010-12-06 08:20:24 +00004144 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00004145 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
4146 ExprTemporaries.end());
John McCallf85e1932011-06-15 23:02:42 +00004147 ExprNeedsCleanups = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004148
Anders Carlsson99ba36d2009-06-05 15:38:08 +00004149 return E;
4150}
4151
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004152ExprResult
John McCall4765fa02010-12-06 08:20:24 +00004153Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004154 if (SubExpr.isInvalid())
4155 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004156
John McCall4765fa02010-12-06 08:20:24 +00004157 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00004158}
4159
John McCall4765fa02010-12-06 08:20:24 +00004160Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004161 assert(SubStmt && "sub statement can't be null!");
4162
John McCallf85e1932011-06-15 23:02:42 +00004163 if (!ExprNeedsCleanups)
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004164 return SubStmt;
4165
4166 // FIXME: In order to attach the temporaries, wrap the statement into
4167 // a StmtExpr; currently this is only used for asm statements.
4168 // This is hacky, either create a new CXXStmtWithTemporaries statement or
4169 // a new AsmStmtWithTemporaries.
4170 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
4171 SourceLocation(),
4172 SourceLocation());
4173 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
4174 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00004175 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004176}
4177
John McCall60d7b3a2010-08-24 06:29:42 +00004178ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004179Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00004180 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00004181 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004182 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004183 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004184 if (Result.isInvalid()) return ExprError();
4185 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004186
John McCall9ae2f072010-08-23 23:25:46 +00004187 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004188 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004189 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00004190 // If we have a pointer to a dependent type and are using the -> operator,
4191 // the object type is the type that the pointer points to. We might still
4192 // have enough information about that type to do something useful.
4193 if (OpKind == tok::arrow)
4194 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4195 BaseType = Ptr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004196
John McCallb3d87482010-08-24 05:47:05 +00004197 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00004198 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004199 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004200 }
Mike Stump1eb44332009-09-09 15:08:12 +00004201
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004202 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00004203 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004204 // returned, with the original second operand.
4205 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00004206 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00004207 llvm::SmallPtrSet<CanQualType,8> CTypes;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004208 SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00004209 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004210
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004211 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00004212 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
4213 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004214 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00004215 Base = Result.get();
4216 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00004217 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00004218 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00004219 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00004220 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004221 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00004222 for (unsigned i = 0; i < Locations.size(); i++)
4223 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004224 return ExprError();
4225 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004226 }
Mike Stump1eb44332009-09-09 15:08:12 +00004227
Douglas Gregor31658df2009-11-20 19:58:21 +00004228 if (BaseType->isPointerType())
4229 BaseType = BaseType->getPointeeType();
4230 }
Mike Stump1eb44332009-09-09 15:08:12 +00004231
4232 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004233 // vector types or Objective-C interfaces. Just return early and let
4234 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00004235 if (!BaseType->isRecordType()) {
4236 // C++ [basic.lookup.classref]p2:
4237 // [...] If the type of the object expression is of pointer to scalar
4238 // type, the unqualified-id is looked up in the context of the complete
4239 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00004240 //
4241 // This also indicates that we should be parsing a
4242 // pseudo-destructor-name.
John McCallb3d87482010-08-24 05:47:05 +00004243 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004244 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004245 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00004246 }
Mike Stump1eb44332009-09-09 15:08:12 +00004247
Douglas Gregor03c57052009-11-17 05:17:33 +00004248 // The object type must be complete (or dependent).
4249 if (!BaseType->isDependentType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004250 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor03c57052009-11-17 05:17:33 +00004251 PDiag(diag::err_incomplete_member_access)))
4252 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004253
Douglas Gregorc68afe22009-09-03 21:38:09 +00004254 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004255 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00004256 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00004257 // type C (or of pointer to a class type C), the unqualified-id is looked
4258 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00004259 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00004260 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004261}
4262
John McCall60d7b3a2010-08-24 06:29:42 +00004263ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00004264 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00004265 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00004266 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
4267 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00004268 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004269
Douglas Gregor77549082010-02-24 21:29:12 +00004270 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00004271 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00004272 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00004273 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00004274 /*RPLoc*/ ExpectedLParenLoc);
4275}
Douglas Gregord4dca082010-02-24 18:44:31 +00004276
John McCall60d7b3a2010-08-24 06:29:42 +00004277ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004278 SourceLocation OpLoc,
4279 tok::TokenKind OpKind,
4280 const CXXScopeSpec &SS,
4281 TypeSourceInfo *ScopeTypeInfo,
4282 SourceLocation CCLoc,
4283 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004284 PseudoDestructorTypeStorage Destructed,
John McCall2d9f5fa2011-02-25 05:21:17 +00004285 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004286 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004287
Douglas Gregorb57fb492010-02-24 22:38:50 +00004288 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004289 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregorb57fb492010-02-24 22:38:50 +00004290 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004291 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00004292 QualType ObjectType = Base->getType();
Douglas Gregorb57fb492010-02-24 22:38:50 +00004293 if (OpKind == tok::arrow) {
4294 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4295 ObjectType = Ptr->getPointeeType();
John McCall9ae2f072010-08-23 23:25:46 +00004296 } else if (!Base->isTypeDependent()) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004297 // The user wrote "p->" when she probably meant "p."; fix it.
4298 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4299 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00004300 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00004301 if (isSFINAEContext())
4302 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004303
Douglas Gregorb57fb492010-02-24 22:38:50 +00004304 OpKind = tok::period;
4305 }
4306 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004307
Douglas Gregorb57fb492010-02-24 22:38:50 +00004308 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
4309 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCall9ae2f072010-08-23 23:25:46 +00004310 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00004311 return ExprError();
4312 }
4313
4314 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004315 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb57fb492010-02-24 22:38:50 +00004316 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004317 if (DestructedTypeInfo) {
4318 QualType DestructedType = DestructedTypeInfo->getType();
4319 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004320 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCallf85e1932011-06-15 23:02:42 +00004321 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
4322 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
4323 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
4324 << ObjectType << DestructedType << Base->getSourceRange()
4325 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004326
John McCallf85e1932011-06-15 23:02:42 +00004327 // Recover by setting the destructed type to the object type.
4328 DestructedType = ObjectType;
4329 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004330 DestructedTypeStart);
John McCallf85e1932011-06-15 23:02:42 +00004331 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4332 } else if (DestructedType.getObjCLifetime() !=
4333 ObjectType.getObjCLifetime()) {
4334
4335 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
4336 // Okay: just pretend that the user provided the correctly-qualified
4337 // type.
4338 } else {
4339 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
4340 << ObjectType << DestructedType << Base->getSourceRange()
4341 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4342 }
4343
4344 // Recover by setting the destructed type to the object type.
4345 DestructedType = ObjectType;
4346 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4347 DestructedTypeStart);
4348 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4349 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004350 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00004351 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004352
Douglas Gregorb57fb492010-02-24 22:38:50 +00004353 // C++ [expr.pseudo]p2:
4354 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4355 // form
4356 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004357 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb57fb492010-02-24 22:38:50 +00004358 //
4359 // shall designate the same scalar type.
4360 if (ScopeTypeInfo) {
4361 QualType ScopeType = ScopeTypeInfo->getType();
4362 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00004363 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004364
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004365 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00004366 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00004367 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004368 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004369
Douglas Gregorb57fb492010-02-24 22:38:50 +00004370 ScopeType = QualType();
4371 ScopeTypeInfo = 0;
4372 }
4373 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004374
John McCall9ae2f072010-08-23 23:25:46 +00004375 Expr *Result
4376 = new (Context) CXXPseudoDestructorExpr(Context, Base,
4377 OpKind == tok::arrow, OpLoc,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004378 SS.getWithLocInContext(Context),
John McCall9ae2f072010-08-23 23:25:46 +00004379 ScopeTypeInfo,
4380 CCLoc,
4381 TildeLoc,
4382 Destructed);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004383
Douglas Gregorb57fb492010-02-24 22:38:50 +00004384 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00004385 return Owned(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004386
John McCall9ae2f072010-08-23 23:25:46 +00004387 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00004388}
4389
John McCall60d7b3a2010-08-24 06:29:42 +00004390ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004391 SourceLocation OpLoc,
4392 tok::TokenKind OpKind,
4393 CXXScopeSpec &SS,
4394 UnqualifiedId &FirstTypeName,
4395 SourceLocation CCLoc,
4396 SourceLocation TildeLoc,
4397 UnqualifiedId &SecondTypeName,
4398 bool HasTrailingLParen) {
Douglas Gregor77549082010-02-24 21:29:12 +00004399 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4400 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4401 "Invalid first type name in pseudo-destructor");
4402 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4403 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4404 "Invalid second type name in pseudo-destructor");
4405
Douglas Gregor77549082010-02-24 21:29:12 +00004406 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004407 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregor77549082010-02-24 21:29:12 +00004408 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004409 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00004410 QualType ObjectType = Base->getType();
Douglas Gregor77549082010-02-24 21:29:12 +00004411 if (OpKind == tok::arrow) {
4412 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4413 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004414 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00004415 // The user wrote "p->" when she probably meant "p."; fix it.
4416 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004417 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00004418 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00004419 if (isSFINAEContext())
4420 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004421
Douglas Gregor77549082010-02-24 21:29:12 +00004422 OpKind = tok::period;
4423 }
4424 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004425
4426 // Compute the object type that we should use for name lookup purposes. Only
4427 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00004428 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004429 if (!SS.isSet()) {
John McCall2d9f5fa2011-02-25 05:21:17 +00004430 if (ObjectType->isRecordType())
4431 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallb3d87482010-08-24 05:47:05 +00004432 else if (ObjectType->isDependentType())
4433 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004434 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004435
4436 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb57fb492010-02-24 22:38:50 +00004437 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00004438 QualType DestructedType;
4439 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004440 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00004441 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004442 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00004443 SecondTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00004444 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004445 if (!T &&
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004446 ((SS.isSet() && !computeDeclContext(SS, false)) ||
4447 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004448 // The name of the type being destroyed is a dependent name, and we
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004449 // couldn't find anything useful in scope. Just store the identifier and
4450 // it's location, and we'll perform (qualified) name lookup again at
4451 // template instantiation time.
4452 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
4453 SecondTypeName.StartLocation);
4454 } else if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004455 Diag(SecondTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00004456 diag::err_pseudo_dtor_destructor_non_type)
4457 << SecondTypeName.Identifier << ObjectType;
4458 if (isSFINAEContext())
4459 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004460
Douglas Gregor77549082010-02-24 21:29:12 +00004461 // Recover by assuming we had the right type all along.
4462 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004463 } else
Douglas Gregor77549082010-02-24 21:29:12 +00004464 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004465 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004466 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00004467 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004468 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4469 TemplateId->getTemplateArgs(),
4470 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00004471 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4472 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004473 TemplateId->TemplateNameLoc,
4474 TemplateId->LAngleLoc,
4475 TemplateArgsPtr,
4476 TemplateId->RAngleLoc);
4477 if (T.isInvalid() || !T.get()) {
4478 // Recover by assuming we had the right type all along.
4479 DestructedType = ObjectType;
4480 } else
4481 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004482 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004483
4484 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb57fb492010-02-24 22:38:50 +00004485 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004486 if (!DestructedType.isNull()) {
4487 if (!DestructedTypeInfo)
4488 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004489 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004490 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4491 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004492
Douglas Gregorb57fb492010-02-24 22:38:50 +00004493 // Convert the name of the scope type (the type prior to '::') into a type.
4494 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00004495 QualType ScopeType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004496 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor77549082010-02-24 21:29:12 +00004497 FirstTypeName.Identifier) {
4498 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004499 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00004500 FirstTypeName.StartLocation,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004501 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00004502 if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004503 Diag(FirstTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00004504 diag::err_pseudo_dtor_destructor_non_type)
4505 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004506
Douglas Gregorb57fb492010-02-24 22:38:50 +00004507 if (isSFINAEContext())
4508 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004509
Douglas Gregorb57fb492010-02-24 22:38:50 +00004510 // Just drop this type. It's unnecessary anyway.
4511 ScopeType = QualType();
4512 } else
4513 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004514 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004515 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00004516 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004517 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4518 TemplateId->getTemplateArgs(),
4519 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00004520 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4521 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004522 TemplateId->TemplateNameLoc,
4523 TemplateId->LAngleLoc,
4524 TemplateArgsPtr,
4525 TemplateId->RAngleLoc);
4526 if (T.isInvalid() || !T.get()) {
4527 // Recover by dropping this type.
4528 ScopeType = QualType();
4529 } else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004530 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004531 }
4532 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004533
Douglas Gregorb4a418f2010-02-24 23:02:30 +00004534 if (!ScopeType.isNull() && !ScopeTypeInfo)
4535 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
4536 FirstTypeName.StartLocation);
4537
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004538
John McCall9ae2f072010-08-23 23:25:46 +00004539 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00004540 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004541 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00004542}
4543
John Wiegley429bb272011-04-08 18:41:53 +00004544ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004545 CXXMethodDecl *Method) {
John Wiegley429bb272011-04-08 18:41:53 +00004546 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
4547 FoundDecl, Method);
4548 if (Exp.isInvalid())
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004549 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00004550
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004551 MemberExpr *ME =
John Wiegley429bb272011-04-08 18:41:53 +00004552 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
John McCallf89e55a2010-11-18 06:31:45 +00004553 SourceLocation(), Method->getType(),
4554 VK_RValue, OK_Ordinary);
4555 QualType ResultType = Method->getResultType();
4556 ExprValueKind VK = Expr::getValueKindForType(ResultType);
4557 ResultType = ResultType.getNonLValueExprType(Context);
4558
John Wiegley429bb272011-04-08 18:41:53 +00004559 MarkDeclarationReferenced(Exp.get()->getLocStart(), Method);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004560 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00004561 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
John Wiegley429bb272011-04-08 18:41:53 +00004562 Exp.get()->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00004563 return CE;
4564}
4565
Sebastian Redl2e156222010-09-10 20:55:43 +00004566ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4567 SourceLocation RParen) {
Sebastian Redl2e156222010-09-10 20:55:43 +00004568 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
4569 Operand->CanThrow(Context),
4570 KeyLoc, RParen));
4571}
4572
4573ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
4574 Expr *Operand, SourceLocation RParen) {
4575 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00004576}
4577
John McCallf6a16482010-12-04 03:47:34 +00004578/// Perform the conversions required for an expression used in a
4579/// context that ignores the result.
John Wiegley429bb272011-04-08 18:41:53 +00004580ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCalla878cda2010-12-02 02:07:15 +00004581 // C99 6.3.2.1:
4582 // [Except in specific positions,] an lvalue that does not have
4583 // array type is converted to the value stored in the
4584 // designated object (and is no longer an lvalue).
John McCalle6d134b2011-06-27 21:24:11 +00004585 if (E->isRValue()) {
4586 // In C, function designators (i.e. expressions of function type)
4587 // are r-values, but we still want to do function-to-pointer decay
4588 // on them. This is both technically correct and convenient for
4589 // some clients.
4590 if (!getLangOptions().CPlusPlus && E->getType()->isFunctionType())
4591 return DefaultFunctionArrayConversion(E);
4592
4593 return Owned(E);
4594 }
John McCalla878cda2010-12-02 02:07:15 +00004595
John McCallf6a16482010-12-04 03:47:34 +00004596 // We always want to do this on ObjC property references.
4597 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley429bb272011-04-08 18:41:53 +00004598 ExprResult Res = ConvertPropertyForRValue(E);
4599 if (Res.isInvalid()) return Owned(E);
4600 E = Res.take();
4601 if (E->isRValue()) return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004602 }
4603
4604 // Otherwise, this rule does not apply in C++, at least not for the moment.
John Wiegley429bb272011-04-08 18:41:53 +00004605 if (getLangOptions().CPlusPlus) return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004606
4607 // GCC seems to also exclude expressions of incomplete enum type.
4608 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
4609 if (!T->getDecl()->isComplete()) {
4610 // FIXME: stupid workaround for a codegen bug!
John Wiegley429bb272011-04-08 18:41:53 +00004611 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
4612 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004613 }
4614 }
4615
John Wiegley429bb272011-04-08 18:41:53 +00004616 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
4617 if (Res.isInvalid())
4618 return Owned(E);
4619 E = Res.take();
4620
John McCall85515d62010-12-04 12:29:11 +00004621 if (!E->getType()->isVoidType())
4622 RequireCompleteType(E->getExprLoc(), E->getType(),
4623 diag::err_incomplete_type);
John Wiegley429bb272011-04-08 18:41:53 +00004624 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004625}
4626
John Wiegley429bb272011-04-08 18:41:53 +00004627ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
4628 ExprResult FullExpr = Owned(FE);
4629
4630 if (!FullExpr.get())
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00004631 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00004632
John Wiegley429bb272011-04-08 18:41:53 +00004633 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregord0937222010-12-13 22:49:22 +00004634 return ExprError();
4635
John McCallfb8721c2011-04-10 19:13:55 +00004636 FullExpr = CheckPlaceholderExpr(FullExpr.take());
4637 if (FullExpr.isInvalid())
4638 return ExprError();
Douglas Gregor353ee242011-03-07 02:05:23 +00004639
John Wiegley429bb272011-04-08 18:41:53 +00004640 FullExpr = IgnoredValueConversions(FullExpr.take());
4641 if (FullExpr.isInvalid())
4642 return ExprError();
4643
4644 CheckImplicitConversions(FullExpr.get());
John McCall4765fa02010-12-06 08:20:24 +00004645 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00004646}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004647
4648StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
4649 if (!FullStmt) return StmtError();
4650
John McCall4765fa02010-12-06 08:20:24 +00004651 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004652}
Francois Pichet1e862692011-05-06 20:48:22 +00004653
4654bool Sema::CheckMicrosoftIfExistsSymbol(CXXScopeSpec &SS,
4655 UnqualifiedId &Name) {
4656 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
4657 DeclarationName TargetName = TargetNameInfo.getName();
4658 if (!TargetName)
4659 return false;
4660
4661 // Do the redeclaration lookup in the current scope.
4662 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
4663 Sema::NotForRedeclaration);
4664 R.suppressDiagnostics();
4665 LookupParsedName(R, getCurScope(), &SS);
4666 return !R.empty();
4667}