blob: 59369d603d9936edbf849bc2f39b8ca75635312e [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
David Blaikie53a75c02011-12-08 16:13:53 +0000268ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
David Blaikie4db8c442011-12-12 04:13:55 +0000269 if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
David Blaikie53a75c02011-12-08 16:13:53 +0000270 return ParsedType();
271 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
272 && "only get destructor types from declspecs");
273 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
274 QualType SearchType = GetTypeFromParser(ObjectType);
275 if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
276 return ParsedType::make(T);
277 }
278
279 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
280 << T << SearchType;
281 return ParsedType();
282}
283
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000284/// \brief Build a C++ typeid expression with a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000285ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000286 SourceLocation TypeidLoc,
287 TypeSourceInfo *Operand,
288 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000289 // C++ [expr.typeid]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000290 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000291 // that is the operand of typeid are always ignored.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000292 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000293 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000294 Qualifiers Quals;
295 QualType T
296 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
297 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000298 if (T->getAs<RecordType>() &&
299 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
300 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000301
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000302 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
303 Operand,
304 SourceRange(TypeidLoc, RParenLoc)));
305}
306
307/// \brief Build a C++ typeid expression with an expression operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000308ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000309 SourceLocation TypeidLoc,
310 Expr *E,
311 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000312 bool isUnevaluatedOperand = true;
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000313 if (E && !E->isTypeDependent()) {
John McCall6dbba4f2011-10-11 23:14:30 +0000314 if (E->getType()->isPlaceholderType()) {
315 ExprResult result = CheckPlaceholderExpr(E);
316 if (result.isInvalid()) return ExprError();
317 E = result.take();
318 }
319
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000320 QualType T = E->getType();
321 if (const RecordType *RecordT = T->getAs<RecordType>()) {
322 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
323 // C++ [expr.typeid]p3:
324 // [...] If the type of the expression is a class type, the class
325 // shall be completely-defined.
326 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
327 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000328
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000329 // C++ [expr.typeid]p3:
Sebastian Redl906082e2010-07-20 04:20:21 +0000330 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000331 // polymorphic class type [...] [the] expression is an unevaluated
332 // operand. [...]
Sebastian Redl906082e2010-07-20 04:20:21 +0000333 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000334 isUnevaluatedOperand = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000335
336 // We require a vtable to query the type at run time.
337 MarkVTableUsed(TypeidLoc, RecordD);
338 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000339 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000340
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000341 // C++ [expr.typeid]p4:
342 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000343 // cv-qualified type, the result of the typeid expression refers to a
344 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000345 // type.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000346 Qualifiers Quals;
347 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
348 if (!Context.hasSameType(T, UnqualT)) {
349 T = UnqualT;
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +0000350 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take();
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000351 }
352 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000353
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000354 // If this is an unevaluated operand, clear out the set of
355 // declaration references we have been computing and eliminate any
356 // temporaries introduced in its computation.
357 if (isUnevaluatedOperand)
358 ExprEvalContexts.back().Context = Unevaluated;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000359
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000360 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCall9ae2f072010-08-23 23:25:46 +0000361 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000362 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000363}
364
365/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCall60d7b3a2010-08-24 06:29:42 +0000366ExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000367Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
368 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000369 // Find the std::type_info type.
Sebastian Redlce0682f2011-03-31 19:29:24 +0000370 if (!getStdNamespace())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000371 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000372
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000373 if (!CXXTypeInfoDecl) {
374 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
375 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
376 LookupQualifiedName(R, getStdNamespace());
377 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
378 if (!CXXTypeInfoDecl)
379 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
380 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000381
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000382 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000383
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000384 if (isType) {
385 // The operand is a type; handle it as such.
386 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +0000387 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
388 &TInfo);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000389 if (T.isNull())
390 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000391
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000392 if (!TInfo)
393 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000394
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000395 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000396 }
Mike Stump1eb44332009-09-09 15:08:12 +0000397
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000398 // The operand is an expression.
John McCall9ae2f072010-08-23 23:25:46 +0000399 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000400}
401
Francois Pichet6915c522010-12-27 01:32:00 +0000402/// Retrieve the UuidAttr associated with QT.
403static UuidAttr *GetUuidAttrOfType(QualType QT) {
404 // Optionally remove one level of pointer, reference or array indirection.
John McCallf4c73712011-01-19 06:33:43 +0000405 const Type *Ty = QT.getTypePtr();;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000406 if (QT->isPointerType() || QT->isReferenceType())
407 Ty = QT->getPointeeType().getTypePtr();
408 else if (QT->isArrayType())
409 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
410
Francois Pichet8db75a22011-05-08 10:02:20 +0000411 // Loop all record redeclaration looking for an uuid attribute.
Francois Pichet6915c522010-12-27 01:32:00 +0000412 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Francois Pichet8db75a22011-05-08 10:02:20 +0000413 for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(),
414 E = RD->redecls_end(); I != E; ++I) {
415 if (UuidAttr *Uuid = I->getAttr<UuidAttr>())
Francois Pichet6915c522010-12-27 01:32:00 +0000416 return Uuid;
Francois Pichet6915c522010-12-27 01:32:00 +0000417 }
Francois Pichet8db75a22011-05-08 10:02:20 +0000418
Francois Pichet6915c522010-12-27 01:32:00 +0000419 return 0;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000420}
421
Francois Pichet01b7c302010-09-08 12:20:18 +0000422/// \brief Build a Microsoft __uuidof expression with a type operand.
423ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
424 SourceLocation TypeidLoc,
425 TypeSourceInfo *Operand,
426 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000427 if (!Operand->getType()->isDependentType()) {
428 if (!GetUuidAttrOfType(Operand->getType()))
429 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
430 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000431
Francois Pichet01b7c302010-09-08 12:20:18 +0000432 // FIXME: add __uuidof semantic analysis for type operand.
433 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
434 Operand,
435 SourceRange(TypeidLoc, RParenLoc)));
436}
437
438/// \brief Build a Microsoft __uuidof expression with an expression operand.
439ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
440 SourceLocation TypeidLoc,
441 Expr *E,
442 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000443 if (!E->getType()->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000444 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichet6915c522010-12-27 01:32:00 +0000445 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
446 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
447 }
448 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet01b7c302010-09-08 12:20:18 +0000449 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
450 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000451 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet01b7c302010-09-08 12:20:18 +0000452}
453
454/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
455ExprResult
456Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
457 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000458 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet01b7c302010-09-08 12:20:18 +0000459 if (!MSVCGuidDecl) {
460 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
461 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
462 LookupQualifiedName(R, Context.getTranslationUnitDecl());
463 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
464 if (!MSVCGuidDecl)
465 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000466 }
467
Francois Pichet01b7c302010-09-08 12:20:18 +0000468 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000469
Francois Pichet01b7c302010-09-08 12:20:18 +0000470 if (isType) {
471 // The operand is a type; handle it as such.
472 TypeSourceInfo *TInfo = 0;
473 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
474 &TInfo);
475 if (T.isNull())
476 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000477
Francois Pichet01b7c302010-09-08 12:20:18 +0000478 if (!TInfo)
479 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
480
481 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
482 }
483
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000484 // The operand is an expression.
Francois Pichet01b7c302010-09-08 12:20:18 +0000485 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
486}
487
Steve Naroff1b273c42007-09-16 14:56:35 +0000488/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCall60d7b3a2010-08-24 06:29:42 +0000489ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000490Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000491 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000492 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000493 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
494 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000495}
Chris Lattner50dd2892008-02-26 00:51:44 +0000496
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000497/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCall60d7b3a2010-08-24 06:29:42 +0000498ExprResult
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000499Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
500 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
501}
502
Chris Lattner50dd2892008-02-26 00:51:44 +0000503/// ActOnCXXThrow - Parse throw expressions.
John McCall60d7b3a2010-08-24 06:29:42 +0000504ExprResult
Douglas Gregorbca01b42011-07-06 22:04:06 +0000505Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
506 bool IsThrownVarInScope = false;
507 if (Ex) {
508 // C++0x [class.copymove]p31:
509 // When certain criteria are met, an implementation is allowed to omit the
510 // copy/move construction of a class object [...]
511 //
512 // - in a throw-expression, when the operand is the name of a
513 // non-volatile automatic object (other than a function or catch-
514 // clause parameter) whose scope does not extend beyond the end of the
515 // innermost enclosing try-block (if there is one), the copy/move
516 // operation from the operand to the exception object (15.1) can be
517 // omitted by constructing the automatic object directly into the
518 // exception object
519 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
520 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
521 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
522 for( ; S; S = S->getParent()) {
523 if (S->isDeclScope(Var)) {
524 IsThrownVarInScope = true;
525 break;
526 }
527
528 if (S->getFlags() &
529 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
530 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
531 Scope::TryScope))
532 break;
533 }
534 }
535 }
536 }
537
538 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
539}
540
541ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
542 bool IsThrownVarInScope) {
Anders Carlsson729b8532011-02-23 03:46:46 +0000543 // Don't report an error if 'throw' is used in system headers.
Anders Carlsson15348ae2011-02-28 02:27:16 +0000544 if (!getLangOptions().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +0000545 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb1fba312011-02-19 21:53:09 +0000546 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Douglas Gregorbca01b42011-07-06 22:04:06 +0000547
John Wiegley429bb272011-04-08 18:41:53 +0000548 if (Ex && !Ex->isTypeDependent()) {
Douglas Gregorbca01b42011-07-06 22:04:06 +0000549 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
John Wiegley429bb272011-04-08 18:41:53 +0000550 if (ExRes.isInvalid())
551 return ExprError();
552 Ex = ExRes.take();
553 }
Douglas Gregorbca01b42011-07-06 22:04:06 +0000554
555 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
556 IsThrownVarInScope));
Sebastian Redl972041f2009-04-27 20:27:31 +0000557}
558
559/// CheckCXXThrowOperand - Validate the operand of a throw.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000560ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
561 bool IsThrownVarInScope) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000562 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000563 // A throw-expression initializes a temporary object, called the exception
564 // object, the type of which is determined by removing any top-level
565 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000566 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor154fe982009-12-23 22:04:40 +0000567 // or "pointer to function returning T", [...]
568 if (E->getType().hasQualifiers())
John Wiegley429bb272011-04-08 18:41:53 +0000569 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +0000570 E->getValueKind()).take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000571
John Wiegley429bb272011-04-08 18:41:53 +0000572 ExprResult Res = DefaultFunctionArrayConversion(E);
573 if (Res.isInvalid())
574 return ExprError();
575 E = Res.take();
Sebastian Redl972041f2009-04-27 20:27:31 +0000576
577 // If the type of the exception would be an incomplete type or a pointer
578 // to an incomplete type other than (cv) void the program is ill-formed.
579 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000580 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000581 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000582 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000583 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000584 }
585 if (!isPointer || !Ty->isVoidType()) {
586 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000587 PDiag(isPointer ? diag::err_throw_incomplete_ptr
588 : diag::err_throw_incomplete)
589 << E->getSourceRange()))
John Wiegley429bb272011-04-08 18:41:53 +0000590 return ExprError();
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000591
Douglas Gregorbf422f92010-04-15 18:05:39 +0000592 if (RequireNonAbstractType(ThrowLoc, E->getType(),
593 PDiag(diag::err_throw_abstract_type)
594 << E->getSourceRange()))
John Wiegley429bb272011-04-08 18:41:53 +0000595 return ExprError();
Sebastian Redl972041f2009-04-27 20:27:31 +0000596 }
597
John McCallac418162010-04-22 01:10:34 +0000598 // Initialize the exception result. This implicitly weeds out
599 // abstract types or types with inaccessible copy constructors.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000600
601 // C++0x [class.copymove]p31:
602 // When certain criteria are met, an implementation is allowed to omit the
603 // copy/move construction of a class object [...]
604 //
605 // - in a throw-expression, when the operand is the name of a
606 // non-volatile automatic object (other than a function or catch-clause
607 // parameter) whose scope does not extend beyond the end of the
608 // innermost enclosing try-block (if there is one), the copy/move
609 // operation from the operand to the exception object (15.1) can be
610 // omitted by constructing the automatic object directly into the
611 // exception object
612 const VarDecl *NRVOVariable = 0;
613 if (IsThrownVarInScope)
614 NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
615
John McCallac418162010-04-22 01:10:34 +0000616 InitializedEntity Entity =
Douglas Gregor72dfa272011-01-21 22:46:35 +0000617 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
Douglas Gregorbca01b42011-07-06 22:04:06 +0000618 /*NRVO=*/NRVOVariable != 0);
John Wiegley429bb272011-04-08 18:41:53 +0000619 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregorbca01b42011-07-06 22:04:06 +0000620 QualType(), E,
621 IsThrownVarInScope);
John McCallac418162010-04-22 01:10:34 +0000622 if (Res.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000623 return ExprError();
624 E = Res.take();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000625
Eli Friedman5ed9b932010-06-03 20:39:03 +0000626 // If the exception has class type, we need additional handling.
627 const RecordType *RecordTy = Ty->getAs<RecordType>();
628 if (!RecordTy)
John Wiegley429bb272011-04-08 18:41:53 +0000629 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000630 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
631
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000632 // If we are throwing a polymorphic class type or pointer thereof,
633 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000634 MarkVTableUsed(ThrowLoc, RD);
635
Eli Friedman98efb9f2010-10-12 20:32:36 +0000636 // If a pointer is thrown, the referenced object will not be destroyed.
637 if (isPointer)
John Wiegley429bb272011-04-08 18:41:53 +0000638 return Owned(E);
Eli Friedman98efb9f2010-10-12 20:32:36 +0000639
Eli Friedman5ed9b932010-06-03 20:39:03 +0000640 // If the class has a non-trivial destructor, we must be able to call it.
641 if (RD->hasTrivialDestructor())
John Wiegley429bb272011-04-08 18:41:53 +0000642 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000643
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000644 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +0000645 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman5ed9b932010-06-03 20:39:03 +0000646 if (!Destructor)
John Wiegley429bb272011-04-08 18:41:53 +0000647 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000648
649 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
650 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000651 PDiag(diag::err_access_dtor_exception) << Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000652 return Owned(E);
Chris Lattner50dd2892008-02-26 00:51:44 +0000653}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000654
Douglas Gregor341350e2011-10-18 16:47:30 +0000655QualType Sema::getCurrentThisType(bool Capture) {
John McCall5808ce42011-02-03 08:15:49 +0000656 // Ignore block scopes: we can capture through them.
657 // Ignore nested enum scopes: we'll diagnose non-constant expressions
658 // where they're invalid, and other uses are legitimate.
659 // Don't ignore nested class scopes: you can't use 'this' in a local class.
John McCall469a1eb2011-02-02 13:00:07 +0000660 DeclContext *DC = CurContext;
Richard Smith7a614d82011-06-11 17:19:42 +0000661 unsigned NumBlocks = 0;
John McCall5808ce42011-02-03 08:15:49 +0000662 while (true) {
Richard Smith7a614d82011-06-11 17:19:42 +0000663 if (isa<BlockDecl>(DC)) {
664 DC = cast<BlockDecl>(DC)->getDeclContext();
665 ++NumBlocks;
666 } else if (isa<EnumDecl>(DC))
667 DC = cast<EnumDecl>(DC)->getDeclContext();
John McCall5808ce42011-02-03 08:15:49 +0000668 else break;
669 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000670
Richard Smith7a614d82011-06-11 17:19:42 +0000671 QualType ThisTy;
672 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
673 if (method && method->isInstance())
674 ThisTy = method->getThisType(Context);
675 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
676 // C++0x [expr.prim]p4:
677 // Otherwise, if a member-declarator declares a non-static data member
678 // of a class X, the expression this is a prvalue of type "pointer to X"
679 // within the optional brace-or-equal-initializer.
680 Scope *S = getScopeForContext(DC);
681 if (!S || S->getFlags() & Scope::ThisScope)
682 ThisTy = Context.getPointerType(Context.getRecordType(RD));
683 }
John McCall469a1eb2011-02-02 13:00:07 +0000684
Douglas Gregor341350e2011-10-18 16:47:30 +0000685 if (!Capture || ThisTy.isNull())
686 return ThisTy;
687
Richard Smith7a614d82011-06-11 17:19:42 +0000688 // Mark that we're closing on 'this' in all the block scopes we ignored.
Douglas Gregor341350e2011-10-18 16:47:30 +0000689 for (unsigned idx = FunctionScopes.size() - 1;
690 NumBlocks; --idx, --NumBlocks)
691 cast<BlockScopeInfo>(FunctionScopes[idx])->CapturesCXXThis = true;
John McCall469a1eb2011-02-02 13:00:07 +0000692
Richard Smith7a614d82011-06-11 17:19:42 +0000693 return ThisTy;
John McCall5808ce42011-02-03 08:15:49 +0000694}
695
Richard Smith7a614d82011-06-11 17:19:42 +0000696ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCall5808ce42011-02-03 08:15:49 +0000697 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
698 /// is a non-lvalue expression whose value is the address of the object for
699 /// which the function is called.
700
Douglas Gregor341350e2011-10-18 16:47:30 +0000701 QualType ThisTy = getCurrentThisType();
Richard Smith7a614d82011-06-11 17:19:42 +0000702 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCall5808ce42011-02-03 08:15:49 +0000703
Richard Smith7a614d82011-06-11 17:19:42 +0000704 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000705}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000706
John McCall60d7b3a2010-08-24 06:29:42 +0000707ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000708Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000709 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000710 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000711 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000712 if (!TypeRep)
713 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000714
John McCall9d125032010-01-15 18:39:57 +0000715 TypeSourceInfo *TInfo;
716 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
717 if (!TInfo)
718 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000719
720 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
721}
722
723/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
724/// Can be interpreted either as function-style casting ("int(x)")
725/// or class type construction ("ClassType(x,y,z)")
726/// or creation of a value-initialized type ("int()").
727ExprResult
728Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
729 SourceLocation LParenLoc,
730 MultiExprArg exprs,
731 SourceLocation RParenLoc) {
732 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000733 unsigned NumExprs = exprs.size();
734 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000735 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000736 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
737
Sebastian Redlf53597f2009-03-15 17:47:39 +0000738 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000739 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000740 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Douglas Gregorab6677e2010-09-08 00:15:04 +0000742 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000743 LParenLoc,
744 Exprs, NumExprs,
745 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000746 }
747
Anders Carlssonbb60a502009-08-27 03:53:50 +0000748 if (Ty->isArrayType())
749 return ExprError(Diag(TyBeginLoc,
750 diag::err_value_init_for_array_type) << FullRange);
751 if (!Ty->isVoidType() &&
752 RequireCompleteType(TyBeginLoc, Ty,
753 PDiag(diag::err_invalid_incomplete_type_use)
754 << FullRange))
755 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000756
Anders Carlssonbb60a502009-08-27 03:53:50 +0000757 if (RequireNonAbstractType(TyBeginLoc, Ty,
758 diag::err_allocation_of_abstract_type))
759 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000760
761
Douglas Gregor506ae412009-01-16 18:33:17 +0000762 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000763 // If the expression list is a single expression, the type conversion
764 // expression is equivalent (in definedness, and if defined in meaning) to the
765 // corresponding cast expression.
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000766 if (NumExprs == 1) {
John McCallb45ae252011-10-05 07:41:44 +0000767 Expr *Arg = Exprs[0];
Anders Carlsson0aebc812009-09-09 21:33:21 +0000768 exprs.release();
John McCallb45ae252011-10-05 07:41:44 +0000769 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000770 }
771
Douglas Gregor19311e72010-09-08 21:40:08 +0000772 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
773 InitializationKind Kind
774 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
775 LParenLoc, RParenLoc)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000776 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor19311e72010-09-08 21:40:08 +0000777 LParenLoc, RParenLoc);
778 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
779 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000780
Douglas Gregor19311e72010-09-08 21:40:08 +0000781 // FIXME: Improve AST representation?
782 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000783}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000784
John McCall6ec278d2011-01-27 09:37:56 +0000785/// doesUsualArrayDeleteWantSize - Answers whether the usual
786/// operator delete[] for the given type has a size_t parameter.
787static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
788 QualType allocType) {
789 const RecordType *record =
790 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
791 if (!record) return false;
792
793 // Try to find an operator delete[] in class scope.
794
795 DeclarationName deleteName =
796 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
797 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
798 S.LookupQualifiedName(ops, record->getDecl());
799
800 // We're just doing this for information.
801 ops.suppressDiagnostics();
802
803 // Very likely: there's no operator delete[].
804 if (ops.empty()) return false;
805
806 // If it's ambiguous, it should be illegal to call operator delete[]
807 // on this thing, so it doesn't matter if we allocate extra space or not.
808 if (ops.isAmbiguous()) return false;
809
810 LookupResult::Filter filter = ops.makeFilter();
811 while (filter.hasNext()) {
812 NamedDecl *del = filter.next()->getUnderlyingDecl();
813
814 // C++0x [basic.stc.dynamic.deallocation]p2:
815 // A template instance is never a usual deallocation function,
816 // regardless of its signature.
817 if (isa<FunctionTemplateDecl>(del)) {
818 filter.erase();
819 continue;
820 }
821
822 // C++0x [basic.stc.dynamic.deallocation]p2:
823 // If class T does not declare [an operator delete[] with one
824 // parameter] but does declare a member deallocation function
825 // named operator delete[] with exactly two parameters, the
826 // second of which has type std::size_t, then this function
827 // is a usual deallocation function.
828 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
829 filter.erase();
830 continue;
831 }
832 }
833 filter.done();
834
835 if (!ops.isSingleResult()) return false;
836
837 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
838 return (del->getNumParams() == 2);
839}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000840
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000841/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
842/// @code new (memory) int[size][4] @endcode
843/// or
844/// @code ::new Foo(23, "hello") @endcode
845/// For the interpretation of this heap of arguments, consult the base version.
John McCall60d7b3a2010-08-24 06:29:42 +0000846ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000847Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000848 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000849 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000850 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000851 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000852 SourceLocation ConstructorRParen) {
Richard Smith34b41d92011-02-20 03:19:35 +0000853 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
854
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000855 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000856 // If the specified type is an array, unwrap it and save the expression.
857 if (D.getNumTypeObjects() > 0 &&
858 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
859 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith34b41d92011-02-20 03:19:35 +0000860 if (TypeContainsAuto)
861 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
862 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000863 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000864 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
865 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000866 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000867 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
868 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000869
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000870 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000871 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000872 }
873
Douglas Gregor043cad22009-09-11 00:18:58 +0000874 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000875 if (ArraySize) {
876 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000877 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
878 break;
879
880 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
881 if (Expr *NumElts = (Expr *)Array.NumElts) {
882 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
883 !NumElts->isIntegerConstantExpr(Context)) {
884 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
885 << NumElts->getSourceRange();
886 return ExprError();
887 }
888 }
889 }
890 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000891
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +0000892 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
John McCallbf1a0282010-06-04 23:28:52 +0000893 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000894 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000895 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000896
Mike Stump1eb44332009-09-09 15:08:12 +0000897 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000898 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000899 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000900 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000901 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000902 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000903 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000904 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000905 ConstructorLParen,
906 move(ConstructorArgs),
Richard Smith34b41d92011-02-20 03:19:35 +0000907 ConstructorRParen,
908 TypeContainsAuto);
Douglas Gregor3433cf72009-05-21 00:00:09 +0000909}
910
John McCall60d7b3a2010-08-24 06:29:42 +0000911ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000912Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
913 SourceLocation PlacementLParen,
914 MultiExprArg PlacementArgs,
915 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000916 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000917 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000918 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000919 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000920 SourceLocation ConstructorLParen,
921 MultiExprArg ConstructorArgs,
Richard Smith34b41d92011-02-20 03:19:35 +0000922 SourceLocation ConstructorRParen,
923 bool TypeMayContainAuto) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000924 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000925
Richard Smith34b41d92011-02-20 03:19:35 +0000926 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
927 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
928 if (ConstructorArgs.size() == 0)
929 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
930 << AllocType << TypeRange);
931 if (ConstructorArgs.size() != 1) {
932 Expr *FirstBad = ConstructorArgs.get()[1];
933 return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
934 diag::err_auto_new_ctor_multiple_expressions)
935 << AllocType << TypeRange);
936 }
Richard Smitha085da82011-03-17 16:11:59 +0000937 TypeSourceInfo *DeducedType = 0;
938 if (!DeduceAutoType(AllocTypeInfo, ConstructorArgs.get()[0], DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +0000939 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
940 << AllocType
941 << ConstructorArgs.get()[0]->getType()
942 << TypeRange
943 << ConstructorArgs.get()[0]->getSourceRange());
Richard Smitha085da82011-03-17 16:11:59 +0000944 if (!DeducedType)
945 return ExprError();
Richard Smith34b41d92011-02-20 03:19:35 +0000946
Richard Smitha085da82011-03-17 16:11:59 +0000947 AllocTypeInfo = DeducedType;
948 AllocType = AllocTypeInfo->getType();
Richard Smith34b41d92011-02-20 03:19:35 +0000949 }
950
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000951 // Per C++0x [expr.new]p5, the type being constructed may be a
952 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +0000953 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000954 if (const ConstantArrayType *Array
955 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000956 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
957 Context.getSizeType(),
958 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000959 AllocType = Array->getElementType();
960 }
961 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000962
Douglas Gregora0750762010-10-06 16:00:31 +0000963 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
964 return ExprError();
965
John McCallf85e1932011-06-15 23:02:42 +0000966 // In ARC, infer 'retaining' for the allocated
967 if (getLangOptions().ObjCAutoRefCount &&
968 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
969 AllocType->isObjCLifetimeType()) {
970 AllocType = Context.getLifetimeQualifiedType(AllocType,
971 AllocType->getObjCARCImplicitLifetime());
972 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000973
John McCallf85e1932011-06-15 23:02:42 +0000974 QualType ResultType = Context.getPointerType(AllocType);
975
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000976 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
977 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000978 if (ArraySize && !ArraySize->isTypeDependent()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000979
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000980 QualType SizeType = ArraySize->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000981
Richard Smithebaf0e62011-10-18 20:49:44 +0000982 ExprResult ConvertedSize = ConvertToIntegralOrEnumerationType(
983 StartLoc, ArraySize,
984 PDiag(diag::err_array_size_not_integral),
985 PDiag(diag::err_array_size_incomplete_type)
986 << ArraySize->getSourceRange(),
987 PDiag(diag::err_array_size_explicit_conversion),
988 PDiag(diag::note_array_size_conversion),
989 PDiag(diag::err_array_size_ambiguous_conversion),
990 PDiag(diag::note_array_size_conversion),
991 PDiag(getLangOptions().CPlusPlus0x ?
992 diag::warn_cxx98_compat_array_size_conversion :
993 diag::ext_array_size_conversion));
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000994 if (ConvertedSize.isInvalid())
995 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000996
John McCall9ae2f072010-08-23 23:25:46 +0000997 ArraySize = ConvertedSize.take();
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000998 SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000999 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +00001000 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001001
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001002 // Let's see if this is a constant < 0. If so, we reject it out of hand.
1003 // We don't care about special rules, so we tell the machinery it's not
1004 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +00001005 if (!ArraySize->isValueDependent()) {
1006 llvm::APSInt Value;
1007 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
1008 if (Value < llvm::APSInt(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001009 llvm::APInt::getNullValue(Value.getBitWidth()),
Anders Carlssonac18b2e2009-09-23 00:37:25 +00001010 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +00001011 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +00001012 diag::err_typecheck_negative_array_size)
Sebastian Redlf53597f2009-03-15 17:47:39 +00001013 << ArraySize->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001014
Douglas Gregor2767ce22010-08-18 00:39:00 +00001015 if (!AllocType->isDependentType()) {
1016 unsigned ActiveSizeBits
1017 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1018 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001019 Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +00001020 diag::err_array_too_large)
1021 << Value.toString(10)
1022 << ArraySize->getSourceRange();
1023 return ExprError();
1024 }
1025 }
Douglas Gregor4bd40312010-07-13 15:54:32 +00001026 } else if (TypeIdParens.isValid()) {
1027 // Can't have dynamic array size when the type-id is in parentheses.
1028 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1029 << ArraySize->getSourceRange()
1030 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1031 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001032
Douglas Gregor4bd40312010-07-13 15:54:32 +00001033 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +00001034 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001035 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001036
John McCallf85e1932011-06-15 23:02:42 +00001037 // ARC: warn about ABI issues.
1038 if (getLangOptions().ObjCAutoRefCount) {
1039 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1040 if (BaseAllocType.hasStrongOrWeakObjCLifetime())
1041 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1042 << 0 << BaseAllocType;
1043 }
1044
John McCall7d166272011-05-15 07:14:44 +00001045 // Note that we do *not* convert the argument in any way. It can
1046 // be signed, larger than size_t, whatever.
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001047 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001048
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001049 FunctionDecl *OperatorNew = 0;
1050 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001051 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
1052 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001053
Sebastian Redl28507842009-02-26 14:39:58 +00001054 if (!AllocType->isDependentType() &&
1055 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
1056 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +00001057 SourceRange(PlacementLParen, PlacementRParen),
1058 UseGlobal, AllocType, ArraySize, PlaceArgs,
1059 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +00001060 return ExprError();
John McCall6ec278d2011-01-27 09:37:56 +00001061
1062 // If this is an array allocation, compute whether the usual array
1063 // deallocation function for the type has a size_t parameter.
1064 bool UsualArrayDeleteWantsSize = false;
1065 if (ArraySize && !AllocType->isDependentType())
1066 UsualArrayDeleteWantsSize
1067 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1068
Chris Lattner5f9e2722011-07-23 10:55:15 +00001069 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001070 if (OperatorNew) {
1071 // Add default arguments, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001072 const FunctionProtoType *Proto =
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001073 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001074 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00001075 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001076
Anders Carlsson28e94832010-05-03 02:07:56 +00001077 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001078 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlsson28e94832010-05-03 02:07:56 +00001079 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001080 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001081
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001082 NumPlaceArgs = AllPlaceArgs.size();
1083 if (NumPlaceArgs > 0)
1084 PlaceArgs = &AllPlaceArgs[0];
1085 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001086
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001087 bool Init = ConstructorLParen.isValid();
1088 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001089 CXXConstructorDecl *Constructor = 0;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001090 bool HadMultipleCandidates = false;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001091 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
1092 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +00001093 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +00001094
Anders Carlsson48c95012010-05-03 15:45:23 +00001095 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +00001096 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +00001097 SourceRange InitRange(ConsArgs[0]->getLocStart(),
1098 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001099
Anders Carlsson48c95012010-05-03 15:45:23 +00001100 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1101 return ExprError();
1102 }
1103
Douglas Gregor99a2e602009-12-16 01:38:02 +00001104 if (!AllocType->isDependentType() &&
1105 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
1106 // C++0x [expr.new]p15:
1107 // A new-expression that creates an object of type T initializes that
1108 // object as follows:
1109 InitializationKind Kind
1110 // - If the new-initializer is omitted, the object is default-
1111 // initialized (8.5); if no initialization is performed,
1112 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001113 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001114 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor99a2e602009-12-16 01:38:02 +00001115 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001116 : InitializationKind::CreateDirect(TypeRange.getBegin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001117 ConstructorLParen,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001118 ConstructorRParen);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001119
Douglas Gregor99a2e602009-12-16 01:38:02 +00001120 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00001121 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001122 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001123 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001124 move(ConstructorArgs));
1125 if (FullInit.isInvalid())
1126 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001127
1128 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor99a2e602009-12-16 01:38:02 +00001129 // constructor call, which CXXNewExpr handles directly.
1130 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1131 if (CXXBindTemporaryExpr *Binder
1132 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1133 FullInitExpr = Binder->getSubExpr();
1134 if (CXXConstructExpr *Construct
1135 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1136 Constructor = Construct->getConstructor();
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001137 HadMultipleCandidates = Construct->hadMultipleCandidates();
Douglas Gregor99a2e602009-12-16 01:38:02 +00001138 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1139 AEnd = Construct->arg_end();
1140 A != AEnd; ++A)
John McCall3fa5cae2010-10-26 07:05:15 +00001141 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001142 } else {
1143 // Take the converted initializer.
1144 ConvertedConstructorArgs.push_back(FullInit.release());
1145 }
1146 } else {
1147 // No initialization required.
1148 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001149
Douglas Gregor99a2e602009-12-16 01:38:02 +00001150 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001151 NumConsArgs = ConvertedConstructorArgs.size();
1152 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001153 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001154
Douglas Gregor6d908702010-02-26 05:06:18 +00001155 // Mark the new and delete operators as referenced.
1156 if (OperatorNew)
1157 MarkDeclarationReferenced(StartLoc, OperatorNew);
1158 if (OperatorDelete)
1159 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1160
John McCall84ff0fc2011-07-13 20:12:57 +00001161 // C++0x [expr.new]p17:
1162 // If the new expression creates an array of objects of class type,
1163 // access and ambiguity control are done for the destructor.
1164 if (ArraySize && Constructor) {
1165 if (CXXDestructorDecl *dtor = LookupDestructor(Constructor->getParent())) {
1166 MarkDeclarationReferenced(StartLoc, dtor);
1167 CheckDestructorAccess(StartLoc, dtor,
1168 PDiag(diag::err_access_dtor)
1169 << Context.getBaseElementType(AllocType));
1170 }
1171 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001172
Sebastian Redlf53597f2009-03-15 17:47:39 +00001173 PlacementArgs.release();
1174 ConstructorArgs.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001175
Ted Kremenekad7fe862010-02-11 22:51:03 +00001176 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001177 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001178 ArraySize, Constructor, Init,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001179 ConsArgs, NumConsArgs,
1180 HadMultipleCandidates,
1181 OperatorDelete,
John McCall6ec278d2011-01-27 09:37:56 +00001182 UsualArrayDeleteWantsSize,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001183 ResultType, AllocTypeInfo,
1184 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001185 Init ? ConstructorRParen :
Chandler Carruth428edaf2010-10-25 08:47:36 +00001186 TypeRange.getEnd(),
1187 ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001188}
1189
1190/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1191/// in a new-expression.
1192/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +00001193bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00001194 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001195 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1196 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +00001197 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001198 return Diag(Loc, diag::err_bad_new_type)
1199 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001200 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001201 return Diag(Loc, diag::err_bad_new_type)
1202 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001203 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +00001204 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001205 PDiag(diag::err_new_incomplete_type)
1206 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001207 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +00001208 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +00001209 diag::err_allocation_of_abstract_type))
1210 return true;
Douglas Gregora0750762010-10-06 16:00:31 +00001211 else if (AllocType->isVariablyModifiedType())
1212 return Diag(Loc, diag::err_variably_modified_new_type)
1213 << AllocType;
Douglas Gregor5666d362011-04-15 19:46:20 +00001214 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1215 return Diag(Loc, diag::err_address_space_qualified_new)
1216 << AllocType.getUnqualifiedType() << AddressSpace;
John McCallf85e1932011-06-15 23:02:42 +00001217 else if (getLangOptions().ObjCAutoRefCount) {
1218 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1219 QualType BaseAllocType = Context.getBaseElementType(AT);
1220 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1221 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001222 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001223 << BaseAllocType;
1224 }
1225 }
Douglas Gregor5666d362011-04-15 19:46:20 +00001226
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001227 return false;
1228}
1229
Douglas Gregor6d908702010-02-26 05:06:18 +00001230/// \brief Determine whether the given function is a non-placement
1231/// deallocation function.
1232static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1233 if (FD->isInvalidDecl())
1234 return false;
1235
1236 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1237 return Method->isUsualDeallocationFunction();
1238
1239 return ((FD->getOverloadedOperator() == OO_Delete ||
1240 FD->getOverloadedOperator() == OO_Array_Delete) &&
1241 FD->getNumParams() == 1);
1242}
1243
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001244/// FindAllocationFunctions - Finds the overloads of operator new and delete
1245/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001246bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1247 bool UseGlobal, QualType AllocType,
1248 bool IsArray, Expr **PlaceArgs,
1249 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001250 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +00001251 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001252 // --- Choosing an allocation function ---
1253 // C++ 5.3.4p8 - 14 & 18
1254 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1255 // in the scope of the allocated class.
1256 // 2) If an array size is given, look for operator new[], else look for
1257 // operator new.
1258 // 3) The first argument is always size_t. Append the arguments from the
1259 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001260
Chris Lattner5f9e2722011-07-23 10:55:15 +00001261 SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001262 // We don't care about the actual value of this argument.
1263 // FIXME: Should the Sema create the expression and embed it in the syntax
1264 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001265 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001266 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssond67c4c32009-08-16 20:29:29 +00001267 Context.getSizeType(),
1268 SourceLocation());
1269 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001270 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1271
Douglas Gregor6d908702010-02-26 05:06:18 +00001272 // C++ [expr.new]p8:
1273 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001274 // function's name is operator new and the deallocation function's
Douglas Gregor6d908702010-02-26 05:06:18 +00001275 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001276 // type, the allocation function's name is operator new[] and the
1277 // deallocation function's name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001278 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1279 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001280 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1281 IsArray ? OO_Array_Delete : OO_Delete);
1282
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001283 QualType AllocElemType = Context.getBaseElementType(AllocType);
1284
1285 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001286 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001287 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001288 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001289 AllocArgs.size(), Record, /*AllowMissing=*/true,
1290 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001291 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001292 }
1293 if (!OperatorNew) {
1294 // Didn't find a member overload. Look for a global one.
1295 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001296 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001297 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001298 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1299 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001300 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001301 }
1302
John McCall9c82afc2010-04-20 02:18:25 +00001303 // We don't need an operator delete if we're running under
1304 // -fno-exceptions.
1305 if (!getLangOptions().Exceptions) {
1306 OperatorDelete = 0;
1307 return false;
1308 }
1309
Anders Carlssond9583892009-05-31 20:26:12 +00001310 // FindAllocationOverload can change the passed in arguments, so we need to
1311 // copy them back.
1312 if (NumPlaceArgs > 0)
1313 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001314
Douglas Gregor6d908702010-02-26 05:06:18 +00001315 // C++ [expr.new]p19:
1316 //
1317 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001318 // deallocation function's name is looked up in the global
Douglas Gregor6d908702010-02-26 05:06:18 +00001319 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001320 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6d908702010-02-26 05:06:18 +00001321 // the scope of T. If this lookup fails to find the name, or if
1322 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001323 // deallocation function's name is looked up in the global scope.
Douglas Gregor6d908702010-02-26 05:06:18 +00001324 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001325 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001326 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001327 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001328 LookupQualifiedName(FoundDelete, RD);
1329 }
John McCall90c8c572010-03-18 08:19:33 +00001330 if (FoundDelete.isAmbiguous())
1331 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001332
1333 if (FoundDelete.empty()) {
1334 DeclareGlobalNewDelete();
1335 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1336 }
1337
1338 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001339
Chris Lattner5f9e2722011-07-23 10:55:15 +00001340 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCall9aa472c2010-03-19 07:35:19 +00001341
John McCalledeb6c92010-09-14 21:34:24 +00001342 // Whether we're looking for a placement operator delete is dictated
1343 // by whether we selected a placement operator new, not by whether
1344 // we had explicit placement arguments. This matters for things like
1345 // struct A { void *operator new(size_t, int = 0); ... };
1346 // A *a = new A()
1347 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1348
1349 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001350 // C++ [expr.new]p20:
1351 // A declaration of a placement deallocation function matches the
1352 // declaration of a placement allocation function if it has the
1353 // same number of parameters and, after parameter transformations
1354 // (8.3.5), all parameter types except the first are
1355 // identical. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001356 //
Douglas Gregor6d908702010-02-26 05:06:18 +00001357 // To perform this comparison, we compute the function type that
1358 // the deallocation function should have, and use that type both
1359 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001360 //
1361 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001362 QualType ExpectedFunctionType;
1363 {
1364 const FunctionProtoType *Proto
1365 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001366
Chris Lattner5f9e2722011-07-23 10:55:15 +00001367 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001368 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6d908702010-02-26 05:06:18 +00001369 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1370 ArgTypes.push_back(Proto->getArgType(I));
1371
John McCalle23cf432010-12-14 08:05:40 +00001372 FunctionProtoType::ExtProtoInfo EPI;
1373 EPI.Variadic = Proto->isVariadic();
1374
Douglas Gregor6d908702010-02-26 05:06:18 +00001375 ExpectedFunctionType
1376 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalle23cf432010-12-14 08:05:40 +00001377 ArgTypes.size(), EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001378 }
1379
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001380 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001381 DEnd = FoundDelete.end();
1382 D != DEnd; ++D) {
1383 FunctionDecl *Fn = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001384 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6d908702010-02-26 05:06:18 +00001385 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1386 // Perform template argument deduction to try to match the
1387 // expected function type.
1388 TemplateDeductionInfo Info(Context, StartLoc);
1389 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1390 continue;
1391 } else
1392 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1393
1394 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001395 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001396 }
1397 } else {
1398 // C++ [expr.new]p20:
1399 // [...] Any non-placement deallocation function matches a
1400 // non-placement allocation function. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001401 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001402 DEnd = FoundDelete.end();
1403 D != DEnd; ++D) {
1404 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1405 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001406 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001407 }
1408 }
1409
1410 // C++ [expr.new]p20:
1411 // [...] If the lookup finds a single matching deallocation
1412 // function, that function will be called; otherwise, no
1413 // deallocation function will be called.
1414 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001415 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001416
1417 // C++0x [expr.new]p20:
1418 // If the lookup finds the two-parameter form of a usual
1419 // deallocation function (3.7.4.2) and that function, considered
1420 // as a placement deallocation function, would have been
1421 // selected as a match for the allocation function, the program
1422 // is ill-formed.
1423 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1424 isNonPlacementDeallocationFunction(OperatorDelete)) {
1425 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001426 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001427 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1428 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1429 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001430 } else {
1431 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001432 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001433 }
1434 }
1435
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001436 return false;
1437}
1438
Sebastian Redl7f662392008-12-04 22:20:51 +00001439/// FindAllocationOverload - Find an fitting overload for the allocation
1440/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001441bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1442 DeclarationName Name, Expr** Args,
1443 unsigned NumArgs, DeclContext *Ctx,
Sean Hunt2be7e902011-05-12 22:46:29 +00001444 bool AllowMissing, FunctionDecl *&Operator,
1445 bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001446 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1447 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001448 if (R.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001449 if (AllowMissing || !Diagnose)
Sebastian Redl7f662392008-12-04 22:20:51 +00001450 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001451 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001452 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001453 }
1454
John McCall90c8c572010-03-18 08:19:33 +00001455 if (R.isAmbiguous())
1456 return true;
1457
1458 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001459
John McCall5769d612010-02-08 23:07:23 +00001460 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001461 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001462 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001463 // Even member operator new/delete are implicitly treated as
1464 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001465 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001466
John McCall9aa472c2010-03-19 07:35:19 +00001467 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1468 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001469 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1470 Candidates,
1471 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001472 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001473 }
1474
John McCall9aa472c2010-03-19 07:35:19 +00001475 FunctionDecl *Fn = cast<FunctionDecl>(D);
1476 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001477 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001478 }
1479
1480 // Do the resolution.
1481 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001482 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001483 case OR_Success: {
1484 // Got one!
1485 FunctionDecl *FnDecl = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00001486 MarkDeclarationReferenced(StartLoc, FnDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001487 // The first argument is size_t, and the first parameter must be size_t,
1488 // too. This is checked on declaration and can be assumed. (It can't be
1489 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001490 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001491 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1492 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001493 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1494 FnDecl->getParamDecl(i));
1495
1496 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1497 return true;
1498
John McCall60d7b3a2010-08-24 06:29:42 +00001499 ExprResult Result
Sean Hunt2be7e902011-05-12 22:46:29 +00001500 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001501 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001502 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001503
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001504 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001505 }
1506 Operator = FnDecl;
Sean Hunt2be7e902011-05-12 22:46:29 +00001507 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl,
1508 Diagnose);
Sebastian Redl7f662392008-12-04 22:20:51 +00001509 return false;
1510 }
1511
1512 case OR_No_Viable_Function:
Chandler Carruth361d3802011-06-08 10:26:03 +00001513 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001514 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1515 << Name << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001516 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1517 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001518 return true;
1519
1520 case OR_Ambiguous:
Chandler Carruth361d3802011-06-08 10:26:03 +00001521 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001522 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1523 << Name << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001524 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
1525 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001526 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001527
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001528 case OR_Deleted: {
Chandler Carruth361d3802011-06-08 10:26:03 +00001529 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001530 Diag(StartLoc, diag::err_ovl_deleted_call)
1531 << Best->Function->isDeleted()
1532 << Name
1533 << getDeletedOrUnavailableSuffix(Best->Function)
1534 << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001535 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1536 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001537 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001538 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001539 }
David Blaikieb219cfc2011-09-23 05:06:16 +00001540 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Sebastian Redl7f662392008-12-04 22:20:51 +00001541}
1542
1543
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001544/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1545/// delete. These are:
1546/// @code
Sebastian Redl8999fe12011-03-14 18:08:30 +00001547/// // C++03:
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001548/// void* operator new(std::size_t) throw(std::bad_alloc);
1549/// void* operator new[](std::size_t) throw(std::bad_alloc);
1550/// void operator delete(void *) throw();
1551/// void operator delete[](void *) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001552/// // C++0x:
1553/// void* operator new(std::size_t);
1554/// void* operator new[](std::size_t);
1555/// void operator delete(void *);
1556/// void operator delete[](void *);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001557/// @endcode
Sebastian Redl8999fe12011-03-14 18:08:30 +00001558/// C++0x operator delete is implicitly noexcept.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001559/// Note that the placement and nothrow forms of new are *not* implicitly
1560/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001561void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001562 if (GlobalNewDeleteDeclared)
1563 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001564
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001565 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001566 // [...] The following allocation and deallocation functions (18.4) are
1567 // implicitly declared in global scope in each translation unit of a
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001568 // program
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001569 //
Sebastian Redl8999fe12011-03-14 18:08:30 +00001570 // C++03:
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001571 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001572 // void* operator new[](std::size_t) throw(std::bad_alloc);
1573 // void operator delete(void*) throw();
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001574 // void operator delete[](void*) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001575 // C++0x:
1576 // void* operator new(std::size_t);
1577 // void* operator new[](std::size_t);
1578 // void operator delete(void*);
1579 // void operator delete[](void*);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001580 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001581 // These implicit declarations introduce only the function names operator
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001582 // new, operator new[], operator delete, operator delete[].
1583 //
1584 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1585 // "std" or "bad_alloc" as necessary to form the exception specification.
1586 // However, we do not make these implicit declarations visible to name
1587 // lookup.
Sebastian Redl8999fe12011-03-14 18:08:30 +00001588 // Note that the C++0x versions of operator delete are deallocation functions,
1589 // and thus are implicitly noexcept.
1590 if (!StdBadAlloc && !getLangOptions().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001591 // The "std::bad_alloc" class has not yet been declared, so build it
1592 // implicitly.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001593 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1594 getOrCreateStdNamespace(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001595 SourceLocation(), SourceLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001596 &PP.getIdentifierTable().get("bad_alloc"),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001597 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001598 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001599 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001600
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001601 GlobalNewDeleteDeclared = true;
1602
1603 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1604 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001605 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001606
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001607 DeclareGlobalAllocationFunction(
1608 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001609 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001610 DeclareGlobalAllocationFunction(
1611 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001612 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001613 DeclareGlobalAllocationFunction(
1614 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1615 Context.VoidTy, VoidPtr);
1616 DeclareGlobalAllocationFunction(
1617 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1618 Context.VoidTy, VoidPtr);
1619}
1620
1621/// DeclareGlobalAllocationFunction - Declares a single implicit global
1622/// allocation function if it doesn't already exist.
1623void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001624 QualType Return, QualType Argument,
1625 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001626 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1627
1628 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001629 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001630 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001631 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001632 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001633 // Only look at non-template functions, as it is the predefined,
1634 // non-templated allocation function we are trying to declare here.
1635 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1636 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001637 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001638 Func->getParamDecl(0)->getType().getUnqualifiedType());
1639 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001640 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1641 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001642 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001643 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001644 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001645 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001646 }
1647 }
1648
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001649 QualType BadAllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001650 bool HasBadAllocExceptionSpec
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001651 = (Name.getCXXOverloadedOperator() == OO_New ||
1652 Name.getCXXOverloadedOperator() == OO_Array_New);
Sebastian Redl8999fe12011-03-14 18:08:30 +00001653 if (HasBadAllocExceptionSpec && !getLangOptions().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001654 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001655 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001656 }
John McCalle23cf432010-12-14 08:05:40 +00001657
1658 FunctionProtoType::ExtProtoInfo EPI;
John McCalle23cf432010-12-14 08:05:40 +00001659 if (HasBadAllocExceptionSpec) {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001660 if (!getLangOptions().CPlusPlus0x) {
1661 EPI.ExceptionSpecType = EST_Dynamic;
1662 EPI.NumExceptions = 1;
1663 EPI.Exceptions = &BadAllocType;
1664 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00001665 } else {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001666 EPI.ExceptionSpecType = getLangOptions().CPlusPlus0x ?
1667 EST_BasicNoexcept : EST_DynamicNone;
John McCalle23cf432010-12-14 08:05:40 +00001668 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001669
John McCalle23cf432010-12-14 08:05:40 +00001670 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001671 FunctionDecl *Alloc =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001672 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1673 SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001674 FnType, /*TInfo=*/0, SC_None,
1675 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001676 Alloc->setImplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001677
Nuno Lopesfc284482009-12-16 16:59:22 +00001678 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001679 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001680
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001681 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001682 SourceLocation(), 0,
1683 Argument, /*TInfo=*/0,
1684 SC_None, SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00001685 Alloc->setParams(Param);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001686
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001687 // FIXME: Also add this declaration to the IdentifierResolver, but
1688 // make sure it is at the end of the chain to coincide with the
1689 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001690 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001691}
1692
Anders Carlsson78f74552009-11-15 18:45:20 +00001693bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1694 DeclarationName Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001695 FunctionDecl* &Operator, bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001696 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001697 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001698 LookupQualifiedName(Found, RD);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001699
John McCalla24dc2e2009-11-17 02:14:36 +00001700 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001701 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001702
Chandler Carruth23893242010-06-28 00:30:51 +00001703 Found.suppressDiagnostics();
1704
Chris Lattner5f9e2722011-07-23 10:55:15 +00001705 SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001706 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1707 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001708 NamedDecl *ND = (*F)->getUnderlyingDecl();
1709
1710 // Ignore template operator delete members from the check for a usual
1711 // deallocation function.
1712 if (isa<FunctionTemplateDecl>(ND))
1713 continue;
1714
1715 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001716 Matches.push_back(F.getPair());
1717 }
1718
1719 // There's exactly one suitable operator; pick it.
1720 if (Matches.size() == 1) {
1721 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
Sean Hunt2be7e902011-05-12 22:46:29 +00001722
1723 if (Operator->isDeleted()) {
1724 if (Diagnose) {
1725 Diag(StartLoc, diag::err_deleted_function_use);
1726 Diag(Operator->getLocation(), diag::note_unavailable_here) << true;
1727 }
1728 return true;
1729 }
1730
John McCall046a7462010-08-04 00:31:26 +00001731 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Sean Hunt2be7e902011-05-12 22:46:29 +00001732 Matches[0], Diagnose);
John McCall046a7462010-08-04 00:31:26 +00001733 return false;
1734
1735 // We found multiple suitable operators; complain about the ambiguity.
1736 } else if (!Matches.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001737 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001738 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1739 << Name << RD;
John McCall046a7462010-08-04 00:31:26 +00001740
Chris Lattner5f9e2722011-07-23 10:55:15 +00001741 for (SmallVectorImpl<DeclAccessPair>::iterator
Sean Huntcb45a0f2011-05-12 22:46:25 +00001742 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1743 Diag((*F)->getUnderlyingDecl()->getLocation(),
1744 diag::note_member_declared_here) << Name;
1745 }
John McCall046a7462010-08-04 00:31:26 +00001746 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001747 }
1748
1749 // We did find operator delete/operator delete[] declarations, but
1750 // none of them were suitable.
1751 if (!Found.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001752 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001753 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1754 << Name << RD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001755
Sean Huntcb45a0f2011-05-12 22:46:25 +00001756 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1757 F != FEnd; ++F)
1758 Diag((*F)->getUnderlyingDecl()->getLocation(),
1759 diag::note_member_declared_here) << Name;
1760 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001761 return true;
1762 }
1763
1764 // Look for a global declaration.
1765 DeclareGlobalNewDelete();
1766 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001767
Anders Carlsson78f74552009-11-15 18:45:20 +00001768 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1769 Expr* DeallocArgs[1];
1770 DeallocArgs[0] = &Null;
1771 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001772 DeallocArgs, 1, TUDecl, !Diagnose,
1773 Operator, Diagnose))
Anders Carlsson78f74552009-11-15 18:45:20 +00001774 return true;
1775
1776 assert(Operator && "Did not find a deallocation function!");
1777 return false;
1778}
1779
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001780/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1781/// @code ::delete ptr; @endcode
1782/// or
1783/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001784ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001785Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley429bb272011-04-08 18:41:53 +00001786 bool ArrayForm, Expr *ExE) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001787 // C++ [expr.delete]p1:
1788 // The operand shall have a pointer type, or a class type having a single
1789 // conversion function to a pointer type. The result has type void.
1790 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001791 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1792
John Wiegley429bb272011-04-08 18:41:53 +00001793 ExprResult Ex = Owned(ExE);
Anders Carlssond67c4c32009-08-16 20:29:29 +00001794 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001795 bool ArrayFormAsWritten = ArrayForm;
John McCall6ec278d2011-01-27 09:37:56 +00001796 bool UsualArrayDeleteWantsSize = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001797
John Wiegley429bb272011-04-08 18:41:53 +00001798 if (!Ex.get()->isTypeDependent()) {
1799 QualType Type = Ex.get()->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001800
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001801 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001802 if (RequireCompleteType(StartLoc, Type,
Douglas Gregor254a9422010-07-29 14:44:35 +00001803 PDiag(diag::err_delete_incomplete_class_type)))
1804 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001805
Chris Lattner5f9e2722011-07-23 10:55:15 +00001806 SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
John McCall32daa422010-03-31 01:36:47 +00001807
Fariborz Jahanian53462782009-09-11 21:44:33 +00001808 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001809 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001810 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001811 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001812 NamedDecl *D = I.getDecl();
1813 if (isa<UsingShadowDecl>(D))
1814 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1815
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001816 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001817 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001818 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001819
John McCall32daa422010-03-31 01:36:47 +00001820 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001821
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001822 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1823 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001824 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001825 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001826 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001827 if (ObjectPtrConversions.size() == 1) {
1828 // We have a single conversion to a pointer-to-object type. Perform
1829 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001830 // TODO: don't redo the conversion calculation.
John Wiegley429bb272011-04-08 18:41:53 +00001831 ExprResult Res =
1832 PerformImplicitConversion(Ex.get(),
John McCall32daa422010-03-31 01:36:47 +00001833 ObjectPtrConversions.front()->getConversionType(),
John Wiegley429bb272011-04-08 18:41:53 +00001834 AA_Converting);
1835 if (Res.isUsable()) {
1836 Ex = move(Res);
1837 Type = Ex.get()->getType();
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001838 }
1839 }
1840 else if (ObjectPtrConversions.size() > 1) {
1841 Diag(StartLoc, diag::err_ambiguous_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001842 << Type << Ex.get()->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001843 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1844 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001845 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001846 }
Sebastian Redl28507842009-02-26 14:39:58 +00001847 }
1848
Sebastian Redlf53597f2009-03-15 17:47:39 +00001849 if (!Type->isPointerType())
1850 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001851 << Type << Ex.get()->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001852
Ted Kremenek6217b802009-07-29 21:53:49 +00001853 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmane52c9142011-07-26 22:25:31 +00001854 QualType PointeeElem = Context.getBaseElementType(Pointee);
1855
1856 if (unsigned AddressSpace = Pointee.getAddressSpace())
1857 return Diag(Ex.get()->getLocStart(),
1858 diag::err_address_space_qualified_delete)
1859 << Pointee.getUnqualifiedType() << AddressSpace;
1860
1861 CXXRecordDecl *PointeeRD = 0;
Douglas Gregor94a61572010-05-24 17:01:56 +00001862 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001863 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregor94a61572010-05-24 17:01:56 +00001864 // effectively bans deletion of "void*". However, most compilers support
1865 // this, so we treat it as a warning unless we're in a SFINAE context.
1866 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001867 << Type << Ex.get()->getSourceRange();
Eli Friedmane52c9142011-07-26 22:25:31 +00001868 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00001869 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001870 << Type << Ex.get()->getSourceRange());
Eli Friedmane52c9142011-07-26 22:25:31 +00001871 } else if (!Pointee->isDependentType()) {
1872 if (!RequireCompleteType(StartLoc, Pointee,
1873 PDiag(diag::warn_delete_incomplete)
1874 << Ex.get()->getSourceRange())) {
1875 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
1876 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
1877 }
1878 }
1879
Abramo Bagnara30bb4202011-11-16 15:42:13 +00001880 // Perform lvalue-to-rvalue cast, if needed.
1881 Ex = DefaultLvalueConversion(Ex.take());
1882
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001883 // C++ [expr.delete]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001884 // [Note: a pointer to a const type can be the operand of a
1885 // delete-expression; it is not necessary to cast away the constness
1886 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001887 // of the delete-expression. ]
John McCallf85e1932011-06-15 23:02:42 +00001888 if (!Context.hasSameType(Ex.get()->getType(), Context.VoidPtrTy))
Abramo Bagnara30bb4202011-11-16 15:42:13 +00001889 Ex = Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy,
1890 CK_BitCast, Ex.take(), 0, VK_RValue));
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001891
1892 if (Pointee->isArrayType() && !ArrayForm) {
1893 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley429bb272011-04-08 18:41:53 +00001894 << Type << Ex.get()->getSourceRange()
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001895 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1896 ArrayForm = true;
1897 }
1898
Anders Carlssond67c4c32009-08-16 20:29:29 +00001899 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1900 ArrayForm ? OO_Array_Delete : OO_Delete);
1901
Eli Friedmane52c9142011-07-26 22:25:31 +00001902 if (PointeeRD) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001903 if (!UseGlobal &&
Eli Friedmane52c9142011-07-26 22:25:31 +00001904 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
1905 OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001906 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001907
John McCall6ec278d2011-01-27 09:37:56 +00001908 // If we're allocating an array of records, check whether the
1909 // usual operator delete[] has a size_t parameter.
1910 if (ArrayForm) {
1911 // If the user specifically asked to use the global allocator,
1912 // we'll need to do the lookup into the class.
1913 if (UseGlobal)
1914 UsualArrayDeleteWantsSize =
1915 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1916
1917 // Otherwise, the usual operator delete[] should be the
1918 // function we just found.
1919 else if (isa<CXXMethodDecl>(OperatorDelete))
1920 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1921 }
1922
Eli Friedmane52c9142011-07-26 22:25:31 +00001923 if (!PointeeRD->hasTrivialDestructor())
1924 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001925 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001926 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00001927 DiagnoseUseOfDecl(Dtor, StartLoc);
1928 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00001929
1930 // C++ [expr.delete]p3:
1931 // In the first alternative (delete object), if the static type of the
1932 // object to be deleted is different from its dynamic type, the static
1933 // type shall be a base class of the dynamic type of the object to be
1934 // deleted and the static type shall have a virtual destructor or the
1935 // behavior is undefined.
1936 //
1937 // Note: a final class cannot be derived from, no issue there
Eli Friedmanef8c79c2011-07-26 23:27:24 +00001938 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
Eli Friedmane52c9142011-07-26 22:25:31 +00001939 CXXDestructorDecl *dtor = PointeeRD->getDestructor();
Eli Friedmanef8c79c2011-07-26 23:27:24 +00001940 if (dtor && !dtor->isVirtual()) {
1941 if (PointeeRD->isAbstract()) {
1942 // If the class is abstract, we warn by default, because we're
1943 // sure the code has undefined behavior.
1944 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
1945 << PointeeElem;
1946 } else if (!ArrayForm) {
1947 // Otherwise, if this is not an array delete, it's a bit suspect,
1948 // but not necessarily wrong.
1949 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
1950 }
1951 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00001952 }
John McCallf85e1932011-06-15 23:02:42 +00001953
1954 } else if (getLangOptions().ObjCAutoRefCount &&
1955 PointeeElem->isObjCLifetimeType() &&
1956 (PointeeElem.getObjCLifetime() == Qualifiers::OCL_Strong ||
1957 PointeeElem.getObjCLifetime() == Qualifiers::OCL_Weak) &&
1958 ArrayForm) {
1959 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1960 << 1 << PointeeElem;
Anders Carlssond67c4c32009-08-16 20:29:29 +00001961 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001962
Anders Carlssond67c4c32009-08-16 20:29:29 +00001963 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001964 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001965 DeclareGlobalNewDelete();
1966 DeclContext *TUDecl = Context.getTranslationUnitDecl();
John Wiegley429bb272011-04-08 18:41:53 +00001967 Expr *Arg = Ex.get();
Mike Stump1eb44332009-09-09 15:08:12 +00001968 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
John Wiegley429bb272011-04-08 18:41:53 +00001969 &Arg, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001970 OperatorDelete))
1971 return ExprError();
1972 }
Mike Stump1eb44332009-09-09 15:08:12 +00001973
John McCall9c82afc2010-04-20 02:18:25 +00001974 MarkDeclarationReferenced(StartLoc, OperatorDelete);
John McCall6ec278d2011-01-27 09:37:56 +00001975
Douglas Gregord880f522011-02-01 15:50:11 +00001976 // Check access and ambiguity of operator delete and destructor.
Eli Friedmane52c9142011-07-26 22:25:31 +00001977 if (PointeeRD) {
1978 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
John Wiegley429bb272011-04-08 18:41:53 +00001979 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregord880f522011-02-01 15:50:11 +00001980 PDiag(diag::err_access_dtor) << PointeeElem);
1981 }
1982 }
1983
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001984 }
1985
Sebastian Redlf53597f2009-03-15 17:47:39 +00001986 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall6ec278d2011-01-27 09:37:56 +00001987 ArrayFormAsWritten,
1988 UsualArrayDeleteWantsSize,
John Wiegley429bb272011-04-08 18:41:53 +00001989 OperatorDelete, Ex.take(), StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001990}
1991
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001992/// \brief Check the use of the given variable as a C++ condition in an if,
1993/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001994ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00001995 SourceLocation StmtLoc,
1996 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001997 QualType T = ConditionVar->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001998
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001999 // C++ [stmt.select]p2:
2000 // The declarator shall not specify a function or an array.
2001 if (T->isFunctionType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002002 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002003 diag::err_invalid_use_of_function_type)
2004 << ConditionVar->getSourceRange());
2005 else if (T->isArrayType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002006 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002007 diag::err_invalid_use_of_array_type)
2008 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00002009
John Wiegley429bb272011-04-08 18:41:53 +00002010 ExprResult Condition =
2011 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
Douglas Gregor40d96a62011-02-28 21:54:11 +00002012 ConditionVar,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002013 ConditionVar->getLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00002014 ConditionVar->getType().getNonReferenceType(),
John Wiegley429bb272011-04-08 18:41:53 +00002015 VK_LValue));
2016 if (ConvertToBoolean) {
2017 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
2018 if (Condition.isInvalid())
2019 return ExprError();
2020 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002021
John Wiegley429bb272011-04-08 18:41:53 +00002022 return move(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002023}
2024
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002025/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley429bb272011-04-08 18:41:53 +00002026ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002027 // C++ 6.4p4:
2028 // The value of a condition that is an initialized declaration in a statement
2029 // other than a switch statement is the value of the declared variable
2030 // implicitly converted to type bool. If that conversion is ill-formed, the
2031 // program is ill-formed.
2032 // The value of a condition that is an expression is the value of the
2033 // expression, implicitly converted to bool.
2034 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002035 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002036}
Douglas Gregor77a52232008-09-12 00:47:35 +00002037
2038/// Helper function to determine whether this is the (deprecated) C++
2039/// conversion from a string literal to a pointer to non-const char or
2040/// non-const wchar_t (for narrow and wide string literals,
2041/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00002042bool
Douglas Gregor77a52232008-09-12 00:47:35 +00002043Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2044 // Look inside the implicit cast, if it exists.
2045 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2046 From = Cast->getSubExpr();
2047
2048 // A string literal (2.13.4) that is not a wide string literal can
2049 // be converted to an rvalue of type "pointer to char"; a wide
2050 // string literal can be converted to an rvalue of type "pointer
2051 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00002052 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00002053 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00002054 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00002055 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00002056 // This conversion is considered only when there is an
2057 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregor5cee1192011-07-27 05:40:30 +00002058 if (!ToPtrType->getPointeeType().hasQualifiers()) {
2059 switch (StrLit->getKind()) {
2060 case StringLiteral::UTF8:
2061 case StringLiteral::UTF16:
2062 case StringLiteral::UTF32:
2063 // We don't allow UTF literals to be implicitly converted
2064 break;
2065 case StringLiteral::Ascii:
2066 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2067 ToPointeeType->getKind() == BuiltinType::Char_S);
2068 case StringLiteral::Wide:
2069 return ToPointeeType->isWideCharType();
2070 }
2071 }
Douglas Gregor77a52232008-09-12 00:47:35 +00002072 }
2073
2074 return false;
2075}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002076
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002077static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00002078 SourceLocation CastLoc,
2079 QualType Ty,
2080 CastKind Kind,
2081 CXXMethodDecl *Method,
John McCallca82a822011-09-21 08:36:56 +00002082 DeclAccessPair FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002083 bool HadMultipleCandidates,
John McCall2de56d12010-08-25 11:45:40 +00002084 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002085 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002086 default: llvm_unreachable("Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00002087 case CK_ConstructorConversion: {
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002088 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
John McCallca0408f2010-08-23 06:44:23 +00002089 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002090
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002091 if (S.CompleteConstructorCall(Constructor,
John McCallf312b1e2010-08-26 23:41:50 +00002092 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00002093 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00002094 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002095
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002096 S.CheckConstructorAccess(CastLoc, Constructor, Constructor->getAccess(),
2097 S.PDiag(diag::err_access_ctor));
2098
2099 ExprResult Result
2100 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2101 move_arg(ConstructorArgs),
2102 HadMultipleCandidates, /*ZeroInit*/ false,
2103 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002104 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00002105 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002106
Douglas Gregorba70ab62010-04-16 22:17:36 +00002107 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2108 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002109
John McCall2de56d12010-08-25 11:45:40 +00002110 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002111 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002112
Douglas Gregorba70ab62010-04-16 22:17:36 +00002113 // Create an implicit call expr that calls it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002114 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method,
2115 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002116 if (Result.isInvalid())
2117 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00002118 // Record usage of conversion in an implicit cast.
2119 Result = S.Owned(ImplicitCastExpr::Create(S.Context,
2120 Result.get()->getType(),
2121 CK_UserDefinedConversion,
2122 Result.get(), 0,
2123 Result.get()->getValueKind()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002124
John McCallca82a822011-09-21 08:36:56 +00002125 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2126
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002127 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002128 }
2129 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002130}
Douglas Gregorba70ab62010-04-16 22:17:36 +00002131
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002132/// PerformImplicitConversion - Perform an implicit conversion of the
2133/// expression From to the type ToType using the pre-computed implicit
John Wiegley429bb272011-04-08 18:41:53 +00002134/// conversion sequence ICS. Returns the converted
Douglas Gregor68647482009-12-16 03:45:30 +00002135/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002136/// used in the error message.
John Wiegley429bb272011-04-08 18:41:53 +00002137ExprResult
2138Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002139 const ImplicitConversionSequence &ICS,
John McCallf85e1932011-06-15 23:02:42 +00002140 AssignmentAction Action,
2141 CheckedConversionKind CCK) {
John McCall1d318332010-01-12 00:44:57 +00002142 switch (ICS.getKind()) {
John Wiegley429bb272011-04-08 18:41:53 +00002143 case ImplicitConversionSequence::StandardConversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002144 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2145 Action, CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002146 if (Res.isInvalid())
2147 return ExprError();
2148 From = Res.take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002149 break;
John Wiegley429bb272011-04-08 18:41:53 +00002150 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002151
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002152 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002153
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00002154 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00002155 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002156 QualType BeforeToType;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00002157 assert(FD && "FIXME: aggregate initialization from init list");
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002158 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00002159 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002160
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002161 // If the user-defined conversion is specified by a conversion function,
2162 // the initial standard conversion sequence converts the source type to
2163 // the implicit object parameter of the conversion function.
2164 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00002165 } else {
2166 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00002167 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002168 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00002169 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002170 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002171 // initial standard conversion sequence converts the source type to the
2172 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00002173 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2174 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002175 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00002176 // Watch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00002177 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley429bb272011-04-08 18:41:53 +00002178 ExprResult Res =
Richard Smithc8d7f582011-11-29 22:48:16 +00002179 PerformImplicitConversion(From, BeforeToType,
2180 ICS.UserDefined.Before, AA_Converting,
2181 CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002182 if (Res.isInvalid())
2183 return ExprError();
2184 From = Res.take();
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002185 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002186
2187 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00002188 = BuildCXXCastArgument(*this,
2189 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00002190 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002191 CastKind, cast<CXXMethodDecl>(FD),
2192 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002193 ICS.UserDefined.HadMultipleCandidates,
John McCall9ae2f072010-08-23 23:25:46 +00002194 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002195
2196 if (CastArg.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00002197 return ExprError();
Eli Friedmand8889622009-11-27 04:41:50 +00002198
John Wiegley429bb272011-04-08 18:41:53 +00002199 From = CastArg.take();
Eli Friedmand8889622009-11-27 04:41:50 +00002200
Richard Smithc8d7f582011-11-29 22:48:16 +00002201 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2202 AA_Converting, CCK);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00002203 }
John McCall1d318332010-01-12 00:44:57 +00002204
2205 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00002206 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00002207 PDiag(diag::err_typecheck_ambiguous_condition)
2208 << From->getSourceRange());
John Wiegley429bb272011-04-08 18:41:53 +00002209 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002210
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002211 case ImplicitConversionSequence::EllipsisConversion:
David Blaikieb219cfc2011-09-23 05:06:16 +00002212 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002213
2214 case ImplicitConversionSequence::BadConversion:
John Wiegley429bb272011-04-08 18:41:53 +00002215 return ExprError();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002216 }
2217
2218 // Everything went well.
John Wiegley429bb272011-04-08 18:41:53 +00002219 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002220}
2221
Richard Smithc8d7f582011-11-29 22:48:16 +00002222/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002223/// expression From to the type ToType by following the standard
John Wiegley429bb272011-04-08 18:41:53 +00002224/// conversion sequence SCS. Returns the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00002225/// expression. Flavor is the context in which we're performing this
2226/// conversion, for use in error messages.
John Wiegley429bb272011-04-08 18:41:53 +00002227ExprResult
Richard Smithc8d7f582011-11-29 22:48:16 +00002228Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00002229 const StandardConversionSequence& SCS,
John McCallf85e1932011-06-15 23:02:42 +00002230 AssignmentAction Action,
2231 CheckedConversionKind CCK) {
2232 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2233
Mike Stump390b4cc2009-05-16 07:39:55 +00002234 // Overall FIXME: we are recomputing too many types here and doing far too
2235 // much extra work. What this means is that we need to keep track of more
2236 // information that is computed when we try the implicit conversion initially,
2237 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002238 QualType FromType = From->getType();
John McCallf85e1932011-06-15 23:02:42 +00002239
Douglas Gregor225c41e2008-11-03 19:09:14 +00002240 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00002241 // FIXME: When can ToType be a reference type?
2242 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002243 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00002244 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002245 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00002246 MultiExprArg(*this, &From, 1),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002247 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002248 ConstructorArgs))
John Wiegley429bb272011-04-08 18:41:53 +00002249 return ExprError();
2250 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2251 ToType, SCS.CopyConstructor,
2252 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002253 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002254 /*ZeroInit*/ false,
2255 CXXConstructExpr::CK_Complete,
2256 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002257 }
John Wiegley429bb272011-04-08 18:41:53 +00002258 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2259 ToType, SCS.CopyConstructor,
2260 MultiExprArg(*this, &From, 1),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002261 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002262 /*ZeroInit*/ false,
2263 CXXConstructExpr::CK_Complete,
2264 SourceRange());
Douglas Gregor225c41e2008-11-03 19:09:14 +00002265 }
2266
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002267 // Resolve overloaded function references.
2268 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2269 DeclAccessPair Found;
2270 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2271 true, Found);
2272 if (!Fn)
John Wiegley429bb272011-04-08 18:41:53 +00002273 return ExprError();
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002274
2275 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
John Wiegley429bb272011-04-08 18:41:53 +00002276 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002277
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002278 From = FixOverloadedFunctionReference(From, Found, Fn);
2279 FromType = From->getType();
2280 }
2281
Richard Smithc8d7f582011-11-29 22:48:16 +00002282 // Perform the first implicit conversion.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002283 switch (SCS.First) {
2284 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002285 // Nothing to do.
2286 break;
2287
John McCallf6a16482010-12-04 03:47:34 +00002288 case ICK_Lvalue_To_Rvalue:
John McCall3c3b7f92011-10-25 17:37:35 +00002289 assert(From->getObjectKind() != OK_ObjCProperty);
John McCallf6a16482010-12-04 03:47:34 +00002290 FromType = FromType.getUnqualifiedType();
2291 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2292 From, 0, VK_RValue);
2293 break;
2294
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002295 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002296 FromType = Context.getArrayDecayedType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002297 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2298 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002299 break;
2300
2301 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002302 FromType = Context.getPointerType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002303 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2304 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002305 break;
2306
2307 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002308 llvm_unreachable("Improper first standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002309 }
2310
Richard Smithc8d7f582011-11-29 22:48:16 +00002311 // Perform the second implicit conversion
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002312 switch (SCS.Second) {
2313 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002314 // If both sides are functions (or pointers/references to them), there could
2315 // be incompatible exception declarations.
2316 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002317 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002318 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002319 break;
2320
Douglas Gregor43c79c22009-12-09 00:47:37 +00002321 case ICK_NoReturn_Adjustment:
2322 // If both sides are functions (or pointers/references to them), there could
2323 // be incompatible exception declarations.
2324 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002325 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002326
Richard Smithc8d7f582011-11-29 22:48:16 +00002327 From = ImpCastExprToType(From, ToType, CK_NoOp,
2328 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor43c79c22009-12-09 00:47:37 +00002329 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002330
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002331 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002332 case ICK_Integral_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002333 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2334 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002335 break;
2336
2337 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002338 case ICK_Floating_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002339 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2340 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002341 break;
2342
2343 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00002344 case ICK_Complex_Conversion: {
2345 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2346 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2347 CastKind CK;
2348 if (FromEl->isRealFloatingType()) {
2349 if (ToEl->isRealFloatingType())
2350 CK = CK_FloatingComplexCast;
2351 else
2352 CK = CK_FloatingComplexToIntegralComplex;
2353 } else if (ToEl->isRealFloatingType()) {
2354 CK = CK_IntegralComplexToFloatingComplex;
2355 } else {
2356 CK = CK_IntegralComplexCast;
2357 }
Richard Smithc8d7f582011-11-29 22:48:16 +00002358 From = ImpCastExprToType(From, ToType, CK,
2359 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002360 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00002361 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002362
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002363 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002364 if (ToType->isRealFloatingType())
Richard Smithc8d7f582011-11-29 22:48:16 +00002365 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2366 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002367 else
Richard Smithc8d7f582011-11-29 22:48:16 +00002368 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2369 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002370 break;
2371
Douglas Gregorf9201e02009-02-11 23:02:49 +00002372 case ICK_Compatible_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002373 From = ImpCastExprToType(From, ToType, CK_NoOp,
2374 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002375 break;
2376
John McCallf85e1932011-06-15 23:02:42 +00002377 case ICK_Writeback_Conversion:
Anders Carlsson61faec12009-09-12 04:46:44 +00002378 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00002379 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002380 // Diagnose incompatible Objective-C conversions
Douglas Gregor8cf0d222011-06-11 04:42:12 +00002381 if (Action == AA_Initializing || Action == AA_Assigning)
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002382 Diag(From->getSourceRange().getBegin(),
2383 diag::ext_typecheck_convert_incompatible_pointer)
2384 << ToType << From->getType() << Action
Anna Zaks67221552011-07-28 19:51:27 +00002385 << From->getSourceRange() << 0;
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002386 else
2387 Diag(From->getSourceRange().getBegin(),
2388 diag::ext_typecheck_convert_incompatible_pointer)
2389 << From->getType() << ToType << Action
Anna Zaks67221552011-07-28 19:51:27 +00002390 << From->getSourceRange() << 0;
John McCallf85e1932011-06-15 23:02:42 +00002391
Douglas Gregor926df6c2011-06-11 01:09:30 +00002392 if (From->getType()->isObjCObjectPointerType() &&
2393 ToType->isObjCObjectPointerType())
2394 EmitRelatedResultTypeNote(From);
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002395 }
2396 else if (getLangOptions().ObjCAutoRefCount &&
2397 !CheckObjCARCUnavailableWeakConversion(ToType,
2398 From->getType())) {
John McCall7f3a6d32011-09-09 06:12:06 +00002399 if (Action == AA_Initializing)
2400 Diag(From->getSourceRange().getBegin(),
2401 diag::err_arc_weak_unavailable_assign);
2402 else
2403 Diag(From->getSourceRange().getBegin(),
2404 diag::err_arc_convesion_of_weak_unavailable)
2405 << (Action == AA_Casting) << From->getType() << ToType
2406 << From->getSourceRange();
2407 }
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002408
John McCalldaa8e4e2010-11-15 09:13:47 +00002409 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002410 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002411 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002412 return ExprError();
John McCalldc05b112011-09-10 01:16:55 +00002413
2414 // Make sure we extend blocks if necessary.
2415 // FIXME: doing this here is really ugly.
2416 if (Kind == CK_BlockPointerToObjCPointerCast) {
2417 ExprResult E = From;
2418 (void) PrepareCastToObjCObjectPointer(E);
2419 From = E.take();
2420 }
2421
Richard Smithc8d7f582011-11-29 22:48:16 +00002422 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2423 .take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002424 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00002425 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002426
Anders Carlsson61faec12009-09-12 04:46:44 +00002427 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002428 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002429 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002430 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002431 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002432 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002433 return ExprError();
Richard Smithc8d7f582011-11-29 22:48:16 +00002434 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2435 .take();
Anders Carlsson61faec12009-09-12 04:46:44 +00002436 break;
2437 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002438
Abramo Bagnara737d5442011-04-07 09:26:19 +00002439 case ICK_Boolean_Conversion:
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00002440 // Perform half-to-boolean conversion via float.
2441 if (From->getType()->isHalfType()) {
2442 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take();
2443 FromType = Context.FloatTy;
2444 }
2445
Richard Smithc8d7f582011-11-29 22:48:16 +00002446 From = ImpCastExprToType(From, Context.BoolTy,
2447 ScalarTypeToBooleanCastKind(FromType),
2448 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002449 break;
2450
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002451 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002452 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002453 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002454 ToType.getNonReferenceType(),
2455 From->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002456 From->getSourceRange(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002457 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002458 CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002459 return ExprError();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002460
Richard Smithc8d7f582011-11-29 22:48:16 +00002461 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2462 CK_DerivedToBase, From->getValueKind(),
2463 &BasePath, CCK).take();
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002464 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002465 }
2466
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002467 case ICK_Vector_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002468 From = ImpCastExprToType(From, ToType, CK_BitCast,
2469 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002470 break;
2471
2472 case ICK_Vector_Splat:
Richard Smithc8d7f582011-11-29 22:48:16 +00002473 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2474 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002475 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002476
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002477 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002478 // Case 1. x -> _Complex y
2479 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2480 QualType ElType = ToComplex->getElementType();
2481 bool isFloatingComplex = ElType->isRealFloatingType();
2482
2483 // x -> y
2484 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2485 // do nothing
2486 } else if (From->getType()->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002487 From = ImpCastExprToType(From, ElType,
2488 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002489 } else {
2490 assert(From->getType()->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002491 From = ImpCastExprToType(From, ElType,
2492 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002493 }
2494 // y -> _Complex y
Richard Smithc8d7f582011-11-29 22:48:16 +00002495 From = ImpCastExprToType(From, ToType,
2496 isFloatingComplex ? CK_FloatingRealToComplex
2497 : CK_IntegralRealToComplex).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002498
2499 // Case 2. _Complex x -> y
2500 } else {
2501 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2502 assert(FromComplex);
2503
2504 QualType ElType = FromComplex->getElementType();
2505 bool isFloatingComplex = ElType->isRealFloatingType();
2506
2507 // _Complex x -> x
Richard Smithc8d7f582011-11-29 22:48:16 +00002508 From = ImpCastExprToType(From, ElType,
2509 isFloatingComplex ? CK_FloatingComplexToReal
2510 : CK_IntegralComplexToReal,
2511 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002512
2513 // x -> y
2514 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2515 // do nothing
2516 } else if (ToType->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002517 From = ImpCastExprToType(From, ToType,
2518 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2519 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002520 } else {
2521 assert(ToType->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002522 From = ImpCastExprToType(From, ToType,
2523 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2524 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002525 }
2526 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002527 break;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002528
2529 case ICK_Block_Pointer_Conversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002530 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2531 VK_RValue, /*BasePath=*/0, CCK).take();
John McCallf85e1932011-06-15 23:02:42 +00002532 break;
2533 }
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002534
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002535 case ICK_TransparentUnionConversion: {
John Wiegley429bb272011-04-08 18:41:53 +00002536 ExprResult FromRes = Owned(From);
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002537 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002538 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2539 if (FromRes.isInvalid())
2540 return ExprError();
2541 From = FromRes.take();
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002542 assert ((ConvTy == Sema::Compatible) &&
2543 "Improper transparent union conversion");
2544 (void)ConvTy;
2545 break;
2546 }
2547
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002548 case ICK_Lvalue_To_Rvalue:
2549 case ICK_Array_To_Pointer:
2550 case ICK_Function_To_Pointer:
2551 case ICK_Qualification:
2552 case ICK_Num_Conversion_Kinds:
David Blaikieb219cfc2011-09-23 05:06:16 +00002553 llvm_unreachable("Improper second standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002554 }
2555
2556 switch (SCS.Third) {
2557 case ICK_Identity:
2558 // Nothing to do.
2559 break;
2560
Sebastian Redl906082e2010-07-20 04:20:21 +00002561 case ICK_Qualification: {
2562 // The qualification keeps the category of the inner expression, unless the
2563 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002564 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002565 From->getValueKind() : VK_RValue;
Richard Smithc8d7f582011-11-29 22:48:16 +00002566 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2567 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
Douglas Gregora9bff302010-02-28 18:30:25 +00002568
Douglas Gregor069a6da2011-03-14 16:13:32 +00002569 if (SCS.DeprecatedStringLiteralToCharPtr &&
2570 !getLangOptions().WritableStrings)
Douglas Gregora9bff302010-02-28 18:30:25 +00002571 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2572 << ToType.getNonReferenceType();
2573
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002574 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002575 }
2576
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002577 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002578 llvm_unreachable("Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002579 }
2580
John Wiegley429bb272011-04-08 18:41:53 +00002581 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002582}
2583
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002584ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002585 SourceLocation KWLoc,
2586 ParsedType Ty,
2587 SourceLocation RParen) {
2588 TypeSourceInfo *TSInfo;
2589 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002590
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002591 if (!TSInfo)
2592 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002593 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002594}
2595
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002596/// \brief Check the completeness of a type in a unary type trait.
2597///
2598/// If the particular type trait requires a complete type, tries to complete
2599/// it. If completing the type fails, a diagnostic is emitted and false
2600/// returned. If completing the type succeeds or no completion was required,
2601/// returns true.
2602static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2603 UnaryTypeTrait UTT,
2604 SourceLocation Loc,
2605 QualType ArgTy) {
2606 // C++0x [meta.unary.prop]p3:
2607 // For all of the class templates X declared in this Clause, instantiating
2608 // that template with a template argument that is a class template
2609 // specialization may result in the implicit instantiation of the template
2610 // argument if and only if the semantics of X require that the argument
2611 // must be a complete type.
2612 // We apply this rule to all the type trait expressions used to implement
2613 // these class templates. We also try to follow any GCC documented behavior
2614 // in these expressions to ensure portability of standard libraries.
2615 switch (UTT) {
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002616 // is_complete_type somewhat obviously cannot require a complete type.
2617 case UTT_IsCompleteType:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002618 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002619
2620 // These traits are modeled on the type predicates in C++0x
2621 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2622 // requiring a complete type, as whether or not they return true cannot be
2623 // impacted by the completeness of the type.
2624 case UTT_IsVoid:
2625 case UTT_IsIntegral:
2626 case UTT_IsFloatingPoint:
2627 case UTT_IsArray:
2628 case UTT_IsPointer:
2629 case UTT_IsLvalueReference:
2630 case UTT_IsRvalueReference:
2631 case UTT_IsMemberFunctionPointer:
2632 case UTT_IsMemberObjectPointer:
2633 case UTT_IsEnum:
2634 case UTT_IsUnion:
2635 case UTT_IsClass:
2636 case UTT_IsFunction:
2637 case UTT_IsReference:
2638 case UTT_IsArithmetic:
2639 case UTT_IsFundamental:
2640 case UTT_IsObject:
2641 case UTT_IsScalar:
2642 case UTT_IsCompound:
2643 case UTT_IsMemberPointer:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002644 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002645
2646 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2647 // which requires some of its traits to have the complete type. However,
2648 // the completeness of the type cannot impact these traits' semantics, and
2649 // so they don't require it. This matches the comments on these traits in
2650 // Table 49.
2651 case UTT_IsConst:
2652 case UTT_IsVolatile:
2653 case UTT_IsSigned:
2654 case UTT_IsUnsigned:
2655 return true;
2656
2657 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002658 // applied to a complete type.
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002659 case UTT_IsTrivial:
Sean Huntfeb375d2011-05-13 00:31:07 +00002660 case UTT_IsTriviallyCopyable:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002661 case UTT_IsStandardLayout:
2662 case UTT_IsPOD:
2663 case UTT_IsLiteral:
2664 case UTT_IsEmpty:
2665 case UTT_IsPolymorphic:
2666 case UTT_IsAbstract:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002667 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002668
Douglas Gregor5e9392b2011-12-03 18:14:24 +00002669 // These traits require a complete type.
2670 case UTT_IsFinal:
2671
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002672 // These trait expressions are designed to help implement predicates in
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002673 // [meta.unary.prop] despite not being named the same. They are specified
2674 // by both GCC and the Embarcadero C++ compiler, and require the complete
2675 // type due to the overarching C++0x type predicates being implemented
2676 // requiring the complete type.
2677 case UTT_HasNothrowAssign:
2678 case UTT_HasNothrowConstructor:
2679 case UTT_HasNothrowCopy:
2680 case UTT_HasTrivialAssign:
Sean Hunt023df372011-05-09 18:22:59 +00002681 case UTT_HasTrivialDefaultConstructor:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002682 case UTT_HasTrivialCopy:
2683 case UTT_HasTrivialDestructor:
2684 case UTT_HasVirtualDestructor:
2685 // Arrays of unknown bound are expressly allowed.
2686 QualType ElTy = ArgTy;
2687 if (ArgTy->isIncompleteArrayType())
2688 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2689
2690 // The void type is expressly allowed.
2691 if (ElTy->isVoidType())
2692 return true;
2693
2694 return !S.RequireCompleteType(
2695 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleycf566412011-04-28 02:06:46 +00002696 }
Chandler Carruth73e0a912011-05-01 07:23:17 +00002697 llvm_unreachable("Type trait not handled by switch");
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002698}
2699
2700static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2701 SourceLocation KeyLoc, QualType T) {
Chandler Carruthd064c702011-05-01 08:41:10 +00002702 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleycf566412011-04-28 02:06:46 +00002703
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002704 ASTContext &C = Self.Context;
2705 switch(UTT) {
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002706 // Type trait expressions corresponding to the primary type category
2707 // predicates in C++0x [meta.unary.cat].
2708 case UTT_IsVoid:
2709 return T->isVoidType();
2710 case UTT_IsIntegral:
2711 return T->isIntegralType(C);
2712 case UTT_IsFloatingPoint:
2713 return T->isFloatingType();
2714 case UTT_IsArray:
2715 return T->isArrayType();
2716 case UTT_IsPointer:
2717 return T->isPointerType();
2718 case UTT_IsLvalueReference:
2719 return T->isLValueReferenceType();
2720 case UTT_IsRvalueReference:
2721 return T->isRValueReferenceType();
2722 case UTT_IsMemberFunctionPointer:
2723 return T->isMemberFunctionPointerType();
2724 case UTT_IsMemberObjectPointer:
2725 return T->isMemberDataPointerType();
2726 case UTT_IsEnum:
2727 return T->isEnumeralType();
Chandler Carruth28eeb382011-05-01 06:11:03 +00002728 case UTT_IsUnion:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002729 return T->isUnionType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002730 case UTT_IsClass:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002731 return T->isClassType() || T->isStructureType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002732 case UTT_IsFunction:
2733 return T->isFunctionType();
2734
2735 // Type trait expressions which correspond to the convenient composition
2736 // predicates in C++0x [meta.unary.comp].
2737 case UTT_IsReference:
2738 return T->isReferenceType();
2739 case UTT_IsArithmetic:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002740 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002741 case UTT_IsFundamental:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002742 return T->isFundamentalType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002743 case UTT_IsObject:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002744 return T->isObjectType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002745 case UTT_IsScalar:
John McCallf85e1932011-06-15 23:02:42 +00002746 // Note: semantic analysis depends on Objective-C lifetime types to be
2747 // considered scalar types. However, such types do not actually behave
2748 // like scalar types at run time (since they may require retain/release
2749 // operations), so we report them as non-scalar.
2750 if (T->isObjCLifetimeType()) {
2751 switch (T.getObjCLifetime()) {
2752 case Qualifiers::OCL_None:
2753 case Qualifiers::OCL_ExplicitNone:
2754 return true;
2755
2756 case Qualifiers::OCL_Strong:
2757 case Qualifiers::OCL_Weak:
2758 case Qualifiers::OCL_Autoreleasing:
2759 return false;
2760 }
2761 }
2762
Chandler Carruthcec0ced2011-05-01 09:29:55 +00002763 return T->isScalarType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002764 case UTT_IsCompound:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002765 return T->isCompoundType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002766 case UTT_IsMemberPointer:
2767 return T->isMemberPointerType();
2768
2769 // Type trait expressions which correspond to the type property predicates
2770 // in C++0x [meta.unary.prop].
2771 case UTT_IsConst:
2772 return T.isConstQualified();
2773 case UTT_IsVolatile:
2774 return T.isVolatileQualified();
2775 case UTT_IsTrivial:
John McCallf85e1932011-06-15 23:02:42 +00002776 return T.isTrivialType(Self.Context);
Sean Huntfeb375d2011-05-13 00:31:07 +00002777 case UTT_IsTriviallyCopyable:
John McCallf85e1932011-06-15 23:02:42 +00002778 return T.isTriviallyCopyableType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002779 case UTT_IsStandardLayout:
2780 return T->isStandardLayoutType();
2781 case UTT_IsPOD:
John McCallf85e1932011-06-15 23:02:42 +00002782 return T.isPODType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002783 case UTT_IsLiteral:
2784 return T->isLiteralType();
2785 case UTT_IsEmpty:
2786 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2787 return !RD->isUnion() && RD->isEmpty();
2788 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002789 case UTT_IsPolymorphic:
Chandler Carruth28eeb382011-05-01 06:11:03 +00002790 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2791 return RD->isPolymorphic();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002792 return false;
2793 case UTT_IsAbstract:
Chandler Carruth28eeb382011-05-01 06:11:03 +00002794 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2795 return RD->isAbstract();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002796 return false;
Douglas Gregor5e9392b2011-12-03 18:14:24 +00002797 case UTT_IsFinal:
2798 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2799 return RD->hasAttr<FinalAttr>();
2800 return false;
John Wiegley20c0da72011-04-27 23:09:49 +00002801 case UTT_IsSigned:
2802 return T->isSignedIntegerType();
John Wiegley20c0da72011-04-27 23:09:49 +00002803 case UTT_IsUnsigned:
2804 return T->isUnsignedIntegerType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002805
2806 // Type trait expressions which query classes regarding their construction,
2807 // destruction, and copying. Rather than being based directly on the
2808 // related type predicates in the standard, they are specified by both
2809 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
2810 // specifications.
2811 //
2812 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
2813 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Sean Hunt023df372011-05-09 18:22:59 +00002814 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002815 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2816 // If __is_pod (type) is true then the trait is true, else if type is
2817 // a cv class or union type (or array thereof) with a trivial default
2818 // constructor ([class.ctor]) then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002819 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002820 return true;
2821 if (const RecordType *RT =
2822 C.getBaseElementType(T)->getAs<RecordType>())
Sean Hunt023df372011-05-09 18:22:59 +00002823 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002824 return false;
2825 case UTT_HasTrivialCopy:
2826 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2827 // If __is_pod (type) is true or type is a reference type then
2828 // the trait is true, else if type is a cv class or union type
2829 // with a trivial copy constructor ([class.copy]) then the trait
2830 // is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002831 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002832 return true;
2833 if (const RecordType *RT = T->getAs<RecordType>())
2834 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2835 return false;
2836 case UTT_HasTrivialAssign:
2837 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2838 // If type is const qualified or is a reference type then the
2839 // trait is false. Otherwise if __is_pod (type) is true then the
2840 // trait is true, else if type is a cv class or union type with
2841 // a trivial copy assignment ([class.copy]) then the trait is
2842 // true, else it is false.
2843 // Note: the const and reference restrictions are interesting,
2844 // given that const and reference members don't prevent a class
2845 // from having a trivial copy assignment operator (but do cause
2846 // errors if the copy assignment operator is actually used, q.v.
2847 // [class.copy]p12).
2848
2849 if (C.getBaseElementType(T).isConstQualified())
2850 return false;
John McCallf85e1932011-06-15 23:02:42 +00002851 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002852 return true;
2853 if (const RecordType *RT = T->getAs<RecordType>())
2854 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2855 return false;
2856 case UTT_HasTrivialDestructor:
2857 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2858 // If __is_pod (type) is true or type is a reference type
2859 // then the trait is true, else if type is a cv class or union
2860 // type (or array thereof) with a trivial destructor
2861 // ([class.dtor]) then the trait is true, else it is
2862 // false.
John McCallf85e1932011-06-15 23:02:42 +00002863 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002864 return true;
John McCallf85e1932011-06-15 23:02:42 +00002865
2866 // Objective-C++ ARC: autorelease types don't require destruction.
2867 if (T->isObjCLifetimeType() &&
2868 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
2869 return true;
2870
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002871 if (const RecordType *RT =
2872 C.getBaseElementType(T)->getAs<RecordType>())
2873 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2874 return false;
2875 // TODO: Propagate nothrowness for implicitly declared special members.
2876 case UTT_HasNothrowAssign:
2877 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2878 // If type is const qualified or is a reference type then the
2879 // trait is false. Otherwise if __has_trivial_assign (type)
2880 // is true then the trait is true, else if type is a cv class
2881 // or union type with copy assignment operators that are known
2882 // not to throw an exception then the trait is true, else it is
2883 // false.
2884 if (C.getBaseElementType(T).isConstQualified())
2885 return false;
2886 if (T->isReferenceType())
2887 return false;
John McCallf85e1932011-06-15 23:02:42 +00002888 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
2889 return true;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002890 if (const RecordType *RT = T->getAs<RecordType>()) {
2891 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2892 if (RD->hasTrivialCopyAssignment())
2893 return true;
2894
2895 bool FoundAssign = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002896 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00002897 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2898 Sema::LookupOrdinaryName);
2899 if (Self.LookupQualifiedName(Res, RD)) {
Douglas Gregord41679d2011-10-12 15:40:49 +00002900 Res.suppressDiagnostics();
Sebastian Redlf8aca862010-09-14 23:40:14 +00002901 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2902 Op != OpEnd; ++Op) {
Douglas Gregord41679d2011-10-12 15:40:49 +00002903 if (isa<FunctionTemplateDecl>(*Op))
2904 continue;
2905
Sebastian Redlf8aca862010-09-14 23:40:14 +00002906 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2907 if (Operator->isCopyAssignmentOperator()) {
2908 FoundAssign = true;
2909 const FunctionProtoType *CPT
2910 = Operator->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00002911 if (CPT->getExceptionSpecType() == EST_Delayed)
2912 return false;
2913 if (!CPT->isNothrow(Self.Context))
2914 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002915 }
2916 }
2917 }
Douglas Gregord41679d2011-10-12 15:40:49 +00002918
Richard Smith7a614d82011-06-11 17:19:42 +00002919 return FoundAssign;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002920 }
2921 return false;
2922 case UTT_HasNothrowCopy:
2923 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2924 // If __has_trivial_copy (type) is true then the trait is true, else
2925 // if type is a cv class or union type with copy constructors that are
2926 // known not to throw an exception then the trait is true, else it is
2927 // false.
John McCallf85e1932011-06-15 23:02:42 +00002928 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002929 return true;
2930 if (const RecordType *RT = T->getAs<RecordType>()) {
2931 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2932 if (RD->hasTrivialCopyConstructor())
2933 return true;
2934
2935 bool FoundConstructor = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002936 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002937 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00002938 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002939 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002940 // A template constructor is never a copy constructor.
2941 // FIXME: However, it may actually be selected at the actual overload
2942 // resolution point.
2943 if (isa<FunctionTemplateDecl>(*Con))
2944 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002945 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2946 if (Constructor->isCopyConstructor(FoundTQs)) {
2947 FoundConstructor = true;
2948 const FunctionProtoType *CPT
2949 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00002950 if (CPT->getExceptionSpecType() == EST_Delayed)
2951 return false;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002952 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redl751025d2010-09-13 22:02:47 +00002953 // For now, we'll be conservative and assume that they can throw.
Richard Smith7a614d82011-06-11 17:19:42 +00002954 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
2955 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002956 }
2957 }
2958
Richard Smith7a614d82011-06-11 17:19:42 +00002959 return FoundConstructor;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002960 }
2961 return false;
2962 case UTT_HasNothrowConstructor:
2963 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2964 // If __has_trivial_constructor (type) is true then the trait is
2965 // true, else if type is a cv class or union type (or array
2966 // thereof) with a default constructor that is known not to
2967 // throw an exception then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002968 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002969 return true;
2970 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2971 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Hunt023df372011-05-09 18:22:59 +00002972 if (RD->hasTrivialDefaultConstructor())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002973 return true;
2974
Sebastian Redl751025d2010-09-13 22:02:47 +00002975 DeclContext::lookup_const_iterator Con, ConEnd;
2976 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2977 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002978 // FIXME: In C++0x, a constructor template can be a default constructor.
2979 if (isa<FunctionTemplateDecl>(*Con))
2980 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00002981 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2982 if (Constructor->isDefaultConstructor()) {
2983 const FunctionProtoType *CPT
2984 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00002985 if (CPT->getExceptionSpecType() == EST_Delayed)
2986 return false;
Sebastian Redl751025d2010-09-13 22:02:47 +00002987 // TODO: check whether evaluating default arguments can throw.
2988 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002989 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
Sebastian Redl751025d2010-09-13 22:02:47 +00002990 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002991 }
2992 }
2993 return false;
2994 case UTT_HasVirtualDestructor:
2995 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2996 // If type is a class type with a virtual destructor ([class.dtor])
2997 // then the trait is true, else it is false.
2998 if (const RecordType *Record = T->getAs<RecordType>()) {
2999 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00003000 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003001 return Destructor->isVirtual();
3002 }
3003 return false;
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003004
3005 // These type trait expressions are modeled on the specifications for the
3006 // Embarcadero C++0x type trait functions:
3007 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3008 case UTT_IsCompleteType:
3009 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3010 // Returns True if and only if T is a complete type at the point of the
3011 // function call.
3012 return !T->isIncompleteType();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003013 }
Chandler Carruth83f563c2011-05-01 07:44:17 +00003014 llvm_unreachable("Type trait not covered by switch");
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003015}
3016
3017ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00003018 SourceLocation KWLoc,
3019 TypeSourceInfo *TSInfo,
3020 SourceLocation RParen) {
3021 QualType T = TSInfo->getType();
Chandler Carrutheb65a102011-04-30 10:07:32 +00003022 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
3023 return ExprError();
Sebastian Redl64b45f72009-01-05 20:52:13 +00003024
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003025 bool Value = false;
3026 if (!T->isDependentType())
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00003027 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003028
3029 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00003030 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00003031}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003032
Francois Pichet6ad6f282010-12-07 00:08:36 +00003033ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
3034 SourceLocation KWLoc,
3035 ParsedType LhsTy,
3036 ParsedType RhsTy,
3037 SourceLocation RParen) {
3038 TypeSourceInfo *LhsTSInfo;
3039 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3040 if (!LhsTSInfo)
3041 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3042
3043 TypeSourceInfo *RhsTSInfo;
3044 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3045 if (!RhsTSInfo)
3046 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3047
3048 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3049}
3050
3051static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3052 QualType LhsT, QualType RhsT,
3053 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003054 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3055 "Cannot evaluate traits of dependent types");
Francois Pichet6ad6f282010-12-07 00:08:36 +00003056
3057 switch(BTT) {
John McCalld89d30f2011-01-28 22:02:36 +00003058 case BTT_IsBaseOf: {
Francois Pichet6ad6f282010-12-07 00:08:36 +00003059 // C++0x [meta.rel]p2
John McCalld89d30f2011-01-28 22:02:36 +00003060 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet6ad6f282010-12-07 00:08:36 +00003061 // Base and Derived are not unions and name the same class type without
3062 // regard to cv-qualifiers.
Francois Pichet6ad6f282010-12-07 00:08:36 +00003063
John McCalld89d30f2011-01-28 22:02:36 +00003064 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3065 if (!lhsRecord) return false;
3066
3067 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3068 if (!rhsRecord) return false;
3069
3070 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3071 == (lhsRecord == rhsRecord));
3072
3073 if (lhsRecord == rhsRecord)
3074 return !lhsRecord->getDecl()->isUnion();
3075
3076 // C++0x [meta.rel]p2:
3077 // If Base and Derived are class types and are different types
3078 // (ignoring possible cv-qualifiers) then Derived shall be a
3079 // complete type.
3080 if (Self.RequireCompleteType(KeyLoc, RhsT,
3081 diag::err_incomplete_type_used_in_type_trait_expr))
3082 return false;
3083
3084 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3085 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3086 }
John Wiegley20c0da72011-04-27 23:09:49 +00003087 case BTT_IsSame:
3088 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichetf1872372010-12-08 22:35:30 +00003089 case BTT_TypeCompatible:
3090 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3091 RhsT.getUnqualifiedType());
John Wiegley20c0da72011-04-27 23:09:49 +00003092 case BTT_IsConvertible:
Douglas Gregor9f361132011-01-27 20:28:01 +00003093 case BTT_IsConvertibleTo: {
3094 // C++0x [meta.rel]p4:
3095 // Given the following function prototype:
3096 //
3097 // template <class T>
3098 // typename add_rvalue_reference<T>::type create();
3099 //
3100 // the predicate condition for a template specialization
3101 // is_convertible<From, To> shall be satisfied if and only if
3102 // the return expression in the following code would be
3103 // well-formed, including any implicit conversions to the return
3104 // type of the function:
3105 //
3106 // To test() {
3107 // return create<From>();
3108 // }
3109 //
3110 // Access checking is performed as if in a context unrelated to To and
3111 // From. Only the validity of the immediate context of the expression
3112 // of the return-statement (including conversions to the return type)
3113 // is considered.
3114 //
3115 // We model the initialization as a copy-initialization of a temporary
3116 // of the appropriate type, which for this expression is identical to the
3117 // return statement (since NRVO doesn't apply).
3118 if (LhsT->isObjectType() || LhsT->isFunctionType())
3119 LhsT = Self.Context.getRValueReferenceType(LhsT);
3120
3121 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorb608b982011-01-28 02:26:04 +00003122 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor9f361132011-01-27 20:28:01 +00003123 Expr::getValueKindForType(LhsT));
3124 Expr *FromPtr = &From;
3125 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3126 SourceLocation()));
3127
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003128 // Perform the initialization within a SFINAE trap at translation unit
3129 // scope.
3130 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3131 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor9f361132011-01-27 20:28:01 +00003132 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003133 if (Init.Failed())
Douglas Gregor9f361132011-01-27 20:28:01 +00003134 return false;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003135
Douglas Gregor9f361132011-01-27 20:28:01 +00003136 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
3137 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3138 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003139 }
3140 llvm_unreachable("Unknown type trait or not implemented");
3141}
3142
3143ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3144 SourceLocation KWLoc,
3145 TypeSourceInfo *LhsTSInfo,
3146 TypeSourceInfo *RhsTSInfo,
3147 SourceLocation RParen) {
3148 QualType LhsT = LhsTSInfo->getType();
3149 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003150
John McCalld89d30f2011-01-28 22:02:36 +00003151 if (BTT == BTT_TypeCompatible) {
Francois Pichetf1872372010-12-08 22:35:30 +00003152 if (getLangOptions().CPlusPlus) {
3153 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3154 << SourceRange(KWLoc, RParen);
3155 return ExprError();
3156 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003157 }
3158
3159 bool Value = false;
3160 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3161 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3162
Francois Pichetf1872372010-12-08 22:35:30 +00003163 // Select trait result type.
3164 QualType ResultType;
3165 switch (BTT) {
Francois Pichetf1872372010-12-08 22:35:30 +00003166 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
John Wiegley20c0da72011-04-27 23:09:49 +00003167 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3168 case BTT_IsSame: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003169 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor9f361132011-01-27 20:28:01 +00003170 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003171 }
3172
Francois Pichet6ad6f282010-12-07 00:08:36 +00003173 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3174 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00003175 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00003176}
3177
John Wiegley21ff2e52011-04-28 00:16:57 +00003178ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3179 SourceLocation KWLoc,
3180 ParsedType Ty,
3181 Expr* DimExpr,
3182 SourceLocation RParen) {
3183 TypeSourceInfo *TSInfo;
3184 QualType T = GetTypeFromParser(Ty, &TSInfo);
3185 if (!TSInfo)
3186 TSInfo = Context.getTrivialTypeSourceInfo(T);
3187
3188 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3189}
3190
3191static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3192 QualType T, Expr *DimExpr,
3193 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003194 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley21ff2e52011-04-28 00:16:57 +00003195
3196 switch(ATT) {
3197 case ATT_ArrayRank:
3198 if (T->isArrayType()) {
3199 unsigned Dim = 0;
3200 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3201 ++Dim;
3202 T = AT->getElementType();
3203 }
3204 return Dim;
John Wiegley21ff2e52011-04-28 00:16:57 +00003205 }
John Wiegleycf566412011-04-28 02:06:46 +00003206 return 0;
3207
John Wiegley21ff2e52011-04-28 00:16:57 +00003208 case ATT_ArrayExtent: {
3209 llvm::APSInt Value;
3210 uint64_t Dim;
John Wiegleycf566412011-04-28 02:06:46 +00003211 if (DimExpr->isIntegerConstantExpr(Value, Self.Context, 0, false)) {
3212 if (Value < llvm::APSInt(Value.getBitWidth(), Value.isUnsigned())) {
3213 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3214 DimExpr->getSourceRange();
3215 return false;
3216 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003217 Dim = Value.getLimitedValue();
John Wiegleycf566412011-04-28 02:06:46 +00003218 } else {
3219 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3220 DimExpr->getSourceRange();
3221 return false;
3222 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003223
3224 if (T->isArrayType()) {
3225 unsigned D = 0;
3226 bool Matched = false;
3227 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3228 if (Dim == D) {
3229 Matched = true;
3230 break;
3231 }
3232 ++D;
3233 T = AT->getElementType();
3234 }
3235
John Wiegleycf566412011-04-28 02:06:46 +00003236 if (Matched && T->isArrayType()) {
3237 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3238 return CAT->getSize().getLimitedValue();
3239 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003240 }
John Wiegleycf566412011-04-28 02:06:46 +00003241 return 0;
John Wiegley21ff2e52011-04-28 00:16:57 +00003242 }
3243 }
3244 llvm_unreachable("Unknown type trait or not implemented");
3245}
3246
3247ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3248 SourceLocation KWLoc,
3249 TypeSourceInfo *TSInfo,
3250 Expr* DimExpr,
3251 SourceLocation RParen) {
3252 QualType T = TSInfo->getType();
John Wiegley21ff2e52011-04-28 00:16:57 +00003253
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003254 // FIXME: This should likely be tracked as an APInt to remove any host
3255 // assumptions about the width of size_t on the target.
Chandler Carruthd064c702011-05-01 08:41:10 +00003256 uint64_t Value = 0;
3257 if (!T->isDependentType())
3258 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3259
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003260 // While the specification for these traits from the Embarcadero C++
3261 // compiler's documentation says the return type is 'unsigned int', Clang
3262 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3263 // compiler, there is no difference. On several other platforms this is an
3264 // important distinction.
John Wiegley21ff2e52011-04-28 00:16:57 +00003265 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
Chandler Carruth06207f62011-05-01 07:49:26 +00003266 DimExpr, RParen,
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003267 Context.getSizeType()));
John Wiegley21ff2e52011-04-28 00:16:57 +00003268}
3269
John Wiegley55262202011-04-25 06:54:41 +00003270ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003271 SourceLocation KWLoc,
3272 Expr *Queried,
3273 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003274 // If error parsing the expression, ignore.
3275 if (!Queried)
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003276 return ExprError();
John Wiegley55262202011-04-25 06:54:41 +00003277
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003278 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegley55262202011-04-25 06:54:41 +00003279
3280 return move(Result);
3281}
3282
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003283static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3284 switch (ET) {
3285 case ET_IsLValueExpr: return E->isLValue();
3286 case ET_IsRValueExpr: return E->isRValue();
3287 }
3288 llvm_unreachable("Expression trait not covered by switch");
3289}
3290
John Wiegley55262202011-04-25 06:54:41 +00003291ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003292 SourceLocation KWLoc,
3293 Expr *Queried,
3294 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003295 if (Queried->isTypeDependent()) {
3296 // Delay type-checking for type-dependent expressions.
3297 } else if (Queried->getType()->isPlaceholderType()) {
3298 ExprResult PE = CheckPlaceholderExpr(Queried);
3299 if (PE.isInvalid()) return ExprError();
3300 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3301 }
3302
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003303 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf7ef0002011-05-01 08:48:19 +00003304
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003305 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3306 RParen, Context.BoolTy));
John Wiegley55262202011-04-25 06:54:41 +00003307}
3308
Richard Trieudd225092011-09-15 21:56:47 +00003309QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCallf89e55a2010-11-18 06:31:45 +00003310 ExprValueKind &VK,
3311 SourceLocation Loc,
3312 bool isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003313 assert(!LHS.get()->getType()->isPlaceholderType() &&
3314 !RHS.get()->getType()->isPlaceholderType() &&
John McCallea4aba02011-06-30 17:15:34 +00003315 "placeholders should have been weeded out by now");
3316
3317 // The LHS undergoes lvalue conversions if this is ->*.
3318 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003319 LHS = DefaultLvalueConversion(LHS.take());
3320 if (LHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003321 }
3322
3323 // The RHS always undergoes lvalue conversions.
Richard Trieudd225092011-09-15 21:56:47 +00003324 RHS = DefaultLvalueConversion(RHS.take());
3325 if (RHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003326
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003327 const char *OpSpelling = isIndirect ? "->*" : ".*";
3328 // C++ 5.5p2
3329 // The binary operator .* [p3: ->*] binds its second operand, which shall
3330 // be of type "pointer to member of T" (where T is a completely-defined
3331 // class type) [...]
Richard Trieudd225092011-09-15 21:56:47 +00003332 QualType RHSType = RHS.get()->getType();
3333 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00003334 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003335 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieudd225092011-09-15 21:56:47 +00003336 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003337 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00003338 }
Douglas Gregore7450f52009-03-24 19:52:54 +00003339
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003340 QualType Class(MemPtr->getClass(), 0);
3341
Douglas Gregor7d520ba2010-10-13 20:41:14 +00003342 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3343 // member pointer points must be completely-defined. However, there is no
3344 // reason for this semantic distinction, and the rule is not enforced by
3345 // other compilers. Therefore, we do not check this property, as it is
3346 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00003347
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003348 // C++ 5.5p2
3349 // [...] to its first operand, which shall be of class T or of a class of
3350 // which T is an unambiguous and accessible base class. [p3: a pointer to
3351 // such a class]
Richard Trieudd225092011-09-15 21:56:47 +00003352 QualType LHSType = LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003353 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003354 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
3355 LHSType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003356 else {
3357 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieudd225092011-09-15 21:56:47 +00003358 << OpSpelling << 1 << LHSType
Douglas Gregor849b2432010-03-31 17:46:05 +00003359 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003360 return QualType();
3361 }
3362 }
3363
Richard Trieudd225092011-09-15 21:56:47 +00003364 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00003365 // If we want to check the hierarchy, we need a complete type.
Richard Trieudd225092011-09-15 21:56:47 +00003366 if (RequireCompleteType(Loc, LHSType, PDiag(diag::err_bad_memptr_lhs)
Sebastian Redl17e1d352010-04-23 17:18:26 +00003367 << OpSpelling << (int)isIndirect)) {
3368 return QualType();
3369 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003370 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00003371 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00003372 // FIXME: Would it be useful to print full ambiguity paths, or is that
3373 // overkill?
Richard Trieudd225092011-09-15 21:56:47 +00003374 if (!IsDerivedFrom(LHSType, Class, Paths) ||
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003375 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3376 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieudd225092011-09-15 21:56:47 +00003377 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003378 return QualType();
3379 }
Eli Friedman3005efe2010-01-16 00:00:48 +00003380 // Cast LHS to type of use.
3381 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00003382 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00003383
John McCallf871d0c2010-08-07 06:22:56 +00003384 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003385 BuildBasePathArray(Paths, BasePath);
Richard Trieudd225092011-09-15 21:56:47 +00003386 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
3387 &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003388 }
3389
Richard Trieudd225092011-09-15 21:56:47 +00003390 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00003391 // Diagnose use of pointer-to-member type which when used as
3392 // the functional cast in a pointer-to-member expression.
3393 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3394 return QualType();
3395 }
John McCallf89e55a2010-11-18 06:31:45 +00003396
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003397 // C++ 5.5p2
3398 // The result is an object or a function of the type specified by the
3399 // second operand.
3400 // The cv qualifiers are the union of those in the pointer and the left side,
3401 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003402 QualType Result = MemPtr->getPointeeType();
Richard Trieudd225092011-09-15 21:56:47 +00003403 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00003404
Douglas Gregor6b4df912011-01-26 16:40:18 +00003405 // C++0x [expr.mptr.oper]p6:
3406 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003407 // ill-formed if the second operand is a pointer to member function with
3408 // ref-qualifier &. In a ->* expression or in a .* expression whose object
3409 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor6b4df912011-01-26 16:40:18 +00003410 // is a pointer to member function with ref-qualifier &&.
3411 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3412 switch (Proto->getRefQualifier()) {
3413 case RQ_None:
3414 // Do nothing
3415 break;
3416
3417 case RQ_LValue:
Richard Trieudd225092011-09-15 21:56:47 +00003418 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003419 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003420 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003421 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003422
Douglas Gregor6b4df912011-01-26 16:40:18 +00003423 case RQ_RValue:
Richard Trieudd225092011-09-15 21:56:47 +00003424 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003425 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003426 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003427 break;
3428 }
3429 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003430
John McCallf89e55a2010-11-18 06:31:45 +00003431 // C++ [expr.mptr.oper]p6:
3432 // The result of a .* expression whose second operand is a pointer
3433 // to a data member is of the same value category as its
3434 // first operand. The result of a .* expression whose second
3435 // operand is a pointer to a member function is a prvalue. The
3436 // result of an ->* expression is an lvalue if its second operand
3437 // is a pointer to data member and a prvalue otherwise.
John McCall864c0412011-04-26 20:42:42 +00003438 if (Result->isFunctionType()) {
John McCallf89e55a2010-11-18 06:31:45 +00003439 VK = VK_RValue;
John McCall864c0412011-04-26 20:42:42 +00003440 return Context.BoundMemberTy;
3441 } else if (isIndirect) {
John McCallf89e55a2010-11-18 06:31:45 +00003442 VK = VK_LValue;
John McCall864c0412011-04-26 20:42:42 +00003443 } else {
Richard Trieudd225092011-09-15 21:56:47 +00003444 VK = LHS.get()->getValueKind();
John McCall864c0412011-04-26 20:42:42 +00003445 }
John McCallf89e55a2010-11-18 06:31:45 +00003446
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003447 return Result;
3448}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003449
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003450/// \brief Try to convert a type to another according to C++0x 5.16p3.
3451///
3452/// This is part of the parameter validation for the ? operator. If either
3453/// value operand is a class type, the two operands are attempted to be
3454/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003455/// It returns true if the program is ill-formed and has already been diagnosed
3456/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003457static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3458 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00003459 bool &HaveConversion,
3460 QualType &ToType) {
3461 HaveConversion = false;
3462 ToType = To->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003463
3464 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003465 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003466 // C++0x 5.16p3
3467 // The process for determining whether an operand expression E1 of type T1
3468 // can be converted to match an operand expression E2 of type T2 is defined
3469 // as follows:
3470 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00003471 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003472 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003473 // E1 can be converted to match E2 if E1 can be implicitly converted to
3474 // type "lvalue reference to T2", subject to the constraint that in the
3475 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003476 QualType T = Self.Context.getLValueReferenceType(ToType);
3477 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003478
Douglas Gregorb70cf442010-03-26 20:14:36 +00003479 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3480 if (InitSeq.isDirectReferenceBinding()) {
3481 ToType = T;
3482 HaveConversion = true;
3483 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003484 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003485
Douglas Gregorb70cf442010-03-26 20:14:36 +00003486 if (InitSeq.isAmbiguous())
3487 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003488 }
John McCallb1bdc622010-02-25 01:37:24 +00003489
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003490 // -- If E2 is an rvalue, or if the conversion above cannot be done:
3491 // -- if E1 and E2 have class type, and the underlying class types are
3492 // the same or one is a base class of the other:
3493 QualType FTy = From->getType();
3494 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003495 const RecordType *FRec = FTy->getAs<RecordType>();
3496 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003497 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003498 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003499 if (FRec && TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003500 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003501 // E1 can be converted to match E2 if the class of T2 is the
3502 // same type as, or a base class of, the class of T1, and
3503 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00003504 if (FRec == TRec || FDerivedFromT) {
3505 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003506 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3507 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003508 if (InitSeq) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003509 HaveConversion = true;
3510 return false;
3511 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003512
Douglas Gregorb70cf442010-03-26 20:14:36 +00003513 if (InitSeq.isAmbiguous())
3514 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003515 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003516 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003517
Douglas Gregorb70cf442010-03-26 20:14:36 +00003518 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003519 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003520
Douglas Gregorb70cf442010-03-26 20:14:36 +00003521 // -- Otherwise: E1 can be converted to match E2 if E1 can be
3522 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003523 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003524 // an rvalue).
3525 //
3526 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3527 // to the array-to-pointer or function-to-pointer conversions.
3528 if (!TTy->getAs<TagType>())
3529 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003530
Douglas Gregorb70cf442010-03-26 20:14:36 +00003531 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3532 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003533 HaveConversion = !InitSeq.Failed();
Douglas Gregorb70cf442010-03-26 20:14:36 +00003534 ToType = TTy;
3535 if (InitSeq.isAmbiguous())
3536 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3537
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003538 return false;
3539}
3540
3541/// \brief Try to find a common type for two according to C++0x 5.16p5.
3542///
3543/// This is part of the parameter validation for the ? operator. If either
3544/// value operand is a class type, overload resolution is used to find a
3545/// conversion to a common type.
John Wiegley429bb272011-04-08 18:41:53 +00003546static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth82214a82011-02-18 23:54:50 +00003547 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00003548 Expr *Args[2] = { LHS.get(), RHS.get() };
Chandler Carruth82214a82011-02-18 23:54:50 +00003549 OverloadCandidateSet CandidateSet(QuestionLoc);
3550 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3551 CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003552
3553 OverloadCandidateSet::iterator Best;
Chandler Carruth82214a82011-02-18 23:54:50 +00003554 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley429bb272011-04-08 18:41:53 +00003555 case OR_Success: {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003556 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley429bb272011-04-08 18:41:53 +00003557 ExprResult LHSRes =
3558 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3559 Best->Conversions[0], Sema::AA_Converting);
3560 if (LHSRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003561 break;
John Wiegley429bb272011-04-08 18:41:53 +00003562 LHS = move(LHSRes);
3563
3564 ExprResult RHSRes =
3565 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3566 Best->Conversions[1], Sema::AA_Converting);
3567 if (RHSRes.isInvalid())
3568 break;
3569 RHS = move(RHSRes);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003570 if (Best->Function)
3571 Self.MarkDeclarationReferenced(QuestionLoc, Best->Function);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003572 return false;
John Wiegley429bb272011-04-08 18:41:53 +00003573 }
3574
Douglas Gregor20093b42009-12-09 23:02:17 +00003575 case OR_No_Viable_Function:
Chandler Carruth82214a82011-02-18 23:54:50 +00003576
3577 // Emit a better diagnostic if one of the expressions is a null pointer
3578 // constant and the other is a pointer type. In this case, the user most
3579 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00003580 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00003581 return true;
3582
3583 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003584 << LHS.get()->getType() << RHS.get()->getType()
3585 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003586 return true;
3587
Douglas Gregor20093b42009-12-09 23:02:17 +00003588 case OR_Ambiguous:
Chandler Carruth82214a82011-02-18 23:54:50 +00003589 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley429bb272011-04-08 18:41:53 +00003590 << LHS.get()->getType() << RHS.get()->getType()
3591 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00003592 // FIXME: Print the possible common types by printing the return types of
3593 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003594 break;
3595
Douglas Gregor20093b42009-12-09 23:02:17 +00003596 case OR_Deleted:
David Blaikieb219cfc2011-09-23 05:06:16 +00003597 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003598 }
3599 return true;
3600}
3601
Sebastian Redl76458502009-04-17 16:30:52 +00003602/// \brief Perform an "extended" implicit conversion as returned by
3603/// TryClassUnification.
John Wiegley429bb272011-04-08 18:41:53 +00003604static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003605 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley429bb272011-04-08 18:41:53 +00003606 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003607 SourceLocation());
John Wiegley429bb272011-04-08 18:41:53 +00003608 Expr *Arg = E.take();
3609 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
3610 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00003611 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00003612 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003613
John Wiegley429bb272011-04-08 18:41:53 +00003614 E = Result;
Sebastian Redl76458502009-04-17 16:30:52 +00003615 return false;
3616}
3617
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003618/// \brief Check the operands of ?: under C++ semantics.
3619///
3620/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
3621/// extension. In this case, LHS == Cond. (But they're not aliases.)
John Wiegley429bb272011-04-08 18:41:53 +00003622QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCall56ca35d2011-02-17 10:25:35 +00003623 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003624 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00003625 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
3626 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003627
3628 // C++0x 5.16p1
3629 // The first expression is contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00003630 if (!Cond.get()->isTypeDependent()) {
3631 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
3632 if (CondRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003633 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003634 Cond = move(CondRes);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003635 }
3636
John McCallf89e55a2010-11-18 06:31:45 +00003637 // Assume r-value.
3638 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00003639 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00003640
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003641 // Either of the arguments dependent?
John Wiegley429bb272011-04-08 18:41:53 +00003642 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003643 return Context.DependentTy;
3644
3645 // C++0x 5.16p2
3646 // If either the second or the third operand has type (cv) void, ...
John Wiegley429bb272011-04-08 18:41:53 +00003647 QualType LTy = LHS.get()->getType();
3648 QualType RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003649 bool LVoid = LTy->isVoidType();
3650 bool RVoid = RTy->isVoidType();
3651 if (LVoid || RVoid) {
3652 // ... then the [l2r] conversions are performed on the second and third
3653 // operands ...
John Wiegley429bb272011-04-08 18:41:53 +00003654 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3655 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3656 if (LHS.isInvalid() || RHS.isInvalid())
3657 return QualType();
3658 LTy = LHS.get()->getType();
3659 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003660
3661 // ... and one of the following shall hold:
3662 // -- The second or the third operand (but not both) is a throw-
3663 // expression; the result is of the type of the other and is an rvalue.
John Wiegley429bb272011-04-08 18:41:53 +00003664 bool LThrow = isa<CXXThrowExpr>(LHS.get());
3665 bool RThrow = isa<CXXThrowExpr>(RHS.get());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003666 if (LThrow && !RThrow)
3667 return RTy;
3668 if (RThrow && !LThrow)
3669 return LTy;
3670
3671 // -- Both the second and third operands have type void; the result is of
3672 // type void and is an rvalue.
3673 if (LVoid && RVoid)
3674 return Context.VoidTy;
3675
3676 // Neither holds, error.
3677 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3678 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley429bb272011-04-08 18:41:53 +00003679 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003680 return QualType();
3681 }
3682
3683 // Neither is void.
3684
3685 // C++0x 5.16p3
3686 // Otherwise, if the second and third operand have different types, and
3687 // either has (cv) class type, and attempt is made to convert each of those
3688 // operands to the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003689 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003690 (LTy->isRecordType() || RTy->isRecordType())) {
3691 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3692 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003693 QualType L2RType, R2LType;
3694 bool HaveL2R, HaveR2L;
John Wiegley429bb272011-04-08 18:41:53 +00003695 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003696 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003697 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003698 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003699
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003700 // If both can be converted, [...] the program is ill-formed.
3701 if (HaveL2R && HaveR2L) {
3702 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley429bb272011-04-08 18:41:53 +00003703 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003704 return QualType();
3705 }
3706
3707 // If exactly one conversion is possible, that conversion is applied to
3708 // the chosen operand and the converted operands are used in place of the
3709 // original operands for the remainder of this section.
3710 if (HaveL2R) {
John Wiegley429bb272011-04-08 18:41:53 +00003711 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003712 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003713 LTy = LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003714 } else if (HaveR2L) {
John Wiegley429bb272011-04-08 18:41:53 +00003715 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003716 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003717 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003718 }
3719 }
3720
3721 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00003722 // If the second and third operands are glvalues of the same value
3723 // category and have the same type, the result is of that type and
3724 // value category and it is a bit-field if the second or the third
3725 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00003726 // We only extend this to bitfields, not to the crazy other kinds of
3727 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003728 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00003729 if (Same &&
John Wiegley429bb272011-04-08 18:41:53 +00003730 LHS.get()->isGLValue() &&
3731 LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
3732 LHS.get()->isOrdinaryOrBitFieldObject() &&
3733 RHS.get()->isOrdinaryOrBitFieldObject()) {
3734 VK = LHS.get()->getValueKind();
3735 if (LHS.get()->getObjectKind() == OK_BitField ||
3736 RHS.get()->getObjectKind() == OK_BitField)
John McCall09431682010-11-18 19:01:18 +00003737 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00003738 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00003739 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003740
3741 // C++0x 5.16p5
3742 // Otherwise, the result is an rvalue. If the second and third operands
3743 // do not have the same type, and either has (cv) class type, ...
3744 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3745 // ... overload resolution is used to determine the conversions (if any)
3746 // to be applied to the operands. If the overload resolution fails, the
3747 // program is ill-formed.
3748 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3749 return QualType();
3750 }
3751
3752 // C++0x 5.16p6
3753 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3754 // conversions are performed on the second and third operands.
John Wiegley429bb272011-04-08 18:41:53 +00003755 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3756 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3757 if (LHS.isInvalid() || RHS.isInvalid())
3758 return QualType();
3759 LTy = LHS.get()->getType();
3760 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003761
3762 // After those conversions, one of the following shall hold:
3763 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00003764 // is of that type. If the operands have class type, the result
3765 // is a prvalue temporary of the result type, which is
3766 // copy-initialized from either the second operand or the third
3767 // operand depending on the value of the first operand.
3768 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3769 if (LTy->isRecordType()) {
3770 // The operands have class type. Make a temporary copy.
3771 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003772 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3773 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00003774 LHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00003775 if (LHSCopy.isInvalid())
3776 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003777
3778 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3779 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00003780 RHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00003781 if (RHSCopy.isInvalid())
3782 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003783
John Wiegley429bb272011-04-08 18:41:53 +00003784 LHS = LHSCopy;
3785 RHS = RHSCopy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003786 }
3787
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003788 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003789 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003790
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003791 // Extension: conditional operator involving vector types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003792 if (LTy->isVectorType() || RTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00003793 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003794
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003795 // -- The second and third operands have arithmetic or enumeration type;
3796 // the usual arithmetic conversions are performed to bring them to a
3797 // common type, and the result is of that type.
3798 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3799 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00003800 if (LHS.isInvalid() || RHS.isInvalid())
3801 return QualType();
3802 return LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003803 }
3804
3805 // -- The second and third operands have pointer type, or one has pointer
3806 // type and the other is a null pointer constant; pointer conversions
3807 // and qualification conversions are performed to bring them to their
3808 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00003809 // -- The second and third operands have pointer to member type, or one has
3810 // pointer to member type and the other is a null pointer constant;
3811 // pointer to member conversions and qualification conversions are
3812 // performed to bring them to a common type, whose cv-qualification
3813 // shall match the cv-qualification of either the second or the third
3814 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003815 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003816 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003817 isSFINAEContext()? 0 : &NonStandardCompositeType);
3818 if (!Composite.isNull()) {
3819 if (NonStandardCompositeType)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003820 Diag(QuestionLoc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003821 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3822 << LTy << RTy << Composite
John Wiegley429bb272011-04-08 18:41:53 +00003823 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003824
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003825 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003826 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003827
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003828 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00003829 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3830 if (!Composite.isNull())
3831 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003832
Chandler Carruth7ef93242011-02-19 00:13:59 +00003833 // Check if we are using a null with a non-pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00003834 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth7ef93242011-02-19 00:13:59 +00003835 return QualType();
3836
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003837 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003838 << LHS.get()->getType() << RHS.get()->getType()
3839 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003840 return QualType();
3841}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003842
3843/// \brief Find a merged pointer type and convert the two expressions to it.
3844///
Douglas Gregor20b3e992009-08-24 17:42:35 +00003845/// This finds the composite pointer type (or member pointer type) for @p E1
3846/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3847/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003848/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003849///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003850/// \param Loc The location of the operator requiring these two expressions to
3851/// be converted to the composite pointer type.
3852///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003853/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3854/// a non-standard (but still sane) composite type to which both expressions
3855/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3856/// will be set true.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003857QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003858 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003859 bool *NonStandardCompositeType) {
3860 if (NonStandardCompositeType)
3861 *NonStandardCompositeType = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003862
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003863 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3864 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003865
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00003866 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3867 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00003868 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003869
3870 // C++0x 5.9p2
3871 // Pointer conversions and qualification conversions are performed on
3872 // pointer operands to bring them to their composite pointer type. If
3873 // one operand is a null pointer constant, the composite pointer type is
3874 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00003875 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003876 if (T2->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00003877 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003878 else
John Wiegley429bb272011-04-08 18:41:53 +00003879 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003880 return T2;
3881 }
Douglas Gregorce940492009-09-25 04:25:58 +00003882 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003883 if (T1->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00003884 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003885 else
John Wiegley429bb272011-04-08 18:41:53 +00003886 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003887 return T1;
3888 }
Mike Stump1eb44332009-09-09 15:08:12 +00003889
Douglas Gregor20b3e992009-08-24 17:42:35 +00003890 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003891 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3892 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003893 return QualType();
3894
3895 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3896 // the other has type "pointer to cv2 T" and the composite pointer type is
3897 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3898 // Otherwise, the composite pointer type is a pointer type similar to the
3899 // type of one of the operands, with a cv-qualification signature that is
3900 // the union of the cv-qualification signatures of the operand types.
3901 // In practice, the first part here is redundant; it's subsumed by the second.
3902 // What we do here is, we build the two possible composite types, and try the
3903 // conversions in both directions. If only one works, or if the two composite
3904 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00003905 // FIXME: extended qualifiers?
Chris Lattner5f9e2722011-07-23 10:55:15 +00003906 typedef SmallVector<unsigned, 4> QualifierVector;
Sebastian Redla439e6f2009-11-16 21:03:45 +00003907 QualifierVector QualifierUnion;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003908 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
Sebastian Redla439e6f2009-11-16 21:03:45 +00003909 ContainingClassVector;
3910 ContainingClassVector MemberOfClass;
3911 QualType Composite1 = Context.getCanonicalType(T1),
3912 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003913 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00003914 do {
3915 const PointerType *Ptr1, *Ptr2;
3916 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3917 (Ptr2 = Composite2->getAs<PointerType>())) {
3918 Composite1 = Ptr1->getPointeeType();
3919 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003920
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003921 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003922 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003923 if (NonStandardCompositeType &&
3924 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3925 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003926
Douglas Gregor20b3e992009-08-24 17:42:35 +00003927 QualifierUnion.push_back(
3928 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3929 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3930 continue;
3931 }
Mike Stump1eb44332009-09-09 15:08:12 +00003932
Douglas Gregor20b3e992009-08-24 17:42:35 +00003933 const MemberPointerType *MemPtr1, *MemPtr2;
3934 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3935 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3936 Composite1 = MemPtr1->getPointeeType();
3937 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003938
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003939 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003940 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003941 if (NonStandardCompositeType &&
3942 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3943 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003944
Douglas Gregor20b3e992009-08-24 17:42:35 +00003945 QualifierUnion.push_back(
3946 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3947 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3948 MemPtr2->getClass()));
3949 continue;
3950 }
Mike Stump1eb44332009-09-09 15:08:12 +00003951
Douglas Gregor20b3e992009-08-24 17:42:35 +00003952 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00003953
Douglas Gregor20b3e992009-08-24 17:42:35 +00003954 // Cannot unwrap any more types.
3955 break;
3956 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00003957
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003958 if (NeedConstBefore && NonStandardCompositeType) {
3959 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003960 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003961 // requirements of C++ [conv.qual]p4 bullet 3.
3962 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3963 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3964 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3965 *NonStandardCompositeType = true;
3966 }
3967 }
3968 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003969
Douglas Gregor20b3e992009-08-24 17:42:35 +00003970 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003971 ContainingClassVector::reverse_iterator MOC
3972 = MemberOfClass.rbegin();
3973 for (QualifierVector::reverse_iterator
3974 I = QualifierUnion.rbegin(),
3975 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00003976 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00003977 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003978 if (MOC->first && MOC->second) {
3979 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00003980 Composite1 = Context.getMemberPointerType(
3981 Context.getQualifiedType(Composite1, Quals),
3982 MOC->first);
3983 Composite2 = Context.getMemberPointerType(
3984 Context.getQualifiedType(Composite2, Quals),
3985 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003986 } else {
3987 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00003988 Composite1
3989 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3990 Composite2
3991 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00003992 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003993 }
3994
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003995 // Try to convert to the first composite pointer type.
3996 InitializedEntity Entity1
3997 = InitializedEntity::InitializeTemporary(Composite1);
3998 InitializationKind Kind
3999 = InitializationKind::CreateCopy(Loc, SourceLocation());
4000 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
4001 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00004002
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004003 if (E1ToC1 && E2ToC1) {
4004 // Conversion to Composite1 is viable.
4005 if (!Context.hasSameType(Composite1, Composite2)) {
4006 // Composite2 is a different type from Composite1. Check whether
4007 // Composite2 is also viable.
4008 InitializedEntity Entity2
4009 = InitializedEntity::InitializeTemporary(Composite2);
4010 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4011 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4012 if (E1ToC2 && E2ToC2) {
4013 // Both Composite1 and Composite2 are viable and are different;
4014 // this is an ambiguity.
4015 return QualType();
4016 }
4017 }
4018
4019 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004020 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004021 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004022 if (E1Result.isInvalid())
4023 return QualType();
4024 E1 = E1Result.takeAs<Expr>();
4025
4026 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004027 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004028 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004029 if (E2Result.isInvalid())
4030 return QualType();
4031 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004032
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004033 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004034 }
4035
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004036 // Check whether Composite2 is viable.
4037 InitializedEntity Entity2
4038 = InitializedEntity::InitializeTemporary(Composite2);
4039 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4040 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4041 if (!E1ToC2 || !E2ToC2)
4042 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004043
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004044 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004045 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004046 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004047 if (E1Result.isInvalid())
4048 return QualType();
4049 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004050
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004051 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004052 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004053 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004054 if (E2Result.isInvalid())
4055 return QualType();
4056 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004057
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004058 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004059}
Anders Carlsson165a0a02009-05-17 18:41:29 +00004060
John McCall60d7b3a2010-08-24 06:29:42 +00004061ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00004062 if (!E)
4063 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004064
John McCallf85e1932011-06-15 23:02:42 +00004065 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4066
4067 // If the result is a glvalue, we shouldn't bind it.
4068 if (!E->isRValue())
Anders Carlsson089c2602009-08-15 23:41:35 +00004069 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004070
John McCallf85e1932011-06-15 23:02:42 +00004071 // In ARC, calls that return a retainable type can return retained,
4072 // in which case we have to insert a consuming cast.
4073 if (getLangOptions().ObjCAutoRefCount &&
4074 E->getType()->isObjCRetainableType()) {
4075
4076 bool ReturnsRetained;
4077
4078 // For actual calls, we compute this by examining the type of the
4079 // called value.
4080 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4081 Expr *Callee = Call->getCallee()->IgnoreParens();
4082 QualType T = Callee->getType();
4083
4084 if (T == Context.BoundMemberTy) {
4085 // Handle pointer-to-members.
4086 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4087 T = BinOp->getRHS()->getType();
4088 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4089 T = Mem->getMemberDecl()->getType();
4090 }
4091
4092 if (const PointerType *Ptr = T->getAs<PointerType>())
4093 T = Ptr->getPointeeType();
4094 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4095 T = Ptr->getPointeeType();
4096 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4097 T = MemPtr->getPointeeType();
4098
4099 const FunctionType *FTy = T->getAs<FunctionType>();
4100 assert(FTy && "call to value not of function type?");
4101 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4102
4103 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4104 // type always produce a +1 object.
4105 } else if (isa<StmtExpr>(E)) {
4106 ReturnsRetained = true;
4107
4108 // For message sends and property references, we try to find an
4109 // actual method. FIXME: we should infer retention by selector in
4110 // cases where we don't have an actual method.
4111 } else {
John McCallfc4b1912011-08-03 07:02:44 +00004112 ObjCMethodDecl *D = 0;
John McCallf85e1932011-06-15 23:02:42 +00004113 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4114 D = Send->getMethodDecl();
John McCallf85e1932011-06-15 23:02:42 +00004115 }
4116
4117 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCallfc4b1912011-08-03 07:02:44 +00004118
4119 // Don't do reclaims on performSelector calls; despite their
4120 // return type, the invoked method doesn't necessarily actually
4121 // return an object.
4122 if (!ReturnsRetained &&
4123 D && D->getMethodFamily() == OMF_performSelector)
4124 return Owned(E);
John McCallf85e1932011-06-15 23:02:42 +00004125 }
4126
John McCall567c5862011-11-14 19:53:16 +00004127 // Don't reclaim an object of Class type.
4128 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4129 return Owned(E);
4130
John McCall7e5e5f42011-07-07 06:58:02 +00004131 ExprNeedsCleanups = true;
4132
John McCall33e56f32011-09-10 06:18:15 +00004133 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4134 : CK_ARCReclaimReturnedObject);
John McCall7e5e5f42011-07-07 06:58:02 +00004135 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4136 VK_RValue));
John McCallf85e1932011-06-15 23:02:42 +00004137 }
4138
4139 if (!getLangOptions().CPlusPlus)
4140 return Owned(E);
Douglas Gregor51326552009-12-24 18:51:59 +00004141
Peter Collingbournebceb7552011-11-27 22:09:28 +00004142 QualType ET = Context.getBaseElementType(E->getType());
4143 const RecordType *RT = ET->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00004144 if (!RT)
4145 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004146
John McCall86ff3082010-02-04 22:26:26 +00004147 // That should be enough to guarantee that this type is complete.
4148 // If it has a trivial destructor, we can avoid the extra copy.
Jeffrey Yasskinb7ee2e52011-01-27 19:17:54 +00004149 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall507384f2010-08-12 02:40:37 +00004150 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00004151 return Owned(E);
4152
John McCallf85e1932011-06-15 23:02:42 +00004153 CXXDestructorDecl *Destructor = LookupDestructor(RD);
4154
4155 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
4156 if (Destructor) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00004157 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00004158 CheckDestructorAccess(E->getExprLoc(), Destructor,
4159 PDiag(diag::err_access_dtor_temp)
4160 << E->getType());
John McCallf85e1932011-06-15 23:02:42 +00004161
John McCall80ee6e82011-11-10 05:35:25 +00004162 // We need a cleanup, but we don't need to remember the temporary.
John McCallf85e1932011-06-15 23:02:42 +00004163 ExprNeedsCleanups = true;
John McCallc91cc662010-04-07 00:41:46 +00004164 }
Anders Carlssondef11992009-05-30 20:36:53 +00004165 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
4166}
4167
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004168ExprResult
John McCall4765fa02010-12-06 08:20:24 +00004169Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004170 if (SubExpr.isInvalid())
4171 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004172
John McCall4765fa02010-12-06 08:20:24 +00004173 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00004174}
4175
John McCall80ee6e82011-11-10 05:35:25 +00004176Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
4177 assert(SubExpr && "sub expression can't be null!");
4178
4179 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
4180 assert(ExprCleanupObjects.size() >= FirstCleanup);
4181 assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
4182 if (!ExprNeedsCleanups)
4183 return SubExpr;
4184
4185 ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
4186 = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
4187 ExprCleanupObjects.size() - FirstCleanup);
4188
4189 Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
4190 DiscardCleanupsInEvaluationContext();
4191
4192 return E;
4193}
4194
John McCall4765fa02010-12-06 08:20:24 +00004195Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004196 assert(SubStmt && "sub statement can't be null!");
4197
John McCallf85e1932011-06-15 23:02:42 +00004198 if (!ExprNeedsCleanups)
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004199 return SubStmt;
4200
4201 // FIXME: In order to attach the temporaries, wrap the statement into
4202 // a StmtExpr; currently this is only used for asm statements.
4203 // This is hacky, either create a new CXXStmtWithTemporaries statement or
4204 // a new AsmStmtWithTemporaries.
4205 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
4206 SourceLocation(),
4207 SourceLocation());
4208 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
4209 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00004210 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004211}
4212
John McCall60d7b3a2010-08-24 06:29:42 +00004213ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004214Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00004215 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00004216 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004217 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004218 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004219 if (Result.isInvalid()) return ExprError();
4220 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004221
John McCall3c3b7f92011-10-25 17:37:35 +00004222 Result = CheckPlaceholderExpr(Base);
4223 if (Result.isInvalid()) return ExprError();
4224 Base = Result.take();
4225
John McCall9ae2f072010-08-23 23:25:46 +00004226 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004227 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004228 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00004229 // If we have a pointer to a dependent type and are using the -> operator,
4230 // the object type is the type that the pointer points to. We might still
4231 // have enough information about that type to do something useful.
4232 if (OpKind == tok::arrow)
4233 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4234 BaseType = Ptr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004235
John McCallb3d87482010-08-24 05:47:05 +00004236 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00004237 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004238 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004239 }
Mike Stump1eb44332009-09-09 15:08:12 +00004240
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004241 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00004242 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004243 // returned, with the original second operand.
4244 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00004245 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00004246 llvm::SmallPtrSet<CanQualType,8> CTypes;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004247 SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00004248 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004249
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004250 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00004251 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
4252 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004253 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00004254 Base = Result.get();
4255 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00004256 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00004257 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00004258 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00004259 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004260 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00004261 for (unsigned i = 0; i < Locations.size(); i++)
4262 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004263 return ExprError();
4264 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004265 }
Mike Stump1eb44332009-09-09 15:08:12 +00004266
Douglas Gregor31658df2009-11-20 19:58:21 +00004267 if (BaseType->isPointerType())
4268 BaseType = BaseType->getPointeeType();
4269 }
Mike Stump1eb44332009-09-09 15:08:12 +00004270
4271 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004272 // vector types or Objective-C interfaces. Just return early and let
4273 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00004274 if (!BaseType->isRecordType()) {
4275 // C++ [basic.lookup.classref]p2:
4276 // [...] If the type of the object expression is of pointer to scalar
4277 // type, the unqualified-id is looked up in the context of the complete
4278 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00004279 //
4280 // This also indicates that we should be parsing a
4281 // pseudo-destructor-name.
John McCallb3d87482010-08-24 05:47:05 +00004282 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004283 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004284 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00004285 }
Mike Stump1eb44332009-09-09 15:08:12 +00004286
Douglas Gregor03c57052009-11-17 05:17:33 +00004287 // The object type must be complete (or dependent).
4288 if (!BaseType->isDependentType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004289 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor03c57052009-11-17 05:17:33 +00004290 PDiag(diag::err_incomplete_member_access)))
4291 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004292
Douglas Gregorc68afe22009-09-03 21:38:09 +00004293 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004294 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00004295 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00004296 // type C (or of pointer to a class type C), the unqualified-id is looked
4297 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00004298 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00004299 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004300}
4301
John McCall60d7b3a2010-08-24 06:29:42 +00004302ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00004303 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00004304 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00004305 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
4306 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00004307 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004308
Douglas Gregor77549082010-02-24 21:29:12 +00004309 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00004310 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00004311 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00004312 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00004313 /*RPLoc*/ ExpectedLParenLoc);
4314}
Douglas Gregord4dca082010-02-24 18:44:31 +00004315
John McCall60d7b3a2010-08-24 06:29:42 +00004316ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004317 SourceLocation OpLoc,
4318 tok::TokenKind OpKind,
4319 const CXXScopeSpec &SS,
4320 TypeSourceInfo *ScopeTypeInfo,
4321 SourceLocation CCLoc,
4322 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004323 PseudoDestructorTypeStorage Destructed,
John McCall2d9f5fa2011-02-25 05:21:17 +00004324 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004325 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004326
Douglas Gregorb57fb492010-02-24 22:38:50 +00004327 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004328 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregorb57fb492010-02-24 22:38:50 +00004329 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004330 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00004331 QualType ObjectType = Base->getType();
Douglas Gregorb57fb492010-02-24 22:38:50 +00004332 if (OpKind == tok::arrow) {
4333 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4334 ObjectType = Ptr->getPointeeType();
John McCall9ae2f072010-08-23 23:25:46 +00004335 } else if (!Base->isTypeDependent()) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004336 // The user wrote "p->" when she probably meant "p."; fix it.
4337 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4338 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00004339 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00004340 if (isSFINAEContext())
4341 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004342
Douglas Gregorb57fb492010-02-24 22:38:50 +00004343 OpKind = tok::period;
4344 }
4345 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004346
Douglas Gregorb57fb492010-02-24 22:38:50 +00004347 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
4348 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCall9ae2f072010-08-23 23:25:46 +00004349 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00004350 return ExprError();
4351 }
4352
4353 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004354 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb57fb492010-02-24 22:38:50 +00004355 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004356 if (DestructedTypeInfo) {
4357 QualType DestructedType = DestructedTypeInfo->getType();
4358 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004359 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCallf85e1932011-06-15 23:02:42 +00004360 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
4361 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
4362 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
4363 << ObjectType << DestructedType << Base->getSourceRange()
4364 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004365
John McCallf85e1932011-06-15 23:02:42 +00004366 // Recover by setting the destructed type to the object type.
4367 DestructedType = ObjectType;
4368 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004369 DestructedTypeStart);
John McCallf85e1932011-06-15 23:02:42 +00004370 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4371 } else if (DestructedType.getObjCLifetime() !=
4372 ObjectType.getObjCLifetime()) {
4373
4374 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
4375 // Okay: just pretend that the user provided the correctly-qualified
4376 // type.
4377 } else {
4378 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
4379 << ObjectType << DestructedType << Base->getSourceRange()
4380 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4381 }
4382
4383 // Recover by setting the destructed type to the object type.
4384 DestructedType = ObjectType;
4385 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4386 DestructedTypeStart);
4387 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4388 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004389 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00004390 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004391
Douglas Gregorb57fb492010-02-24 22:38:50 +00004392 // C++ [expr.pseudo]p2:
4393 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4394 // form
4395 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004396 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb57fb492010-02-24 22:38:50 +00004397 //
4398 // shall designate the same scalar type.
4399 if (ScopeTypeInfo) {
4400 QualType ScopeType = ScopeTypeInfo->getType();
4401 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00004402 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004403
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004404 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00004405 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00004406 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004407 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004408
Douglas Gregorb57fb492010-02-24 22:38:50 +00004409 ScopeType = QualType();
4410 ScopeTypeInfo = 0;
4411 }
4412 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004413
John McCall9ae2f072010-08-23 23:25:46 +00004414 Expr *Result
4415 = new (Context) CXXPseudoDestructorExpr(Context, Base,
4416 OpKind == tok::arrow, OpLoc,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004417 SS.getWithLocInContext(Context),
John McCall9ae2f072010-08-23 23:25:46 +00004418 ScopeTypeInfo,
4419 CCLoc,
4420 TildeLoc,
4421 Destructed);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004422
Douglas Gregorb57fb492010-02-24 22:38:50 +00004423 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00004424 return Owned(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004425
John McCall9ae2f072010-08-23 23:25:46 +00004426 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00004427}
4428
John McCall60d7b3a2010-08-24 06:29:42 +00004429ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004430 SourceLocation OpLoc,
4431 tok::TokenKind OpKind,
4432 CXXScopeSpec &SS,
4433 UnqualifiedId &FirstTypeName,
4434 SourceLocation CCLoc,
4435 SourceLocation TildeLoc,
4436 UnqualifiedId &SecondTypeName,
4437 bool HasTrailingLParen) {
Douglas Gregor77549082010-02-24 21:29:12 +00004438 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4439 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4440 "Invalid first type name in pseudo-destructor");
4441 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4442 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4443 "Invalid second type name in pseudo-destructor");
4444
Douglas Gregor77549082010-02-24 21:29:12 +00004445 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004446 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregor77549082010-02-24 21:29:12 +00004447 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004448 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00004449 QualType ObjectType = Base->getType();
Douglas Gregor77549082010-02-24 21:29:12 +00004450 if (OpKind == tok::arrow) {
4451 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4452 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004453 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00004454 // The user wrote "p->" when she probably meant "p."; fix it.
4455 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004456 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00004457 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00004458 if (isSFINAEContext())
4459 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004460
Douglas Gregor77549082010-02-24 21:29:12 +00004461 OpKind = tok::period;
4462 }
4463 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004464
4465 // Compute the object type that we should use for name lookup purposes. Only
4466 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00004467 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004468 if (!SS.isSet()) {
John McCall2d9f5fa2011-02-25 05:21:17 +00004469 if (ObjectType->isRecordType())
4470 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallb3d87482010-08-24 05:47:05 +00004471 else if (ObjectType->isDependentType())
4472 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004473 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004474
4475 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb57fb492010-02-24 22:38:50 +00004476 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00004477 QualType DestructedType;
4478 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004479 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00004480 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004481 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00004482 SecondTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00004483 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004484 if (!T &&
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004485 ((SS.isSet() && !computeDeclContext(SS, false)) ||
4486 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004487 // The name of the type being destroyed is a dependent name, and we
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004488 // couldn't find anything useful in scope. Just store the identifier and
4489 // it's location, and we'll perform (qualified) name lookup again at
4490 // template instantiation time.
4491 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
4492 SecondTypeName.StartLocation);
4493 } else if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004494 Diag(SecondTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00004495 diag::err_pseudo_dtor_destructor_non_type)
4496 << SecondTypeName.Identifier << ObjectType;
4497 if (isSFINAEContext())
4498 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004499
Douglas Gregor77549082010-02-24 21:29:12 +00004500 // Recover by assuming we had the right type all along.
4501 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004502 } else
Douglas Gregor77549082010-02-24 21:29:12 +00004503 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004504 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004505 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00004506 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004507 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4508 TemplateId->getTemplateArgs(),
4509 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00004510 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4511 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004512 TemplateId->TemplateNameLoc,
4513 TemplateId->LAngleLoc,
4514 TemplateArgsPtr,
4515 TemplateId->RAngleLoc);
4516 if (T.isInvalid() || !T.get()) {
4517 // Recover by assuming we had the right type all along.
4518 DestructedType = ObjectType;
4519 } else
4520 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004521 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004522
4523 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb57fb492010-02-24 22:38:50 +00004524 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004525 if (!DestructedType.isNull()) {
4526 if (!DestructedTypeInfo)
4527 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004528 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004529 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4530 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004531
Douglas Gregorb57fb492010-02-24 22:38:50 +00004532 // Convert the name of the scope type (the type prior to '::') into a type.
4533 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00004534 QualType ScopeType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004535 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor77549082010-02-24 21:29:12 +00004536 FirstTypeName.Identifier) {
4537 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004538 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00004539 FirstTypeName.StartLocation,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004540 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00004541 if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004542 Diag(FirstTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00004543 diag::err_pseudo_dtor_destructor_non_type)
4544 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004545
Douglas Gregorb57fb492010-02-24 22:38:50 +00004546 if (isSFINAEContext())
4547 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004548
Douglas Gregorb57fb492010-02-24 22:38:50 +00004549 // Just drop this type. It's unnecessary anyway.
4550 ScopeType = QualType();
4551 } else
4552 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004553 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004554 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00004555 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004556 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4557 TemplateId->getTemplateArgs(),
4558 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00004559 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4560 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004561 TemplateId->TemplateNameLoc,
4562 TemplateId->LAngleLoc,
4563 TemplateArgsPtr,
4564 TemplateId->RAngleLoc);
4565 if (T.isInvalid() || !T.get()) {
4566 // Recover by dropping this type.
4567 ScopeType = QualType();
4568 } else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004569 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004570 }
4571 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004572
Douglas Gregorb4a418f2010-02-24 23:02:30 +00004573 if (!ScopeType.isNull() && !ScopeTypeInfo)
4574 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
4575 FirstTypeName.StartLocation);
4576
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004577
John McCall9ae2f072010-08-23 23:25:46 +00004578 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00004579 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004580 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00004581}
4582
John Wiegley429bb272011-04-08 18:41:53 +00004583ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004584 CXXMethodDecl *Method,
4585 bool HadMultipleCandidates) {
John Wiegley429bb272011-04-08 18:41:53 +00004586 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
4587 FoundDecl, Method);
4588 if (Exp.isInvalid())
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004589 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00004590
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004591 MemberExpr *ME =
John Wiegley429bb272011-04-08 18:41:53 +00004592 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
Abramo Bagnara960809e2011-11-16 22:46:05 +00004593 SourceLocation(), Context.BoundMemberTy,
John McCallf89e55a2010-11-18 06:31:45 +00004594 VK_RValue, OK_Ordinary);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004595 if (HadMultipleCandidates)
4596 ME->setHadMultipleCandidates(true);
4597
John McCallf89e55a2010-11-18 06:31:45 +00004598 QualType ResultType = Method->getResultType();
4599 ExprValueKind VK = Expr::getValueKindForType(ResultType);
4600 ResultType = ResultType.getNonLValueExprType(Context);
4601
John Wiegley429bb272011-04-08 18:41:53 +00004602 MarkDeclarationReferenced(Exp.get()->getLocStart(), Method);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004603 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00004604 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
John Wiegley429bb272011-04-08 18:41:53 +00004605 Exp.get()->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00004606 return CE;
4607}
4608
Sebastian Redl2e156222010-09-10 20:55:43 +00004609ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4610 SourceLocation RParen) {
Sebastian Redl2e156222010-09-10 20:55:43 +00004611 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
4612 Operand->CanThrow(Context),
4613 KeyLoc, RParen));
4614}
4615
4616ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
4617 Expr *Operand, SourceLocation RParen) {
4618 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00004619}
4620
John McCallf6a16482010-12-04 03:47:34 +00004621/// Perform the conversions required for an expression used in a
4622/// context that ignores the result.
John Wiegley429bb272011-04-08 18:41:53 +00004623ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall3c3b7f92011-10-25 17:37:35 +00004624 if (E->hasPlaceholderType()) {
4625 ExprResult result = CheckPlaceholderExpr(E);
4626 if (result.isInvalid()) return Owned(E);
4627 E = result.take();
4628 }
4629
John McCalla878cda2010-12-02 02:07:15 +00004630 // C99 6.3.2.1:
4631 // [Except in specific positions,] an lvalue that does not have
4632 // array type is converted to the value stored in the
4633 // designated object (and is no longer an lvalue).
John McCalle6d134b2011-06-27 21:24:11 +00004634 if (E->isRValue()) {
4635 // In C, function designators (i.e. expressions of function type)
4636 // are r-values, but we still want to do function-to-pointer decay
4637 // on them. This is both technically correct and convenient for
4638 // some clients.
4639 if (!getLangOptions().CPlusPlus && E->getType()->isFunctionType())
4640 return DefaultFunctionArrayConversion(E);
4641
4642 return Owned(E);
4643 }
John McCalla878cda2010-12-02 02:07:15 +00004644
John McCallf6a16482010-12-04 03:47:34 +00004645 // Otherwise, this rule does not apply in C++, at least not for the moment.
John Wiegley429bb272011-04-08 18:41:53 +00004646 if (getLangOptions().CPlusPlus) return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004647
4648 // GCC seems to also exclude expressions of incomplete enum type.
4649 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
4650 if (!T->getDecl()->isComplete()) {
4651 // FIXME: stupid workaround for a codegen bug!
John Wiegley429bb272011-04-08 18:41:53 +00004652 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
4653 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004654 }
4655 }
4656
John Wiegley429bb272011-04-08 18:41:53 +00004657 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
4658 if (Res.isInvalid())
4659 return Owned(E);
4660 E = Res.take();
4661
John McCall85515d62010-12-04 12:29:11 +00004662 if (!E->getType()->isVoidType())
4663 RequireCompleteType(E->getExprLoc(), E->getType(),
4664 diag::err_incomplete_type);
John Wiegley429bb272011-04-08 18:41:53 +00004665 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004666}
4667
John Wiegley429bb272011-04-08 18:41:53 +00004668ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
4669 ExprResult FullExpr = Owned(FE);
4670
4671 if (!FullExpr.get())
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00004672 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00004673
John Wiegley429bb272011-04-08 18:41:53 +00004674 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregord0937222010-12-13 22:49:22 +00004675 return ExprError();
4676
John McCallfb8721c2011-04-10 19:13:55 +00004677 FullExpr = CheckPlaceholderExpr(FullExpr.take());
4678 if (FullExpr.isInvalid())
4679 return ExprError();
Douglas Gregor353ee242011-03-07 02:05:23 +00004680
John Wiegley429bb272011-04-08 18:41:53 +00004681 FullExpr = IgnoredValueConversions(FullExpr.take());
4682 if (FullExpr.isInvalid())
4683 return ExprError();
4684
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004685 CheckImplicitConversions(FullExpr.get(), FullExpr.get()->getExprLoc());
John McCall4765fa02010-12-06 08:20:24 +00004686 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00004687}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004688
4689StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
4690 if (!FullStmt) return StmtError();
4691
John McCall4765fa02010-12-06 08:20:24 +00004692 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004693}
Francois Pichet1e862692011-05-06 20:48:22 +00004694
Douglas Gregorba0513d2011-10-25 01:33:02 +00004695Sema::IfExistsResult
4696Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
4697 CXXScopeSpec &SS,
4698 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet1e862692011-05-06 20:48:22 +00004699 DeclarationName TargetName = TargetNameInfo.getName();
4700 if (!TargetName)
Douglas Gregor3896fc52011-10-24 22:31:10 +00004701 return IER_DoesNotExist;
Douglas Gregorba0513d2011-10-25 01:33:02 +00004702
Douglas Gregor3896fc52011-10-24 22:31:10 +00004703 // If the name itself is dependent, then the result is dependent.
4704 if (TargetName.isDependentName())
4705 return IER_Dependent;
Douglas Gregorba0513d2011-10-25 01:33:02 +00004706
Francois Pichet1e862692011-05-06 20:48:22 +00004707 // Do the redeclaration lookup in the current scope.
4708 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
4709 Sema::NotForRedeclaration);
Douglas Gregor3896fc52011-10-24 22:31:10 +00004710 LookupParsedName(R, S, &SS);
Francois Pichet1e862692011-05-06 20:48:22 +00004711 R.suppressDiagnostics();
Douglas Gregor3896fc52011-10-24 22:31:10 +00004712
4713 switch (R.getResultKind()) {
4714 case LookupResult::Found:
4715 case LookupResult::FoundOverloaded:
4716 case LookupResult::FoundUnresolvedValue:
4717 case LookupResult::Ambiguous:
4718 return IER_Exists;
4719
4720 case LookupResult::NotFound:
4721 return IER_DoesNotExist;
4722
4723 case LookupResult::NotFoundInCurrentInstantiation:
4724 return IER_Dependent;
4725 }
4726
Douglas Gregorba0513d2011-10-25 01:33:02 +00004727 return IER_DoesNotExist;
Francois Pichet1e862692011-05-06 20:48:22 +00004728}
Douglas Gregorba0513d2011-10-25 01:33:02 +00004729
Douglas Gregor65019ac2011-10-25 03:44:56 +00004730Sema::IfExistsResult
4731Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4732 bool IsIfExists, CXXScopeSpec &SS,
4733 UnqualifiedId &Name) {
Douglas Gregorba0513d2011-10-25 01:33:02 +00004734 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Douglas Gregor65019ac2011-10-25 03:44:56 +00004735
4736 // Check for unexpanded parameter packs.
4737 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
4738 collectUnexpandedParameterPacks(SS, Unexpanded);
4739 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
4740 if (!Unexpanded.empty()) {
4741 DiagnoseUnexpandedParameterPacks(KeywordLoc,
4742 IsIfExists? UPPC_IfExists
4743 : UPPC_IfNotExists,
4744 Unexpanded);
4745 return IER_Error;
4746 }
4747
Douglas Gregorba0513d2011-10-25 01:33:02 +00004748 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
4749}
4750