blob: eaa330b183a956297789b97fb49373128ed6b015 [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"
David Blaikie91ec7892011-12-16 16:03:09 +000031#include "TypeLocBuilder.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000032#include "llvm/ADT/STLExtras.h"
Chandler Carruth73e0a912011-05-01 07:23:17 +000033#include "llvm/Support/ErrorHandling.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000034using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000035using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000036
John McCallb3d87482010-08-24 05:47:05 +000037ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000038 IdentifierInfo &II,
John McCallb3d87482010-08-24 05:47:05 +000039 SourceLocation NameLoc,
40 Scope *S, CXXScopeSpec &SS,
41 ParsedType ObjectTypePtr,
42 bool EnteringContext) {
Douglas Gregor124b8782010-02-16 19:09:40 +000043 // Determine where to perform name lookup.
44
45 // FIXME: This area of the standard is very messy, and the current
46 // wording is rather unclear about which scopes we search for the
47 // destructor name; see core issues 399 and 555. Issue 399 in
48 // particular shows where the current description of destructor name
49 // lookup is completely out of line with existing practice, e.g.,
50 // this appears to be ill-formed:
51 //
52 // namespace N {
53 // template <typename T> struct S {
54 // ~S();
55 // };
56 // }
57 //
58 // void f(N::S<int>* s) {
59 // s->N::S<int>::~S();
60 // }
61 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000062 // See also PR6358 and PR6359.
Sebastian Redlc0fee502010-07-07 23:17:38 +000063 // For this reason, we're currently only doing the C++03 version of this
64 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregor124b8782010-02-16 19:09:40 +000065 QualType SearchType;
66 DeclContext *LookupCtx = 0;
67 bool isDependent = false;
68 bool LookInScope = false;
69
70 // If we have an object type, it's because we are in a
71 // pseudo-destructor-expression or a member access expression, and
72 // we know what type we're looking for.
73 if (ObjectTypePtr)
74 SearchType = GetTypeFromParser(ObjectTypePtr);
75
76 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000077 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000078
Douglas Gregor93649fd2010-02-23 00:15:22 +000079 bool AlreadySearched = false;
80 bool LookAtPrefix = true;
Sebastian Redlc0fee502010-07-07 23:17:38 +000081 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000082 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redlc0fee502010-07-07 23:17:38 +000083 // the type-names are looked up as types in the scope designated by the
84 // nested-name-specifier. In a qualified-id of the form:
NAKAMURA Takumi00995302011-01-27 07:09:49 +000085 //
86 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redlc0fee502010-07-07 23:17:38 +000087 //
88 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth5e895a82010-02-21 10:19:54 +000089 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +000090 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +000091 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregor124b8782010-02-16 19:09:40 +000092 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000093 // the class-names are looked up as types in the scope designated by
Sebastian Redlc0fee502010-07-07 23:17:38 +000094 // the nested-name-specifier.
Douglas Gregor124b8782010-02-16 19:09:40 +000095 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000096 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000097 // code below is permitted to look at the prefix of the
Sebastian Redlc0fee502010-07-07 23:17:38 +000098 // nested-name-specifier.
99 DeclContext *DC = computeDeclContext(SS, EnteringContext);
100 if (DC && DC->isFileContext()) {
101 AlreadySearched = true;
102 LookupCtx = DC;
103 isDependent = false;
104 } else if (DC && isa<CXXRecordDecl>(DC))
105 LookAtPrefix = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000106
Sebastian Redlc0fee502010-07-07 23:17:38 +0000107 // The second case from the C++03 rules quoted further above.
Douglas Gregor93649fd2010-02-23 00:15:22 +0000108 NestedNameSpecifier *Prefix = 0;
109 if (AlreadySearched) {
110 // Nothing left to do.
111 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
112 CXXScopeSpec PrefixSS;
Douglas Gregor7e384942011-02-25 16:07:42 +0000113 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor93649fd2010-02-23 00:15:22 +0000114 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
115 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000116 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000117 LookupCtx = computeDeclContext(SearchType);
118 isDependent = SearchType->isDependentType();
119 } else {
120 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000121 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000122 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000123
Douglas Gregoredc90502010-02-25 04:46:04 +0000124 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000125 } else if (ObjectTypePtr) {
126 // C++ [basic.lookup.classref]p3:
127 // If the unqualified-id is ~type-name, the type-name is looked up
128 // in the context of the entire postfix-expression. If the type T
129 // of the object expression is of a class type C, the type-name is
130 // also looked up in the scope of class C. At least one of the
131 // lookups shall find a name that refers to (possibly
132 // cv-qualified) T.
133 LookupCtx = computeDeclContext(SearchType);
134 isDependent = SearchType->isDependentType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000135 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregor124b8782010-02-16 19:09:40 +0000136 "Caller should have completed object type");
137
138 LookInScope = true;
139 } else {
140 // Perform lookup into the current scope (only).
141 LookInScope = true;
142 }
143
Douglas Gregor7ec18732011-03-04 22:32:08 +0000144 TypeDecl *NonMatchingTypeDecl = 0;
Douglas Gregor124b8782010-02-16 19:09:40 +0000145 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
146 for (unsigned Step = 0; Step != 2; ++Step) {
147 // Look for the name first in the computed lookup context (if we
Douglas Gregor7ec18732011-03-04 22:32:08 +0000148 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregor124b8782010-02-16 19:09:40 +0000149 // we're allowed to look there).
150 Found.clear();
151 if (Step == 0 && LookupCtx)
152 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000153 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000154 LookupName(Found, S);
155 else
156 continue;
157
158 // FIXME: Should we be suppressing ambiguities here?
159 if (Found.isAmbiguous())
John McCallb3d87482010-08-24 05:47:05 +0000160 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000161
162 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
163 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000164
165 if (SearchType.isNull() || SearchType->isDependentType() ||
166 Context.hasSameUnqualifiedType(T, SearchType)) {
167 // We found our type!
168
John McCallb3d87482010-08-24 05:47:05 +0000169 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000170 }
John Wiegley36784e72011-03-08 08:13:22 +0000171
Douglas Gregor7ec18732011-03-04 22:32:08 +0000172 if (!SearchType.isNull())
173 NonMatchingTypeDecl = Type;
Douglas Gregor124b8782010-02-16 19:09:40 +0000174 }
175
176 // If the name that we found is a class template name, and it is
177 // the same name as the template name in the last part of the
178 // nested-name-specifier (if present) or the object type, then
179 // this is the destructor for that class.
180 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000181 // issue 399, for which there isn't even an obvious direction.
Douglas Gregor124b8782010-02-16 19:09:40 +0000182 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
183 QualType MemberOfType;
184 if (SS.isSet()) {
185 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
186 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000187 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
188 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000189 }
190 }
191 if (MemberOfType.isNull())
192 MemberOfType = SearchType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000193
Douglas Gregor124b8782010-02-16 19:09:40 +0000194 if (MemberOfType.isNull())
195 continue;
196
197 // We're referring into a class template specialization. If the
198 // class template we found is the same as the template being
199 // specialized, we found what we are looking for.
200 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
201 if (ClassTemplateSpecializationDecl *Spec
202 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
203 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
204 Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000205 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000206 }
207
208 continue;
209 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000210
Douglas Gregor124b8782010-02-16 19:09:40 +0000211 // We're referring to an unresolved class template
212 // specialization. Determine whether we class template we found
213 // is the same as the template being specialized or, if we don't
214 // know which template is being specialized, that it at least
215 // has the same name.
216 if (const TemplateSpecializationType *SpecType
217 = MemberOfType->getAs<TemplateSpecializationType>()) {
218 TemplateName SpecName = SpecType->getTemplateName();
219
220 // The class template we found is the same template being
221 // specialized.
222 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
223 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000224 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000225
226 continue;
227 }
228
229 // The class template we found has the same name as the
230 // (dependent) template name being specialized.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000231 if (DependentTemplateName *DepTemplate
Douglas Gregor124b8782010-02-16 19:09:40 +0000232 = SpecName.getAsDependentTemplateName()) {
233 if (DepTemplate->isIdentifier() &&
234 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallb3d87482010-08-24 05:47:05 +0000235 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000236
237 continue;
238 }
239 }
240 }
241 }
242
243 if (isDependent) {
244 // We didn't find our type, but that's okay: it's dependent
245 // anyway.
Douglas Gregore29425b2011-02-28 22:42:13 +0000246
247 // FIXME: What if we have no nested-name-specifier?
248 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
249 SS.getWithLocInContext(Context),
250 II, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000251 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000252 }
253
Douglas Gregor7ec18732011-03-04 22:32:08 +0000254 if (NonMatchingTypeDecl) {
255 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
256 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
257 << T << SearchType;
258 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
259 << T;
260 } else if (ObjectTypePtr)
261 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000262 << &II;
Douglas Gregor124b8782010-02-16 19:09:40 +0000263 else
264 Diag(NameLoc, diag::err_destructor_class_name);
265
John McCallb3d87482010-08-24 05:47:05 +0000266 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000267}
268
David Blaikie53a75c02011-12-08 16:13:53 +0000269ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
David Blaikie4db8c442011-12-12 04:13:55 +0000270 if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
David Blaikie53a75c02011-12-08 16:13:53 +0000271 return ParsedType();
272 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
273 && "only get destructor types from declspecs");
274 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
275 QualType SearchType = GetTypeFromParser(ObjectType);
276 if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
277 return ParsedType::make(T);
278 }
279
280 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
281 << T << SearchType;
282 return ParsedType();
283}
284
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000285/// \brief Build a C++ typeid expression with a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000286ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000287 SourceLocation TypeidLoc,
288 TypeSourceInfo *Operand,
289 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000290 // C++ [expr.typeid]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000291 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000292 // that is the operand of typeid are always ignored.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000293 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000294 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000295 Qualifiers Quals;
296 QualType T
297 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
298 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000299 if (T->getAs<RecordType>() &&
300 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
301 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000302
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000303 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
304 Operand,
305 SourceRange(TypeidLoc, RParenLoc)));
306}
307
308/// \brief Build a C++ typeid expression with an expression operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000309ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000310 SourceLocation TypeidLoc,
311 Expr *E,
312 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000313 bool isUnevaluatedOperand = true;
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000314 if (E && !E->isTypeDependent()) {
John McCall6dbba4f2011-10-11 23:14:30 +0000315 if (E->getType()->isPlaceholderType()) {
316 ExprResult result = CheckPlaceholderExpr(E);
317 if (result.isInvalid()) return ExprError();
318 E = result.take();
319 }
320
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000321 QualType T = E->getType();
322 if (const RecordType *RecordT = T->getAs<RecordType>()) {
323 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
324 // C++ [expr.typeid]p3:
325 // [...] If the type of the expression is a class type, the class
326 // shall be completely-defined.
327 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
328 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000329
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000330 // C++ [expr.typeid]p3:
Sebastian Redl906082e2010-07-20 04:20:21 +0000331 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000332 // polymorphic class type [...] [the] expression is an unevaluated
333 // operand. [...]
Sebastian Redl906082e2010-07-20 04:20:21 +0000334 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000335 isUnevaluatedOperand = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000336
337 // We require a vtable to query the type at run time.
338 MarkVTableUsed(TypeidLoc, RecordD);
339 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000340 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000341
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000342 // C++ [expr.typeid]p4:
343 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000344 // cv-qualified type, the result of the typeid expression refers to a
345 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000346 // type.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000347 Qualifiers Quals;
348 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
349 if (!Context.hasSameType(T, UnqualT)) {
350 T = UnqualT;
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +0000351 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take();
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000352 }
353 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000354
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000355 // If this is an unevaluated operand, clear out the set of
356 // declaration references we have been computing and eliminate any
357 // temporaries introduced in its computation.
358 if (isUnevaluatedOperand)
359 ExprEvalContexts.back().Context = Unevaluated;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000360
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000361 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCall9ae2f072010-08-23 23:25:46 +0000362 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000363 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000364}
365
366/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCall60d7b3a2010-08-24 06:29:42 +0000367ExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000368Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
369 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000370 // Find the std::type_info type.
Sebastian Redlce0682f2011-03-31 19:29:24 +0000371 if (!getStdNamespace())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000372 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000373
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000374 if (!CXXTypeInfoDecl) {
375 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
376 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
377 LookupQualifiedName(R, getStdNamespace());
378 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
379 if (!CXXTypeInfoDecl)
380 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
381 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000382
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000383 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000384
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000385 if (isType) {
386 // The operand is a type; handle it as such.
387 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +0000388 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
389 &TInfo);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000390 if (T.isNull())
391 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000392
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000393 if (!TInfo)
394 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000395
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000396 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000397 }
Mike Stump1eb44332009-09-09 15:08:12 +0000398
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000399 // The operand is an expression.
John McCall9ae2f072010-08-23 23:25:46 +0000400 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000401}
402
Francois Pichet6915c522010-12-27 01:32:00 +0000403/// Retrieve the UuidAttr associated with QT.
404static UuidAttr *GetUuidAttrOfType(QualType QT) {
405 // Optionally remove one level of pointer, reference or array indirection.
John McCallf4c73712011-01-19 06:33:43 +0000406 const Type *Ty = QT.getTypePtr();;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000407 if (QT->isPointerType() || QT->isReferenceType())
408 Ty = QT->getPointeeType().getTypePtr();
409 else if (QT->isArrayType())
410 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
411
Francois Pichet8db75a22011-05-08 10:02:20 +0000412 // Loop all record redeclaration looking for an uuid attribute.
Francois Pichet6915c522010-12-27 01:32:00 +0000413 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Francois Pichet8db75a22011-05-08 10:02:20 +0000414 for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(),
415 E = RD->redecls_end(); I != E; ++I) {
416 if (UuidAttr *Uuid = I->getAttr<UuidAttr>())
Francois Pichet6915c522010-12-27 01:32:00 +0000417 return Uuid;
Francois Pichet6915c522010-12-27 01:32:00 +0000418 }
Francois Pichet8db75a22011-05-08 10:02:20 +0000419
Francois Pichet6915c522010-12-27 01:32:00 +0000420 return 0;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000421}
422
Francois Pichet01b7c302010-09-08 12:20:18 +0000423/// \brief Build a Microsoft __uuidof expression with a type operand.
424ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
425 SourceLocation TypeidLoc,
426 TypeSourceInfo *Operand,
427 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000428 if (!Operand->getType()->isDependentType()) {
429 if (!GetUuidAttrOfType(Operand->getType()))
430 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
431 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000432
Francois Pichet01b7c302010-09-08 12:20:18 +0000433 // FIXME: add __uuidof semantic analysis for type operand.
434 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
435 Operand,
436 SourceRange(TypeidLoc, RParenLoc)));
437}
438
439/// \brief Build a Microsoft __uuidof expression with an expression operand.
440ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
441 SourceLocation TypeidLoc,
442 Expr *E,
443 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000444 if (!E->getType()->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000445 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichet6915c522010-12-27 01:32:00 +0000446 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
447 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
448 }
449 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet01b7c302010-09-08 12:20:18 +0000450 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
451 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000452 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet01b7c302010-09-08 12:20:18 +0000453}
454
455/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
456ExprResult
457Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
458 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000459 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet01b7c302010-09-08 12:20:18 +0000460 if (!MSVCGuidDecl) {
461 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
462 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
463 LookupQualifiedName(R, Context.getTranslationUnitDecl());
464 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
465 if (!MSVCGuidDecl)
466 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000467 }
468
Francois Pichet01b7c302010-09-08 12:20:18 +0000469 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000470
Francois Pichet01b7c302010-09-08 12:20:18 +0000471 if (isType) {
472 // The operand is a type; handle it as such.
473 TypeSourceInfo *TInfo = 0;
474 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
475 &TInfo);
476 if (T.isNull())
477 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000478
Francois Pichet01b7c302010-09-08 12:20:18 +0000479 if (!TInfo)
480 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
481
482 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
483 }
484
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000485 // The operand is an expression.
Francois Pichet01b7c302010-09-08 12:20:18 +0000486 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
487}
488
Steve Naroff1b273c42007-09-16 14:56:35 +0000489/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCall60d7b3a2010-08-24 06:29:42 +0000490ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000491Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000492 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000493 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000494 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
495 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000496}
Chris Lattner50dd2892008-02-26 00:51:44 +0000497
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000498/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCall60d7b3a2010-08-24 06:29:42 +0000499ExprResult
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000500Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
501 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
502}
503
Chris Lattner50dd2892008-02-26 00:51:44 +0000504/// ActOnCXXThrow - Parse throw expressions.
John McCall60d7b3a2010-08-24 06:29:42 +0000505ExprResult
Douglas Gregorbca01b42011-07-06 22:04:06 +0000506Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
507 bool IsThrownVarInScope = false;
508 if (Ex) {
509 // C++0x [class.copymove]p31:
510 // When certain criteria are met, an implementation is allowed to omit the
511 // copy/move construction of a class object [...]
512 //
513 // - in a throw-expression, when the operand is the name of a
514 // non-volatile automatic object (other than a function or catch-
515 // clause parameter) whose scope does not extend beyond the end of the
516 // innermost enclosing try-block (if there is one), the copy/move
517 // operation from the operand to the exception object (15.1) can be
518 // omitted by constructing the automatic object directly into the
519 // exception object
520 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
521 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
522 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
523 for( ; S; S = S->getParent()) {
524 if (S->isDeclScope(Var)) {
525 IsThrownVarInScope = true;
526 break;
527 }
528
529 if (S->getFlags() &
530 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
531 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
532 Scope::TryScope))
533 break;
534 }
535 }
536 }
537 }
538
539 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
540}
541
542ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
543 bool IsThrownVarInScope) {
Anders Carlsson729b8532011-02-23 03:46:46 +0000544 // Don't report an error if 'throw' is used in system headers.
Anders Carlsson15348ae2011-02-28 02:27:16 +0000545 if (!getLangOptions().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +0000546 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb1fba312011-02-19 21:53:09 +0000547 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Douglas Gregorbca01b42011-07-06 22:04:06 +0000548
John Wiegley429bb272011-04-08 18:41:53 +0000549 if (Ex && !Ex->isTypeDependent()) {
Douglas Gregorbca01b42011-07-06 22:04:06 +0000550 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
John Wiegley429bb272011-04-08 18:41:53 +0000551 if (ExRes.isInvalid())
552 return ExprError();
553 Ex = ExRes.take();
554 }
Douglas Gregorbca01b42011-07-06 22:04:06 +0000555
556 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
557 IsThrownVarInScope));
Sebastian Redl972041f2009-04-27 20:27:31 +0000558}
559
560/// CheckCXXThrowOperand - Validate the operand of a throw.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000561ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
562 bool IsThrownVarInScope) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000563 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000564 // A throw-expression initializes a temporary object, called the exception
565 // object, the type of which is determined by removing any top-level
566 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000567 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor154fe982009-12-23 22:04:40 +0000568 // or "pointer to function returning T", [...]
569 if (E->getType().hasQualifiers())
John Wiegley429bb272011-04-08 18:41:53 +0000570 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +0000571 E->getValueKind()).take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000572
John Wiegley429bb272011-04-08 18:41:53 +0000573 ExprResult Res = DefaultFunctionArrayConversion(E);
574 if (Res.isInvalid())
575 return ExprError();
576 E = Res.take();
Sebastian Redl972041f2009-04-27 20:27:31 +0000577
578 // If the type of the exception would be an incomplete type or a pointer
579 // to an incomplete type other than (cv) void the program is ill-formed.
580 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000581 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000582 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000583 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000584 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000585 }
586 if (!isPointer || !Ty->isVoidType()) {
587 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000588 PDiag(isPointer ? diag::err_throw_incomplete_ptr
589 : diag::err_throw_incomplete)
590 << E->getSourceRange()))
John Wiegley429bb272011-04-08 18:41:53 +0000591 return ExprError();
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000592
Douglas Gregorbf422f92010-04-15 18:05:39 +0000593 if (RequireNonAbstractType(ThrowLoc, E->getType(),
594 PDiag(diag::err_throw_abstract_type)
595 << E->getSourceRange()))
John Wiegley429bb272011-04-08 18:41:53 +0000596 return ExprError();
Sebastian Redl972041f2009-04-27 20:27:31 +0000597 }
598
John McCallac418162010-04-22 01:10:34 +0000599 // Initialize the exception result. This implicitly weeds out
600 // abstract types or types with inaccessible copy constructors.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000601
602 // C++0x [class.copymove]p31:
603 // When certain criteria are met, an implementation is allowed to omit the
604 // copy/move construction of a class object [...]
605 //
606 // - in a throw-expression, when the operand is the name of a
607 // non-volatile automatic object (other than a function or catch-clause
608 // parameter) whose scope does not extend beyond the end of the
609 // innermost enclosing try-block (if there is one), the copy/move
610 // operation from the operand to the exception object (15.1) can be
611 // omitted by constructing the automatic object directly into the
612 // exception object
613 const VarDecl *NRVOVariable = 0;
614 if (IsThrownVarInScope)
615 NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
616
John McCallac418162010-04-22 01:10:34 +0000617 InitializedEntity Entity =
Douglas Gregor72dfa272011-01-21 22:46:35 +0000618 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
Douglas Gregorbca01b42011-07-06 22:04:06 +0000619 /*NRVO=*/NRVOVariable != 0);
John Wiegley429bb272011-04-08 18:41:53 +0000620 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregorbca01b42011-07-06 22:04:06 +0000621 QualType(), E,
622 IsThrownVarInScope);
John McCallac418162010-04-22 01:10:34 +0000623 if (Res.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000624 return ExprError();
625 E = Res.take();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000626
Eli Friedman5ed9b932010-06-03 20:39:03 +0000627 // If the exception has class type, we need additional handling.
628 const RecordType *RecordTy = Ty->getAs<RecordType>();
629 if (!RecordTy)
John Wiegley429bb272011-04-08 18:41:53 +0000630 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000631 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
632
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000633 // If we are throwing a polymorphic class type or pointer thereof,
634 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000635 MarkVTableUsed(ThrowLoc, RD);
636
Eli Friedman98efb9f2010-10-12 20:32:36 +0000637 // If a pointer is thrown, the referenced object will not be destroyed.
638 if (isPointer)
John Wiegley429bb272011-04-08 18:41:53 +0000639 return Owned(E);
Eli Friedman98efb9f2010-10-12 20:32:36 +0000640
Eli Friedman5ed9b932010-06-03 20:39:03 +0000641 // If the class has a non-trivial destructor, we must be able to call it.
642 if (RD->hasTrivialDestructor())
John Wiegley429bb272011-04-08 18:41:53 +0000643 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000644
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000645 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +0000646 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman5ed9b932010-06-03 20:39:03 +0000647 if (!Destructor)
John Wiegley429bb272011-04-08 18:41:53 +0000648 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000649
650 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
651 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000652 PDiag(diag::err_access_dtor_exception) << Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000653 return Owned(E);
Chris Lattner50dd2892008-02-26 00:51:44 +0000654}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000655
Douglas Gregor341350e2011-10-18 16:47:30 +0000656QualType Sema::getCurrentThisType(bool Capture) {
John McCall5808ce42011-02-03 08:15:49 +0000657 // Ignore block scopes: we can capture through them.
658 // Ignore nested enum scopes: we'll diagnose non-constant expressions
659 // where they're invalid, and other uses are legitimate.
660 // Don't ignore nested class scopes: you can't use 'this' in a local class.
John McCall469a1eb2011-02-02 13:00:07 +0000661 DeclContext *DC = CurContext;
Richard Smith7a614d82011-06-11 17:19:42 +0000662 unsigned NumBlocks = 0;
John McCall5808ce42011-02-03 08:15:49 +0000663 while (true) {
Richard Smith7a614d82011-06-11 17:19:42 +0000664 if (isa<BlockDecl>(DC)) {
665 DC = cast<BlockDecl>(DC)->getDeclContext();
666 ++NumBlocks;
667 } else if (isa<EnumDecl>(DC))
668 DC = cast<EnumDecl>(DC)->getDeclContext();
John McCall5808ce42011-02-03 08:15:49 +0000669 else break;
670 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000671
Richard Smith7a614d82011-06-11 17:19:42 +0000672 QualType ThisTy;
673 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
674 if (method && method->isInstance())
675 ThisTy = method->getThisType(Context);
676 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
677 // C++0x [expr.prim]p4:
678 // Otherwise, if a member-declarator declares a non-static data member
679 // of a class X, the expression this is a prvalue of type "pointer to X"
680 // within the optional brace-or-equal-initializer.
681 Scope *S = getScopeForContext(DC);
682 if (!S || S->getFlags() & Scope::ThisScope)
683 ThisTy = Context.getPointerType(Context.getRecordType(RD));
684 }
John McCall469a1eb2011-02-02 13:00:07 +0000685
Douglas Gregor341350e2011-10-18 16:47:30 +0000686 if (!Capture || ThisTy.isNull())
687 return ThisTy;
688
Richard Smith7a614d82011-06-11 17:19:42 +0000689 // Mark that we're closing on 'this' in all the block scopes we ignored.
Douglas Gregor341350e2011-10-18 16:47:30 +0000690 for (unsigned idx = FunctionScopes.size() - 1;
691 NumBlocks; --idx, --NumBlocks)
692 cast<BlockScopeInfo>(FunctionScopes[idx])->CapturesCXXThis = true;
John McCall469a1eb2011-02-02 13:00:07 +0000693
Richard Smith7a614d82011-06-11 17:19:42 +0000694 return ThisTy;
John McCall5808ce42011-02-03 08:15:49 +0000695}
696
Richard Smith7a614d82011-06-11 17:19:42 +0000697ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCall5808ce42011-02-03 08:15:49 +0000698 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
699 /// is a non-lvalue expression whose value is the address of the object for
700 /// which the function is called.
701
Douglas Gregor341350e2011-10-18 16:47:30 +0000702 QualType ThisTy = getCurrentThisType();
Richard Smith7a614d82011-06-11 17:19:42 +0000703 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCall5808ce42011-02-03 08:15:49 +0000704
Richard Smith7a614d82011-06-11 17:19:42 +0000705 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000706}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000707
John McCall60d7b3a2010-08-24 06:29:42 +0000708ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000709Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000710 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000711 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000712 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000713 if (!TypeRep)
714 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000715
John McCall9d125032010-01-15 18:39:57 +0000716 TypeSourceInfo *TInfo;
717 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
718 if (!TInfo)
719 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000720
721 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
722}
723
724/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
725/// Can be interpreted either as function-style casting ("int(x)")
726/// or class type construction ("ClassType(x,y,z)")
727/// or creation of a value-initialized type ("int()").
728ExprResult
729Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
730 SourceLocation LParenLoc,
731 MultiExprArg exprs,
732 SourceLocation RParenLoc) {
733 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000734 unsigned NumExprs = exprs.size();
735 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000736 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000737 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
738
Sebastian Redlf53597f2009-03-15 17:47:39 +0000739 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000740 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000741 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000742
Douglas Gregorab6677e2010-09-08 00:15:04 +0000743 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000744 LParenLoc,
745 Exprs, NumExprs,
746 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000747 }
748
Anders Carlssonbb60a502009-08-27 03:53:50 +0000749 if (Ty->isArrayType())
750 return ExprError(Diag(TyBeginLoc,
751 diag::err_value_init_for_array_type) << FullRange);
752 if (!Ty->isVoidType() &&
753 RequireCompleteType(TyBeginLoc, Ty,
754 PDiag(diag::err_invalid_incomplete_type_use)
755 << FullRange))
756 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000757
Anders Carlssonbb60a502009-08-27 03:53:50 +0000758 if (RequireNonAbstractType(TyBeginLoc, Ty,
759 diag::err_allocation_of_abstract_type))
760 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000761
762
Douglas Gregor506ae412009-01-16 18:33:17 +0000763 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000764 // If the expression list is a single expression, the type conversion
765 // expression is equivalent (in definedness, and if defined in meaning) to the
766 // corresponding cast expression.
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000767 if (NumExprs == 1) {
John McCallb45ae252011-10-05 07:41:44 +0000768 Expr *Arg = Exprs[0];
Anders Carlsson0aebc812009-09-09 21:33:21 +0000769 exprs.release();
John McCallb45ae252011-10-05 07:41:44 +0000770 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000771 }
772
Douglas Gregor19311e72010-09-08 21:40:08 +0000773 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
774 InitializationKind Kind
775 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
776 LParenLoc, RParenLoc)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000777 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor19311e72010-09-08 21:40:08 +0000778 LParenLoc, RParenLoc);
779 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
780 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000781
Douglas Gregor19311e72010-09-08 21:40:08 +0000782 // FIXME: Improve AST representation?
783 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000784}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000785
John McCall6ec278d2011-01-27 09:37:56 +0000786/// doesUsualArrayDeleteWantSize - Answers whether the usual
787/// operator delete[] for the given type has a size_t parameter.
788static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
789 QualType allocType) {
790 const RecordType *record =
791 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
792 if (!record) return false;
793
794 // Try to find an operator delete[] in class scope.
795
796 DeclarationName deleteName =
797 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
798 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
799 S.LookupQualifiedName(ops, record->getDecl());
800
801 // We're just doing this for information.
802 ops.suppressDiagnostics();
803
804 // Very likely: there's no operator delete[].
805 if (ops.empty()) return false;
806
807 // If it's ambiguous, it should be illegal to call operator delete[]
808 // on this thing, so it doesn't matter if we allocate extra space or not.
809 if (ops.isAmbiguous()) return false;
810
811 LookupResult::Filter filter = ops.makeFilter();
812 while (filter.hasNext()) {
813 NamedDecl *del = filter.next()->getUnderlyingDecl();
814
815 // C++0x [basic.stc.dynamic.deallocation]p2:
816 // A template instance is never a usual deallocation function,
817 // regardless of its signature.
818 if (isa<FunctionTemplateDecl>(del)) {
819 filter.erase();
820 continue;
821 }
822
823 // C++0x [basic.stc.dynamic.deallocation]p2:
824 // If class T does not declare [an operator delete[] with one
825 // parameter] but does declare a member deallocation function
826 // named operator delete[] with exactly two parameters, the
827 // second of which has type std::size_t, then this function
828 // is a usual deallocation function.
829 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
830 filter.erase();
831 continue;
832 }
833 }
834 filter.done();
835
836 if (!ops.isSingleResult()) return false;
837
838 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
839 return (del->getNumParams() == 2);
840}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000841
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000842/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
843/// @code new (memory) int[size][4] @endcode
844/// or
845/// @code ::new Foo(23, "hello") @endcode
846/// For the interpretation of this heap of arguments, consult the base version.
John McCall60d7b3a2010-08-24 06:29:42 +0000847ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000848Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000849 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000850 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000851 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000852 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000853 SourceLocation ConstructorRParen) {
Richard Smith34b41d92011-02-20 03:19:35 +0000854 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
855
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000856 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000857 // If the specified type is an array, unwrap it and save the expression.
858 if (D.getNumTypeObjects() > 0 &&
859 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
860 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith34b41d92011-02-20 03:19:35 +0000861 if (TypeContainsAuto)
862 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
863 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000864 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000865 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
866 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000867 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000868 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
869 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000870
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000871 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000872 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000873 }
874
Douglas Gregor043cad22009-09-11 00:18:58 +0000875 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000876 if (ArraySize) {
877 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000878 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
879 break;
880
881 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
882 if (Expr *NumElts = (Expr *)Array.NumElts) {
883 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
884 !NumElts->isIntegerConstantExpr(Context)) {
885 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
886 << NumElts->getSourceRange();
887 return ExprError();
888 }
889 }
890 }
891 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000892
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +0000893 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
John McCallbf1a0282010-06-04 23:28:52 +0000894 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000895 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000896 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000897
Mike Stump1eb44332009-09-09 15:08:12 +0000898 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000899 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000900 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000901 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000902 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000903 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000904 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000905 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000906 ConstructorLParen,
907 move(ConstructorArgs),
Richard Smith34b41d92011-02-20 03:19:35 +0000908 ConstructorRParen,
909 TypeContainsAuto);
Douglas Gregor3433cf72009-05-21 00:00:09 +0000910}
911
John McCall60d7b3a2010-08-24 06:29:42 +0000912ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000913Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
914 SourceLocation PlacementLParen,
915 MultiExprArg PlacementArgs,
916 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000917 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000918 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000919 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000920 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000921 SourceLocation ConstructorLParen,
922 MultiExprArg ConstructorArgs,
Richard Smith34b41d92011-02-20 03:19:35 +0000923 SourceLocation ConstructorRParen,
924 bool TypeMayContainAuto) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000925 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000926
Richard Smith34b41d92011-02-20 03:19:35 +0000927 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
928 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
929 if (ConstructorArgs.size() == 0)
930 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
931 << AllocType << TypeRange);
932 if (ConstructorArgs.size() != 1) {
933 Expr *FirstBad = ConstructorArgs.get()[1];
934 return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
935 diag::err_auto_new_ctor_multiple_expressions)
936 << AllocType << TypeRange);
937 }
Richard Smitha085da82011-03-17 16:11:59 +0000938 TypeSourceInfo *DeducedType = 0;
939 if (!DeduceAutoType(AllocTypeInfo, ConstructorArgs.get()[0], DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +0000940 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
941 << AllocType
942 << ConstructorArgs.get()[0]->getType()
943 << TypeRange
944 << ConstructorArgs.get()[0]->getSourceRange());
Richard Smitha085da82011-03-17 16:11:59 +0000945 if (!DeducedType)
946 return ExprError();
Richard Smith34b41d92011-02-20 03:19:35 +0000947
Richard Smitha085da82011-03-17 16:11:59 +0000948 AllocTypeInfo = DeducedType;
949 AllocType = AllocTypeInfo->getType();
Richard Smith34b41d92011-02-20 03:19:35 +0000950 }
951
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000952 // Per C++0x [expr.new]p5, the type being constructed may be a
953 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +0000954 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000955 if (const ConstantArrayType *Array
956 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000957 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
958 Context.getSizeType(),
959 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000960 AllocType = Array->getElementType();
961 }
962 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000963
Douglas Gregora0750762010-10-06 16:00:31 +0000964 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
965 return ExprError();
966
John McCallf85e1932011-06-15 23:02:42 +0000967 // In ARC, infer 'retaining' for the allocated
968 if (getLangOptions().ObjCAutoRefCount &&
969 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
970 AllocType->isObjCLifetimeType()) {
971 AllocType = Context.getLifetimeQualifiedType(AllocType,
972 AllocType->getObjCARCImplicitLifetime());
973 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000974
John McCallf85e1932011-06-15 23:02:42 +0000975 QualType ResultType = Context.getPointerType(AllocType);
976
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000977 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
978 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000979 if (ArraySize && !ArraySize->isTypeDependent()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000980
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000981 QualType SizeType = ArraySize->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000982
Richard Smithebaf0e62011-10-18 20:49:44 +0000983 ExprResult ConvertedSize = ConvertToIntegralOrEnumerationType(
984 StartLoc, ArraySize,
985 PDiag(diag::err_array_size_not_integral),
986 PDiag(diag::err_array_size_incomplete_type)
987 << ArraySize->getSourceRange(),
988 PDiag(diag::err_array_size_explicit_conversion),
989 PDiag(diag::note_array_size_conversion),
990 PDiag(diag::err_array_size_ambiguous_conversion),
991 PDiag(diag::note_array_size_conversion),
992 PDiag(getLangOptions().CPlusPlus0x ?
993 diag::warn_cxx98_compat_array_size_conversion :
994 diag::ext_array_size_conversion));
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000995 if (ConvertedSize.isInvalid())
996 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000997
John McCall9ae2f072010-08-23 23:25:46 +0000998 ArraySize = ConvertedSize.take();
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000999 SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001000 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +00001001 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001002
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001003 // Let's see if this is a constant < 0. If so, we reject it out of hand.
1004 // We don't care about special rules, so we tell the machinery it's not
1005 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +00001006 if (!ArraySize->isValueDependent()) {
1007 llvm::APSInt Value;
1008 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
1009 if (Value < llvm::APSInt(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001010 llvm::APInt::getNullValue(Value.getBitWidth()),
Anders Carlssonac18b2e2009-09-23 00:37:25 +00001011 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +00001012 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +00001013 diag::err_typecheck_negative_array_size)
Sebastian Redlf53597f2009-03-15 17:47:39 +00001014 << ArraySize->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001015
Douglas Gregor2767ce22010-08-18 00:39:00 +00001016 if (!AllocType->isDependentType()) {
1017 unsigned ActiveSizeBits
1018 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1019 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001020 Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +00001021 diag::err_array_too_large)
1022 << Value.toString(10)
1023 << ArraySize->getSourceRange();
1024 return ExprError();
1025 }
1026 }
Douglas Gregor4bd40312010-07-13 15:54:32 +00001027 } else if (TypeIdParens.isValid()) {
1028 // Can't have dynamic array size when the type-id is in parentheses.
1029 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1030 << ArraySize->getSourceRange()
1031 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1032 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001033
Douglas Gregor4bd40312010-07-13 15:54:32 +00001034 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +00001035 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001036 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001037
John McCallf85e1932011-06-15 23:02:42 +00001038 // ARC: warn about ABI issues.
1039 if (getLangOptions().ObjCAutoRefCount) {
1040 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1041 if (BaseAllocType.hasStrongOrWeakObjCLifetime())
1042 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1043 << 0 << BaseAllocType;
1044 }
1045
John McCall7d166272011-05-15 07:14:44 +00001046 // Note that we do *not* convert the argument in any way. It can
1047 // be signed, larger than size_t, whatever.
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001048 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001049
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001050 FunctionDecl *OperatorNew = 0;
1051 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001052 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
1053 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001054
Sebastian Redl28507842009-02-26 14:39:58 +00001055 if (!AllocType->isDependentType() &&
1056 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
1057 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +00001058 SourceRange(PlacementLParen, PlacementRParen),
1059 UseGlobal, AllocType, ArraySize, PlaceArgs,
1060 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +00001061 return ExprError();
John McCall6ec278d2011-01-27 09:37:56 +00001062
1063 // If this is an array allocation, compute whether the usual array
1064 // deallocation function for the type has a size_t parameter.
1065 bool UsualArrayDeleteWantsSize = false;
1066 if (ArraySize && !AllocType->isDependentType())
1067 UsualArrayDeleteWantsSize
1068 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1069
Chris Lattner5f9e2722011-07-23 10:55:15 +00001070 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001071 if (OperatorNew) {
1072 // Add default arguments, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001073 const FunctionProtoType *Proto =
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001074 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001075 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00001076 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001077
Anders Carlsson28e94832010-05-03 02:07:56 +00001078 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001079 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlsson28e94832010-05-03 02:07:56 +00001080 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001081 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001082
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001083 NumPlaceArgs = AllPlaceArgs.size();
1084 if (NumPlaceArgs > 0)
1085 PlaceArgs = &AllPlaceArgs[0];
1086 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001087
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001088 bool Init = ConstructorLParen.isValid();
1089 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001090 CXXConstructorDecl *Constructor = 0;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001091 bool HadMultipleCandidates = false;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001092 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
1093 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +00001094 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +00001095
Anders Carlsson48c95012010-05-03 15:45:23 +00001096 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +00001097 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +00001098 SourceRange InitRange(ConsArgs[0]->getLocStart(),
1099 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001100
Anders Carlsson48c95012010-05-03 15:45:23 +00001101 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1102 return ExprError();
1103 }
1104
Douglas Gregor99a2e602009-12-16 01:38:02 +00001105 if (!AllocType->isDependentType() &&
1106 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
1107 // C++0x [expr.new]p15:
1108 // A new-expression that creates an object of type T initializes that
1109 // object as follows:
1110 InitializationKind Kind
1111 // - If the new-initializer is omitted, the object is default-
1112 // initialized (8.5); if no initialization is performed,
1113 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001114 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001115 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor99a2e602009-12-16 01:38:02 +00001116 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001117 : InitializationKind::CreateDirect(TypeRange.getBegin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001118 ConstructorLParen,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001119 ConstructorRParen);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001120
Douglas Gregor99a2e602009-12-16 01:38:02 +00001121 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00001122 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001123 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001124 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001125 move(ConstructorArgs));
1126 if (FullInit.isInvalid())
1127 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001128
1129 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor99a2e602009-12-16 01:38:02 +00001130 // constructor call, which CXXNewExpr handles directly.
1131 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1132 if (CXXBindTemporaryExpr *Binder
1133 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1134 FullInitExpr = Binder->getSubExpr();
1135 if (CXXConstructExpr *Construct
1136 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1137 Constructor = Construct->getConstructor();
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001138 HadMultipleCandidates = Construct->hadMultipleCandidates();
Douglas Gregor99a2e602009-12-16 01:38:02 +00001139 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1140 AEnd = Construct->arg_end();
1141 A != AEnd; ++A)
John McCall3fa5cae2010-10-26 07:05:15 +00001142 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001143 } else {
1144 // Take the converted initializer.
1145 ConvertedConstructorArgs.push_back(FullInit.release());
1146 }
1147 } else {
1148 // No initialization required.
1149 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001150
Douglas Gregor99a2e602009-12-16 01:38:02 +00001151 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001152 NumConsArgs = ConvertedConstructorArgs.size();
1153 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001154 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001155
Douglas Gregor6d908702010-02-26 05:06:18 +00001156 // Mark the new and delete operators as referenced.
1157 if (OperatorNew)
1158 MarkDeclarationReferenced(StartLoc, OperatorNew);
1159 if (OperatorDelete)
1160 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1161
John McCall84ff0fc2011-07-13 20:12:57 +00001162 // C++0x [expr.new]p17:
1163 // If the new expression creates an array of objects of class type,
1164 // access and ambiguity control are done for the destructor.
1165 if (ArraySize && Constructor) {
1166 if (CXXDestructorDecl *dtor = LookupDestructor(Constructor->getParent())) {
1167 MarkDeclarationReferenced(StartLoc, dtor);
1168 CheckDestructorAccess(StartLoc, dtor,
1169 PDiag(diag::err_access_dtor)
1170 << Context.getBaseElementType(AllocType));
1171 }
1172 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001173
Sebastian Redlf53597f2009-03-15 17:47:39 +00001174 PlacementArgs.release();
1175 ConstructorArgs.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001176
Ted Kremenekad7fe862010-02-11 22:51:03 +00001177 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001178 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001179 ArraySize, Constructor, Init,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001180 ConsArgs, NumConsArgs,
1181 HadMultipleCandidates,
1182 OperatorDelete,
John McCall6ec278d2011-01-27 09:37:56 +00001183 UsualArrayDeleteWantsSize,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001184 ResultType, AllocTypeInfo,
1185 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001186 Init ? ConstructorRParen :
Chandler Carruth428edaf2010-10-25 08:47:36 +00001187 TypeRange.getEnd(),
1188 ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001189}
1190
1191/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1192/// in a new-expression.
1193/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +00001194bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00001195 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001196 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1197 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +00001198 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001199 return Diag(Loc, diag::err_bad_new_type)
1200 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001201 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001202 return Diag(Loc, diag::err_bad_new_type)
1203 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001204 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +00001205 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001206 PDiag(diag::err_new_incomplete_type)
1207 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001208 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +00001209 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +00001210 diag::err_allocation_of_abstract_type))
1211 return true;
Douglas Gregora0750762010-10-06 16:00:31 +00001212 else if (AllocType->isVariablyModifiedType())
1213 return Diag(Loc, diag::err_variably_modified_new_type)
1214 << AllocType;
Douglas Gregor5666d362011-04-15 19:46:20 +00001215 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1216 return Diag(Loc, diag::err_address_space_qualified_new)
1217 << AllocType.getUnqualifiedType() << AddressSpace;
John McCallf85e1932011-06-15 23:02:42 +00001218 else if (getLangOptions().ObjCAutoRefCount) {
1219 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1220 QualType BaseAllocType = Context.getBaseElementType(AT);
1221 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1222 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001223 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001224 << BaseAllocType;
1225 }
1226 }
Douglas Gregor5666d362011-04-15 19:46:20 +00001227
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001228 return false;
1229}
1230
Douglas Gregor6d908702010-02-26 05:06:18 +00001231/// \brief Determine whether the given function is a non-placement
1232/// deallocation function.
1233static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1234 if (FD->isInvalidDecl())
1235 return false;
1236
1237 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1238 return Method->isUsualDeallocationFunction();
1239
1240 return ((FD->getOverloadedOperator() == OO_Delete ||
1241 FD->getOverloadedOperator() == OO_Array_Delete) &&
1242 FD->getNumParams() == 1);
1243}
1244
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001245/// FindAllocationFunctions - Finds the overloads of operator new and delete
1246/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001247bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1248 bool UseGlobal, QualType AllocType,
1249 bool IsArray, Expr **PlaceArgs,
1250 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001251 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +00001252 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001253 // --- Choosing an allocation function ---
1254 // C++ 5.3.4p8 - 14 & 18
1255 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1256 // in the scope of the allocated class.
1257 // 2) If an array size is given, look for operator new[], else look for
1258 // operator new.
1259 // 3) The first argument is always size_t. Append the arguments from the
1260 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001261
Chris Lattner5f9e2722011-07-23 10:55:15 +00001262 SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001263 // We don't care about the actual value of this argument.
1264 // FIXME: Should the Sema create the expression and embed it in the syntax
1265 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001266 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001267 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssond67c4c32009-08-16 20:29:29 +00001268 Context.getSizeType(),
1269 SourceLocation());
1270 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001271 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1272
Douglas Gregor6d908702010-02-26 05:06:18 +00001273 // C++ [expr.new]p8:
1274 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001275 // function's name is operator new and the deallocation function's
Douglas Gregor6d908702010-02-26 05:06:18 +00001276 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001277 // type, the allocation function's name is operator new[] and the
1278 // deallocation function's name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001279 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1280 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001281 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1282 IsArray ? OO_Array_Delete : OO_Delete);
1283
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001284 QualType AllocElemType = Context.getBaseElementType(AllocType);
1285
1286 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001287 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001288 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001289 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001290 AllocArgs.size(), Record, /*AllowMissing=*/true,
1291 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001292 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001293 }
1294 if (!OperatorNew) {
1295 // Didn't find a member overload. Look for a global one.
1296 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001297 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001298 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001299 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1300 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001301 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001302 }
1303
John McCall9c82afc2010-04-20 02:18:25 +00001304 // We don't need an operator delete if we're running under
1305 // -fno-exceptions.
1306 if (!getLangOptions().Exceptions) {
1307 OperatorDelete = 0;
1308 return false;
1309 }
1310
Anders Carlssond9583892009-05-31 20:26:12 +00001311 // FindAllocationOverload can change the passed in arguments, so we need to
1312 // copy them back.
1313 if (NumPlaceArgs > 0)
1314 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001315
Douglas Gregor6d908702010-02-26 05:06:18 +00001316 // C++ [expr.new]p19:
1317 //
1318 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001319 // deallocation function's name is looked up in the global
Douglas Gregor6d908702010-02-26 05:06:18 +00001320 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001321 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6d908702010-02-26 05:06:18 +00001322 // the scope of T. If this lookup fails to find the name, or if
1323 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001324 // deallocation function's name is looked up in the global scope.
Douglas Gregor6d908702010-02-26 05:06:18 +00001325 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001326 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001327 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001328 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001329 LookupQualifiedName(FoundDelete, RD);
1330 }
John McCall90c8c572010-03-18 08:19:33 +00001331 if (FoundDelete.isAmbiguous())
1332 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001333
1334 if (FoundDelete.empty()) {
1335 DeclareGlobalNewDelete();
1336 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1337 }
1338
1339 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001340
Chris Lattner5f9e2722011-07-23 10:55:15 +00001341 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCall9aa472c2010-03-19 07:35:19 +00001342
John McCalledeb6c92010-09-14 21:34:24 +00001343 // Whether we're looking for a placement operator delete is dictated
1344 // by whether we selected a placement operator new, not by whether
1345 // we had explicit placement arguments. This matters for things like
1346 // struct A { void *operator new(size_t, int = 0); ... };
1347 // A *a = new A()
1348 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1349
1350 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001351 // C++ [expr.new]p20:
1352 // A declaration of a placement deallocation function matches the
1353 // declaration of a placement allocation function if it has the
1354 // same number of parameters and, after parameter transformations
1355 // (8.3.5), all parameter types except the first are
1356 // identical. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001357 //
Douglas Gregor6d908702010-02-26 05:06:18 +00001358 // To perform this comparison, we compute the function type that
1359 // the deallocation function should have, and use that type both
1360 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001361 //
1362 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001363 QualType ExpectedFunctionType;
1364 {
1365 const FunctionProtoType *Proto
1366 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001367
Chris Lattner5f9e2722011-07-23 10:55:15 +00001368 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001369 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6d908702010-02-26 05:06:18 +00001370 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1371 ArgTypes.push_back(Proto->getArgType(I));
1372
John McCalle23cf432010-12-14 08:05:40 +00001373 FunctionProtoType::ExtProtoInfo EPI;
1374 EPI.Variadic = Proto->isVariadic();
1375
Douglas Gregor6d908702010-02-26 05:06:18 +00001376 ExpectedFunctionType
1377 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalle23cf432010-12-14 08:05:40 +00001378 ArgTypes.size(), EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001379 }
1380
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001381 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001382 DEnd = FoundDelete.end();
1383 D != DEnd; ++D) {
1384 FunctionDecl *Fn = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001385 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6d908702010-02-26 05:06:18 +00001386 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1387 // Perform template argument deduction to try to match the
1388 // expected function type.
1389 TemplateDeductionInfo Info(Context, StartLoc);
1390 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1391 continue;
1392 } else
1393 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1394
1395 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001396 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001397 }
1398 } else {
1399 // C++ [expr.new]p20:
1400 // [...] Any non-placement deallocation function matches a
1401 // non-placement allocation function. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001402 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001403 DEnd = FoundDelete.end();
1404 D != DEnd; ++D) {
1405 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1406 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001407 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001408 }
1409 }
1410
1411 // C++ [expr.new]p20:
1412 // [...] If the lookup finds a single matching deallocation
1413 // function, that function will be called; otherwise, no
1414 // deallocation function will be called.
1415 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001416 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001417
1418 // C++0x [expr.new]p20:
1419 // If the lookup finds the two-parameter form of a usual
1420 // deallocation function (3.7.4.2) and that function, considered
1421 // as a placement deallocation function, would have been
1422 // selected as a match for the allocation function, the program
1423 // is ill-formed.
1424 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1425 isNonPlacementDeallocationFunction(OperatorDelete)) {
1426 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001427 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001428 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1429 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1430 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001431 } else {
1432 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001433 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001434 }
1435 }
1436
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001437 return false;
1438}
1439
Sebastian Redl7f662392008-12-04 22:20:51 +00001440/// FindAllocationOverload - Find an fitting overload for the allocation
1441/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001442bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1443 DeclarationName Name, Expr** Args,
1444 unsigned NumArgs, DeclContext *Ctx,
Sean Hunt2be7e902011-05-12 22:46:29 +00001445 bool AllowMissing, FunctionDecl *&Operator,
1446 bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001447 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1448 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001449 if (R.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001450 if (AllowMissing || !Diagnose)
Sebastian Redl7f662392008-12-04 22:20:51 +00001451 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001452 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001453 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001454 }
1455
John McCall90c8c572010-03-18 08:19:33 +00001456 if (R.isAmbiguous())
1457 return true;
1458
1459 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001460
John McCall5769d612010-02-08 23:07:23 +00001461 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001462 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001463 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001464 // Even member operator new/delete are implicitly treated as
1465 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001466 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001467
John McCall9aa472c2010-03-19 07:35:19 +00001468 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1469 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001470 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1471 Candidates,
1472 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001473 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001474 }
1475
John McCall9aa472c2010-03-19 07:35:19 +00001476 FunctionDecl *Fn = cast<FunctionDecl>(D);
1477 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001478 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001479 }
1480
1481 // Do the resolution.
1482 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001483 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001484 case OR_Success: {
1485 // Got one!
1486 FunctionDecl *FnDecl = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00001487 MarkDeclarationReferenced(StartLoc, FnDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001488 // The first argument is size_t, and the first parameter must be size_t,
1489 // too. This is checked on declaration and can be assumed. (It can't be
1490 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001491 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001492 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1493 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001494 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1495 FnDecl->getParamDecl(i));
1496
1497 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1498 return true;
1499
John McCall60d7b3a2010-08-24 06:29:42 +00001500 ExprResult Result
Sean Hunt2be7e902011-05-12 22:46:29 +00001501 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001502 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001503 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001504
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001505 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001506 }
1507 Operator = FnDecl;
Sean Hunt2be7e902011-05-12 22:46:29 +00001508 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl,
1509 Diagnose);
Sebastian Redl7f662392008-12-04 22:20:51 +00001510 return false;
1511 }
1512
1513 case OR_No_Viable_Function:
Chandler Carruth361d3802011-06-08 10:26:03 +00001514 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001515 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1516 << Name << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001517 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1518 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001519 return true;
1520
1521 case OR_Ambiguous:
Chandler Carruth361d3802011-06-08 10:26:03 +00001522 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001523 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1524 << Name << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001525 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
1526 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001527 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001528
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001529 case OR_Deleted: {
Chandler Carruth361d3802011-06-08 10:26:03 +00001530 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001531 Diag(StartLoc, diag::err_ovl_deleted_call)
1532 << Best->Function->isDeleted()
1533 << Name
1534 << getDeletedOrUnavailableSuffix(Best->Function)
1535 << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001536 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1537 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001538 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001539 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001540 }
David Blaikieb219cfc2011-09-23 05:06:16 +00001541 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Sebastian Redl7f662392008-12-04 22:20:51 +00001542}
1543
1544
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001545/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1546/// delete. These are:
1547/// @code
Sebastian Redl8999fe12011-03-14 18:08:30 +00001548/// // C++03:
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001549/// void* operator new(std::size_t) throw(std::bad_alloc);
1550/// void* operator new[](std::size_t) throw(std::bad_alloc);
1551/// void operator delete(void *) throw();
1552/// void operator delete[](void *) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001553/// // C++0x:
1554/// void* operator new(std::size_t);
1555/// void* operator new[](std::size_t);
1556/// void operator delete(void *);
1557/// void operator delete[](void *);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001558/// @endcode
Sebastian Redl8999fe12011-03-14 18:08:30 +00001559/// C++0x operator delete is implicitly noexcept.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001560/// Note that the placement and nothrow forms of new are *not* implicitly
1561/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001562void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001563 if (GlobalNewDeleteDeclared)
1564 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001565
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001566 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001567 // [...] The following allocation and deallocation functions (18.4) are
1568 // implicitly declared in global scope in each translation unit of a
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001569 // program
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001570 //
Sebastian Redl8999fe12011-03-14 18:08:30 +00001571 // C++03:
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001572 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001573 // void* operator new[](std::size_t) throw(std::bad_alloc);
1574 // void operator delete(void*) throw();
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001575 // void operator delete[](void*) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001576 // C++0x:
1577 // void* operator new(std::size_t);
1578 // void* operator new[](std::size_t);
1579 // void operator delete(void*);
1580 // void operator delete[](void*);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001581 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001582 // These implicit declarations introduce only the function names operator
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001583 // new, operator new[], operator delete, operator delete[].
1584 //
1585 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1586 // "std" or "bad_alloc" as necessary to form the exception specification.
1587 // However, we do not make these implicit declarations visible to name
1588 // lookup.
Sebastian Redl8999fe12011-03-14 18:08:30 +00001589 // Note that the C++0x versions of operator delete are deallocation functions,
1590 // and thus are implicitly noexcept.
1591 if (!StdBadAlloc && !getLangOptions().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001592 // The "std::bad_alloc" class has not yet been declared, so build it
1593 // implicitly.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001594 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1595 getOrCreateStdNamespace(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001596 SourceLocation(), SourceLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001597 &PP.getIdentifierTable().get("bad_alloc"),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001598 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001599 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001600 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001601
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001602 GlobalNewDeleteDeclared = true;
1603
1604 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1605 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001606 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001607
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001608 DeclareGlobalAllocationFunction(
1609 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001610 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001611 DeclareGlobalAllocationFunction(
1612 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001613 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001614 DeclareGlobalAllocationFunction(
1615 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1616 Context.VoidTy, VoidPtr);
1617 DeclareGlobalAllocationFunction(
1618 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1619 Context.VoidTy, VoidPtr);
1620}
1621
1622/// DeclareGlobalAllocationFunction - Declares a single implicit global
1623/// allocation function if it doesn't already exist.
1624void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001625 QualType Return, QualType Argument,
1626 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001627 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1628
1629 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001630 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001631 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001632 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001633 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001634 // Only look at non-template functions, as it is the predefined,
1635 // non-templated allocation function we are trying to declare here.
1636 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1637 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001638 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001639 Func->getParamDecl(0)->getType().getUnqualifiedType());
1640 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001641 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1642 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001643 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001644 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001645 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001646 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001647 }
1648 }
1649
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001650 QualType BadAllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001651 bool HasBadAllocExceptionSpec
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001652 = (Name.getCXXOverloadedOperator() == OO_New ||
1653 Name.getCXXOverloadedOperator() == OO_Array_New);
Sebastian Redl8999fe12011-03-14 18:08:30 +00001654 if (HasBadAllocExceptionSpec && !getLangOptions().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001655 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001656 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001657 }
John McCalle23cf432010-12-14 08:05:40 +00001658
1659 FunctionProtoType::ExtProtoInfo EPI;
John McCalle23cf432010-12-14 08:05:40 +00001660 if (HasBadAllocExceptionSpec) {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001661 if (!getLangOptions().CPlusPlus0x) {
1662 EPI.ExceptionSpecType = EST_Dynamic;
1663 EPI.NumExceptions = 1;
1664 EPI.Exceptions = &BadAllocType;
1665 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00001666 } else {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001667 EPI.ExceptionSpecType = getLangOptions().CPlusPlus0x ?
1668 EST_BasicNoexcept : EST_DynamicNone;
John McCalle23cf432010-12-14 08:05:40 +00001669 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001670
John McCalle23cf432010-12-14 08:05:40 +00001671 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001672 FunctionDecl *Alloc =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001673 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1674 SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001675 FnType, /*TInfo=*/0, SC_None,
1676 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001677 Alloc->setImplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001678
Nuno Lopesfc284482009-12-16 16:59:22 +00001679 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001680 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001681
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001682 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001683 SourceLocation(), 0,
1684 Argument, /*TInfo=*/0,
1685 SC_None, SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00001686 Alloc->setParams(Param);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001687
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001688 // FIXME: Also add this declaration to the IdentifierResolver, but
1689 // make sure it is at the end of the chain to coincide with the
1690 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001691 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001692}
1693
Anders Carlsson78f74552009-11-15 18:45:20 +00001694bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1695 DeclarationName Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001696 FunctionDecl* &Operator, bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001697 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001698 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001699 LookupQualifiedName(Found, RD);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001700
John McCalla24dc2e2009-11-17 02:14:36 +00001701 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001702 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001703
Chandler Carruth23893242010-06-28 00:30:51 +00001704 Found.suppressDiagnostics();
1705
Chris Lattner5f9e2722011-07-23 10:55:15 +00001706 SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001707 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1708 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001709 NamedDecl *ND = (*F)->getUnderlyingDecl();
1710
1711 // Ignore template operator delete members from the check for a usual
1712 // deallocation function.
1713 if (isa<FunctionTemplateDecl>(ND))
1714 continue;
1715
1716 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001717 Matches.push_back(F.getPair());
1718 }
1719
1720 // There's exactly one suitable operator; pick it.
1721 if (Matches.size() == 1) {
1722 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
Sean Hunt2be7e902011-05-12 22:46:29 +00001723
1724 if (Operator->isDeleted()) {
1725 if (Diagnose) {
1726 Diag(StartLoc, diag::err_deleted_function_use);
1727 Diag(Operator->getLocation(), diag::note_unavailable_here) << true;
1728 }
1729 return true;
1730 }
1731
John McCall046a7462010-08-04 00:31:26 +00001732 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Sean Hunt2be7e902011-05-12 22:46:29 +00001733 Matches[0], Diagnose);
John McCall046a7462010-08-04 00:31:26 +00001734 return false;
1735
1736 // We found multiple suitable operators; complain about the ambiguity.
1737 } else if (!Matches.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001738 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001739 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1740 << Name << RD;
John McCall046a7462010-08-04 00:31:26 +00001741
Chris Lattner5f9e2722011-07-23 10:55:15 +00001742 for (SmallVectorImpl<DeclAccessPair>::iterator
Sean Huntcb45a0f2011-05-12 22:46:25 +00001743 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1744 Diag((*F)->getUnderlyingDecl()->getLocation(),
1745 diag::note_member_declared_here) << Name;
1746 }
John McCall046a7462010-08-04 00:31:26 +00001747 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001748 }
1749
1750 // We did find operator delete/operator delete[] declarations, but
1751 // none of them were suitable.
1752 if (!Found.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001753 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001754 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1755 << Name << RD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001756
Sean Huntcb45a0f2011-05-12 22:46:25 +00001757 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1758 F != FEnd; ++F)
1759 Diag((*F)->getUnderlyingDecl()->getLocation(),
1760 diag::note_member_declared_here) << Name;
1761 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001762 return true;
1763 }
1764
1765 // Look for a global declaration.
1766 DeclareGlobalNewDelete();
1767 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001768
Anders Carlsson78f74552009-11-15 18:45:20 +00001769 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1770 Expr* DeallocArgs[1];
1771 DeallocArgs[0] = &Null;
1772 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001773 DeallocArgs, 1, TUDecl, !Diagnose,
1774 Operator, Diagnose))
Anders Carlsson78f74552009-11-15 18:45:20 +00001775 return true;
1776
1777 assert(Operator && "Did not find a deallocation function!");
1778 return false;
1779}
1780
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001781/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1782/// @code ::delete ptr; @endcode
1783/// or
1784/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001785ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001786Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley429bb272011-04-08 18:41:53 +00001787 bool ArrayForm, Expr *ExE) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001788 // C++ [expr.delete]p1:
1789 // The operand shall have a pointer type, or a class type having a single
1790 // conversion function to a pointer type. The result has type void.
1791 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001792 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1793
John Wiegley429bb272011-04-08 18:41:53 +00001794 ExprResult Ex = Owned(ExE);
Anders Carlssond67c4c32009-08-16 20:29:29 +00001795 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001796 bool ArrayFormAsWritten = ArrayForm;
John McCall6ec278d2011-01-27 09:37:56 +00001797 bool UsualArrayDeleteWantsSize = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001798
John Wiegley429bb272011-04-08 18:41:53 +00001799 if (!Ex.get()->isTypeDependent()) {
1800 QualType Type = Ex.get()->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001801
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001802 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001803 if (RequireCompleteType(StartLoc, Type,
Douglas Gregor254a9422010-07-29 14:44:35 +00001804 PDiag(diag::err_delete_incomplete_class_type)))
1805 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001806
Chris Lattner5f9e2722011-07-23 10:55:15 +00001807 SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
John McCall32daa422010-03-31 01:36:47 +00001808
Fariborz Jahanian53462782009-09-11 21:44:33 +00001809 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001810 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001811 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001812 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001813 NamedDecl *D = I.getDecl();
1814 if (isa<UsingShadowDecl>(D))
1815 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1816
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001817 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001818 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001819 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001820
John McCall32daa422010-03-31 01:36:47 +00001821 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001822
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001823 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1824 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001825 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001826 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001827 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001828 if (ObjectPtrConversions.size() == 1) {
1829 // We have a single conversion to a pointer-to-object type. Perform
1830 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001831 // TODO: don't redo the conversion calculation.
John Wiegley429bb272011-04-08 18:41:53 +00001832 ExprResult Res =
1833 PerformImplicitConversion(Ex.get(),
John McCall32daa422010-03-31 01:36:47 +00001834 ObjectPtrConversions.front()->getConversionType(),
John Wiegley429bb272011-04-08 18:41:53 +00001835 AA_Converting);
1836 if (Res.isUsable()) {
1837 Ex = move(Res);
1838 Type = Ex.get()->getType();
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001839 }
1840 }
1841 else if (ObjectPtrConversions.size() > 1) {
1842 Diag(StartLoc, diag::err_ambiguous_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001843 << Type << Ex.get()->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001844 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1845 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001846 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001847 }
Sebastian Redl28507842009-02-26 14:39:58 +00001848 }
1849
Sebastian Redlf53597f2009-03-15 17:47:39 +00001850 if (!Type->isPointerType())
1851 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001852 << Type << Ex.get()->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001853
Ted Kremenek6217b802009-07-29 21:53:49 +00001854 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmane52c9142011-07-26 22:25:31 +00001855 QualType PointeeElem = Context.getBaseElementType(Pointee);
1856
1857 if (unsigned AddressSpace = Pointee.getAddressSpace())
1858 return Diag(Ex.get()->getLocStart(),
1859 diag::err_address_space_qualified_delete)
1860 << Pointee.getUnqualifiedType() << AddressSpace;
1861
1862 CXXRecordDecl *PointeeRD = 0;
Douglas Gregor94a61572010-05-24 17:01:56 +00001863 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001864 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregor94a61572010-05-24 17:01:56 +00001865 // effectively bans deletion of "void*". However, most compilers support
1866 // this, so we treat it as a warning unless we're in a SFINAE context.
1867 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001868 << Type << Ex.get()->getSourceRange();
Eli Friedmane52c9142011-07-26 22:25:31 +00001869 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00001870 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001871 << Type << Ex.get()->getSourceRange());
Eli Friedmane52c9142011-07-26 22:25:31 +00001872 } else if (!Pointee->isDependentType()) {
1873 if (!RequireCompleteType(StartLoc, Pointee,
1874 PDiag(diag::warn_delete_incomplete)
1875 << Ex.get()->getSourceRange())) {
1876 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
1877 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
1878 }
1879 }
1880
Abramo Bagnara30bb4202011-11-16 15:42:13 +00001881 // Perform lvalue-to-rvalue cast, if needed.
1882 Ex = DefaultLvalueConversion(Ex.take());
1883
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001884 // C++ [expr.delete]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001885 // [Note: a pointer to a const type can be the operand of a
1886 // delete-expression; it is not necessary to cast away the constness
1887 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001888 // of the delete-expression. ]
John McCallf85e1932011-06-15 23:02:42 +00001889 if (!Context.hasSameType(Ex.get()->getType(), Context.VoidPtrTy))
Abramo Bagnara30bb4202011-11-16 15:42:13 +00001890 Ex = Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy,
1891 CK_BitCast, Ex.take(), 0, VK_RValue));
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001892
1893 if (Pointee->isArrayType() && !ArrayForm) {
1894 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley429bb272011-04-08 18:41:53 +00001895 << Type << Ex.get()->getSourceRange()
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001896 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1897 ArrayForm = true;
1898 }
1899
Anders Carlssond67c4c32009-08-16 20:29:29 +00001900 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1901 ArrayForm ? OO_Array_Delete : OO_Delete);
1902
Eli Friedmane52c9142011-07-26 22:25:31 +00001903 if (PointeeRD) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001904 if (!UseGlobal &&
Eli Friedmane52c9142011-07-26 22:25:31 +00001905 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
1906 OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001907 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001908
John McCall6ec278d2011-01-27 09:37:56 +00001909 // If we're allocating an array of records, check whether the
1910 // usual operator delete[] has a size_t parameter.
1911 if (ArrayForm) {
1912 // If the user specifically asked to use the global allocator,
1913 // we'll need to do the lookup into the class.
1914 if (UseGlobal)
1915 UsualArrayDeleteWantsSize =
1916 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1917
1918 // Otherwise, the usual operator delete[] should be the
1919 // function we just found.
1920 else if (isa<CXXMethodDecl>(OperatorDelete))
1921 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1922 }
1923
Eli Friedmane52c9142011-07-26 22:25:31 +00001924 if (!PointeeRD->hasTrivialDestructor())
1925 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001926 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001927 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00001928 DiagnoseUseOfDecl(Dtor, StartLoc);
1929 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00001930
1931 // C++ [expr.delete]p3:
1932 // In the first alternative (delete object), if the static type of the
1933 // object to be deleted is different from its dynamic type, the static
1934 // type shall be a base class of the dynamic type of the object to be
1935 // deleted and the static type shall have a virtual destructor or the
1936 // behavior is undefined.
1937 //
1938 // Note: a final class cannot be derived from, no issue there
Eli Friedmanef8c79c2011-07-26 23:27:24 +00001939 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
Eli Friedmane52c9142011-07-26 22:25:31 +00001940 CXXDestructorDecl *dtor = PointeeRD->getDestructor();
Eli Friedmanef8c79c2011-07-26 23:27:24 +00001941 if (dtor && !dtor->isVirtual()) {
1942 if (PointeeRD->isAbstract()) {
1943 // If the class is abstract, we warn by default, because we're
1944 // sure the code has undefined behavior.
1945 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
1946 << PointeeElem;
1947 } else if (!ArrayForm) {
1948 // Otherwise, if this is not an array delete, it's a bit suspect,
1949 // but not necessarily wrong.
1950 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
1951 }
1952 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00001953 }
John McCallf85e1932011-06-15 23:02:42 +00001954
1955 } else if (getLangOptions().ObjCAutoRefCount &&
1956 PointeeElem->isObjCLifetimeType() &&
1957 (PointeeElem.getObjCLifetime() == Qualifiers::OCL_Strong ||
1958 PointeeElem.getObjCLifetime() == Qualifiers::OCL_Weak) &&
1959 ArrayForm) {
1960 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1961 << 1 << PointeeElem;
Anders Carlssond67c4c32009-08-16 20:29:29 +00001962 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001963
Anders Carlssond67c4c32009-08-16 20:29:29 +00001964 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001965 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001966 DeclareGlobalNewDelete();
1967 DeclContext *TUDecl = Context.getTranslationUnitDecl();
John Wiegley429bb272011-04-08 18:41:53 +00001968 Expr *Arg = Ex.get();
Mike Stump1eb44332009-09-09 15:08:12 +00001969 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
John Wiegley429bb272011-04-08 18:41:53 +00001970 &Arg, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001971 OperatorDelete))
1972 return ExprError();
1973 }
Mike Stump1eb44332009-09-09 15:08:12 +00001974
John McCall9c82afc2010-04-20 02:18:25 +00001975 MarkDeclarationReferenced(StartLoc, OperatorDelete);
John McCall6ec278d2011-01-27 09:37:56 +00001976
Douglas Gregord880f522011-02-01 15:50:11 +00001977 // Check access and ambiguity of operator delete and destructor.
Eli Friedmane52c9142011-07-26 22:25:31 +00001978 if (PointeeRD) {
1979 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
John Wiegley429bb272011-04-08 18:41:53 +00001980 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregord880f522011-02-01 15:50:11 +00001981 PDiag(diag::err_access_dtor) << PointeeElem);
1982 }
1983 }
1984
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001985 }
1986
Sebastian Redlf53597f2009-03-15 17:47:39 +00001987 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall6ec278d2011-01-27 09:37:56 +00001988 ArrayFormAsWritten,
1989 UsualArrayDeleteWantsSize,
John Wiegley429bb272011-04-08 18:41:53 +00001990 OperatorDelete, Ex.take(), StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001991}
1992
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001993/// \brief Check the use of the given variable as a C++ condition in an if,
1994/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001995ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00001996 SourceLocation StmtLoc,
1997 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001998 QualType T = ConditionVar->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001999
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002000 // C++ [stmt.select]p2:
2001 // The declarator shall not specify a function or an array.
2002 if (T->isFunctionType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002003 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002004 diag::err_invalid_use_of_function_type)
2005 << ConditionVar->getSourceRange());
2006 else if (T->isArrayType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002007 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002008 diag::err_invalid_use_of_array_type)
2009 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00002010
John Wiegley429bb272011-04-08 18:41:53 +00002011 ExprResult Condition =
2012 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
Douglas Gregor40d96a62011-02-28 21:54:11 +00002013 ConditionVar,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002014 ConditionVar->getLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00002015 ConditionVar->getType().getNonReferenceType(),
John Wiegley429bb272011-04-08 18:41:53 +00002016 VK_LValue));
2017 if (ConvertToBoolean) {
2018 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
2019 if (Condition.isInvalid())
2020 return ExprError();
2021 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002022
John Wiegley429bb272011-04-08 18:41:53 +00002023 return move(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002024}
2025
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002026/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley429bb272011-04-08 18:41:53 +00002027ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002028 // C++ 6.4p4:
2029 // The value of a condition that is an initialized declaration in a statement
2030 // other than a switch statement is the value of the declared variable
2031 // implicitly converted to type bool. If that conversion is ill-formed, the
2032 // program is ill-formed.
2033 // The value of a condition that is an expression is the value of the
2034 // expression, implicitly converted to bool.
2035 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002036 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002037}
Douglas Gregor77a52232008-09-12 00:47:35 +00002038
2039/// Helper function to determine whether this is the (deprecated) C++
2040/// conversion from a string literal to a pointer to non-const char or
2041/// non-const wchar_t (for narrow and wide string literals,
2042/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00002043bool
Douglas Gregor77a52232008-09-12 00:47:35 +00002044Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2045 // Look inside the implicit cast, if it exists.
2046 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2047 From = Cast->getSubExpr();
2048
2049 // A string literal (2.13.4) that is not a wide string literal can
2050 // be converted to an rvalue of type "pointer to char"; a wide
2051 // string literal can be converted to an rvalue of type "pointer
2052 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00002053 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00002054 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00002055 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00002056 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00002057 // This conversion is considered only when there is an
2058 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregor5cee1192011-07-27 05:40:30 +00002059 if (!ToPtrType->getPointeeType().hasQualifiers()) {
2060 switch (StrLit->getKind()) {
2061 case StringLiteral::UTF8:
2062 case StringLiteral::UTF16:
2063 case StringLiteral::UTF32:
2064 // We don't allow UTF literals to be implicitly converted
2065 break;
2066 case StringLiteral::Ascii:
2067 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2068 ToPointeeType->getKind() == BuiltinType::Char_S);
2069 case StringLiteral::Wide:
2070 return ToPointeeType->isWideCharType();
2071 }
2072 }
Douglas Gregor77a52232008-09-12 00:47:35 +00002073 }
2074
2075 return false;
2076}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002077
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002078static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00002079 SourceLocation CastLoc,
2080 QualType Ty,
2081 CastKind Kind,
2082 CXXMethodDecl *Method,
John McCallca82a822011-09-21 08:36:56 +00002083 DeclAccessPair FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002084 bool HadMultipleCandidates,
John McCall2de56d12010-08-25 11:45:40 +00002085 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002086 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002087 default: llvm_unreachable("Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00002088 case CK_ConstructorConversion: {
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002089 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
John McCallca0408f2010-08-23 06:44:23 +00002090 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002091
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002092 if (S.CompleteConstructorCall(Constructor,
John McCallf312b1e2010-08-26 23:41:50 +00002093 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00002094 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00002095 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002096
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002097 S.CheckConstructorAccess(CastLoc, Constructor, Constructor->getAccess(),
2098 S.PDiag(diag::err_access_ctor));
2099
2100 ExprResult Result
2101 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2102 move_arg(ConstructorArgs),
2103 HadMultipleCandidates, /*ZeroInit*/ false,
2104 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002105 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00002106 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002107
Douglas Gregorba70ab62010-04-16 22:17:36 +00002108 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2109 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002110
John McCall2de56d12010-08-25 11:45:40 +00002111 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002112 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002113
Douglas Gregorba70ab62010-04-16 22:17:36 +00002114 // Create an implicit call expr that calls it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002115 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method,
2116 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002117 if (Result.isInvalid())
2118 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00002119 // Record usage of conversion in an implicit cast.
2120 Result = S.Owned(ImplicitCastExpr::Create(S.Context,
2121 Result.get()->getType(),
2122 CK_UserDefinedConversion,
2123 Result.get(), 0,
2124 Result.get()->getValueKind()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002125
John McCallca82a822011-09-21 08:36:56 +00002126 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2127
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002128 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002129 }
2130 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002131}
Douglas Gregorba70ab62010-04-16 22:17:36 +00002132
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002133/// PerformImplicitConversion - Perform an implicit conversion of the
2134/// expression From to the type ToType using the pre-computed implicit
John Wiegley429bb272011-04-08 18:41:53 +00002135/// conversion sequence ICS. Returns the converted
Douglas Gregor68647482009-12-16 03:45:30 +00002136/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002137/// used in the error message.
John Wiegley429bb272011-04-08 18:41:53 +00002138ExprResult
2139Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002140 const ImplicitConversionSequence &ICS,
John McCallf85e1932011-06-15 23:02:42 +00002141 AssignmentAction Action,
2142 CheckedConversionKind CCK) {
John McCall1d318332010-01-12 00:44:57 +00002143 switch (ICS.getKind()) {
John Wiegley429bb272011-04-08 18:41:53 +00002144 case ImplicitConversionSequence::StandardConversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002145 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2146 Action, CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002147 if (Res.isInvalid())
2148 return ExprError();
2149 From = Res.take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002150 break;
John Wiegley429bb272011-04-08 18:41:53 +00002151 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002152
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002153 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002154
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00002155 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00002156 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002157 QualType BeforeToType;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00002158 assert(FD && "FIXME: aggregate initialization from init list");
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002159 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00002160 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002161
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002162 // If the user-defined conversion is specified by a conversion function,
2163 // the initial standard conversion sequence converts the source type to
2164 // the implicit object parameter of the conversion function.
2165 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00002166 } else {
2167 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00002168 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002169 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00002170 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002171 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002172 // initial standard conversion sequence converts the source type to the
2173 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00002174 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2175 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002176 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00002177 // Watch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00002178 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley429bb272011-04-08 18:41:53 +00002179 ExprResult Res =
Richard Smithc8d7f582011-11-29 22:48:16 +00002180 PerformImplicitConversion(From, BeforeToType,
2181 ICS.UserDefined.Before, AA_Converting,
2182 CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002183 if (Res.isInvalid())
2184 return ExprError();
2185 From = Res.take();
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002186 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002187
2188 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00002189 = BuildCXXCastArgument(*this,
2190 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00002191 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002192 CastKind, cast<CXXMethodDecl>(FD),
2193 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002194 ICS.UserDefined.HadMultipleCandidates,
John McCall9ae2f072010-08-23 23:25:46 +00002195 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002196
2197 if (CastArg.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00002198 return ExprError();
Eli Friedmand8889622009-11-27 04:41:50 +00002199
John Wiegley429bb272011-04-08 18:41:53 +00002200 From = CastArg.take();
Eli Friedmand8889622009-11-27 04:41:50 +00002201
Richard Smithc8d7f582011-11-29 22:48:16 +00002202 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2203 AA_Converting, CCK);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00002204 }
John McCall1d318332010-01-12 00:44:57 +00002205
2206 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00002207 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00002208 PDiag(diag::err_typecheck_ambiguous_condition)
2209 << From->getSourceRange());
John Wiegley429bb272011-04-08 18:41:53 +00002210 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002211
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002212 case ImplicitConversionSequence::EllipsisConversion:
David Blaikieb219cfc2011-09-23 05:06:16 +00002213 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002214
2215 case ImplicitConversionSequence::BadConversion:
John Wiegley429bb272011-04-08 18:41:53 +00002216 return ExprError();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002217 }
2218
2219 // Everything went well.
John Wiegley429bb272011-04-08 18:41:53 +00002220 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002221}
2222
Richard Smithc8d7f582011-11-29 22:48:16 +00002223/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002224/// expression From to the type ToType by following the standard
John Wiegley429bb272011-04-08 18:41:53 +00002225/// conversion sequence SCS. Returns the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00002226/// expression. Flavor is the context in which we're performing this
2227/// conversion, for use in error messages.
John Wiegley429bb272011-04-08 18:41:53 +00002228ExprResult
Richard Smithc8d7f582011-11-29 22:48:16 +00002229Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00002230 const StandardConversionSequence& SCS,
John McCallf85e1932011-06-15 23:02:42 +00002231 AssignmentAction Action,
2232 CheckedConversionKind CCK) {
2233 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2234
Mike Stump390b4cc2009-05-16 07:39:55 +00002235 // Overall FIXME: we are recomputing too many types here and doing far too
2236 // much extra work. What this means is that we need to keep track of more
2237 // information that is computed when we try the implicit conversion initially,
2238 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002239 QualType FromType = From->getType();
John McCallf85e1932011-06-15 23:02:42 +00002240
Douglas Gregor225c41e2008-11-03 19:09:14 +00002241 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00002242 // FIXME: When can ToType be a reference type?
2243 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002244 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00002245 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002246 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00002247 MultiExprArg(*this, &From, 1),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002248 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002249 ConstructorArgs))
John Wiegley429bb272011-04-08 18:41:53 +00002250 return ExprError();
2251 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2252 ToType, SCS.CopyConstructor,
2253 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002254 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002255 /*ZeroInit*/ false,
2256 CXXConstructExpr::CK_Complete,
2257 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002258 }
John Wiegley429bb272011-04-08 18:41:53 +00002259 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2260 ToType, SCS.CopyConstructor,
2261 MultiExprArg(*this, &From, 1),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002262 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002263 /*ZeroInit*/ false,
2264 CXXConstructExpr::CK_Complete,
2265 SourceRange());
Douglas Gregor225c41e2008-11-03 19:09:14 +00002266 }
2267
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002268 // Resolve overloaded function references.
2269 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2270 DeclAccessPair Found;
2271 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2272 true, Found);
2273 if (!Fn)
John Wiegley429bb272011-04-08 18:41:53 +00002274 return ExprError();
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002275
2276 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
John Wiegley429bb272011-04-08 18:41:53 +00002277 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002278
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002279 From = FixOverloadedFunctionReference(From, Found, Fn);
2280 FromType = From->getType();
2281 }
2282
Richard Smithc8d7f582011-11-29 22:48:16 +00002283 // Perform the first implicit conversion.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002284 switch (SCS.First) {
2285 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002286 // Nothing to do.
2287 break;
2288
John McCallf6a16482010-12-04 03:47:34 +00002289 case ICK_Lvalue_To_Rvalue:
John McCall3c3b7f92011-10-25 17:37:35 +00002290 assert(From->getObjectKind() != OK_ObjCProperty);
John McCallf6a16482010-12-04 03:47:34 +00002291 FromType = FromType.getUnqualifiedType();
2292 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2293 From, 0, VK_RValue);
2294 break;
2295
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002296 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002297 FromType = Context.getArrayDecayedType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002298 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2299 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002300 break;
2301
2302 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002303 FromType = Context.getPointerType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002304 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2305 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002306 break;
2307
2308 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002309 llvm_unreachable("Improper first standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002310 }
2311
Richard Smithc8d7f582011-11-29 22:48:16 +00002312 // Perform the second implicit conversion
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002313 switch (SCS.Second) {
2314 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002315 // If both sides are functions (or pointers/references to them), there could
2316 // be incompatible exception declarations.
2317 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002318 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002319 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002320 break;
2321
Douglas Gregor43c79c22009-12-09 00:47:37 +00002322 case ICK_NoReturn_Adjustment:
2323 // If both sides are functions (or pointers/references to them), there could
2324 // be incompatible exception declarations.
2325 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002326 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002327
Richard Smithc8d7f582011-11-29 22:48:16 +00002328 From = ImpCastExprToType(From, ToType, CK_NoOp,
2329 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor43c79c22009-12-09 00:47:37 +00002330 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002331
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002332 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002333 case ICK_Integral_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002334 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2335 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002336 break;
2337
2338 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002339 case ICK_Floating_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002340 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2341 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002342 break;
2343
2344 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00002345 case ICK_Complex_Conversion: {
2346 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2347 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2348 CastKind CK;
2349 if (FromEl->isRealFloatingType()) {
2350 if (ToEl->isRealFloatingType())
2351 CK = CK_FloatingComplexCast;
2352 else
2353 CK = CK_FloatingComplexToIntegralComplex;
2354 } else if (ToEl->isRealFloatingType()) {
2355 CK = CK_IntegralComplexToFloatingComplex;
2356 } else {
2357 CK = CK_IntegralComplexCast;
2358 }
Richard Smithc8d7f582011-11-29 22:48:16 +00002359 From = ImpCastExprToType(From, ToType, CK,
2360 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002361 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00002362 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002363
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002364 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002365 if (ToType->isRealFloatingType())
Richard Smithc8d7f582011-11-29 22:48:16 +00002366 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2367 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002368 else
Richard Smithc8d7f582011-11-29 22:48:16 +00002369 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2370 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002371 break;
2372
Douglas Gregorf9201e02009-02-11 23:02:49 +00002373 case ICK_Compatible_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002374 From = ImpCastExprToType(From, ToType, CK_NoOp,
2375 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002376 break;
2377
John McCallf85e1932011-06-15 23:02:42 +00002378 case ICK_Writeback_Conversion:
Anders Carlsson61faec12009-09-12 04:46:44 +00002379 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00002380 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002381 // Diagnose incompatible Objective-C conversions
Douglas Gregor8cf0d222011-06-11 04:42:12 +00002382 if (Action == AA_Initializing || Action == AA_Assigning)
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002383 Diag(From->getSourceRange().getBegin(),
2384 diag::ext_typecheck_convert_incompatible_pointer)
2385 << ToType << From->getType() << Action
Anna Zaks67221552011-07-28 19:51:27 +00002386 << From->getSourceRange() << 0;
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002387 else
2388 Diag(From->getSourceRange().getBegin(),
2389 diag::ext_typecheck_convert_incompatible_pointer)
2390 << From->getType() << ToType << Action
Anna Zaks67221552011-07-28 19:51:27 +00002391 << From->getSourceRange() << 0;
John McCallf85e1932011-06-15 23:02:42 +00002392
Douglas Gregor926df6c2011-06-11 01:09:30 +00002393 if (From->getType()->isObjCObjectPointerType() &&
2394 ToType->isObjCObjectPointerType())
2395 EmitRelatedResultTypeNote(From);
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002396 }
2397 else if (getLangOptions().ObjCAutoRefCount &&
2398 !CheckObjCARCUnavailableWeakConversion(ToType,
2399 From->getType())) {
John McCall7f3a6d32011-09-09 06:12:06 +00002400 if (Action == AA_Initializing)
2401 Diag(From->getSourceRange().getBegin(),
2402 diag::err_arc_weak_unavailable_assign);
2403 else
2404 Diag(From->getSourceRange().getBegin(),
2405 diag::err_arc_convesion_of_weak_unavailable)
2406 << (Action == AA_Casting) << From->getType() << ToType
2407 << From->getSourceRange();
2408 }
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002409
John McCalldaa8e4e2010-11-15 09:13:47 +00002410 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002411 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002412 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002413 return ExprError();
John McCalldc05b112011-09-10 01:16:55 +00002414
2415 // Make sure we extend blocks if necessary.
2416 // FIXME: doing this here is really ugly.
2417 if (Kind == CK_BlockPointerToObjCPointerCast) {
2418 ExprResult E = From;
2419 (void) PrepareCastToObjCObjectPointer(E);
2420 From = E.take();
2421 }
2422
Richard Smithc8d7f582011-11-29 22:48:16 +00002423 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2424 .take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002425 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00002426 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002427
Anders Carlsson61faec12009-09-12 04:46:44 +00002428 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002429 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002430 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002431 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002432 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002433 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002434 return ExprError();
Richard Smithc8d7f582011-11-29 22:48:16 +00002435 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2436 .take();
Anders Carlsson61faec12009-09-12 04:46:44 +00002437 break;
2438 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002439
Abramo Bagnara737d5442011-04-07 09:26:19 +00002440 case ICK_Boolean_Conversion:
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00002441 // Perform half-to-boolean conversion via float.
2442 if (From->getType()->isHalfType()) {
2443 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take();
2444 FromType = Context.FloatTy;
2445 }
2446
Richard Smithc8d7f582011-11-29 22:48:16 +00002447 From = ImpCastExprToType(From, Context.BoolTy,
2448 ScalarTypeToBooleanCastKind(FromType),
2449 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002450 break;
2451
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002452 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002453 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002454 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002455 ToType.getNonReferenceType(),
2456 From->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002457 From->getSourceRange(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002458 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002459 CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002460 return ExprError();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002461
Richard Smithc8d7f582011-11-29 22:48:16 +00002462 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2463 CK_DerivedToBase, From->getValueKind(),
2464 &BasePath, CCK).take();
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002465 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002466 }
2467
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002468 case ICK_Vector_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002469 From = ImpCastExprToType(From, ToType, CK_BitCast,
2470 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002471 break;
2472
2473 case ICK_Vector_Splat:
Richard Smithc8d7f582011-11-29 22:48:16 +00002474 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2475 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002476 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002477
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002478 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002479 // Case 1. x -> _Complex y
2480 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2481 QualType ElType = ToComplex->getElementType();
2482 bool isFloatingComplex = ElType->isRealFloatingType();
2483
2484 // x -> y
2485 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2486 // do nothing
2487 } else if (From->getType()->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002488 From = ImpCastExprToType(From, ElType,
2489 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002490 } else {
2491 assert(From->getType()->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002492 From = ImpCastExprToType(From, ElType,
2493 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002494 }
2495 // y -> _Complex y
Richard Smithc8d7f582011-11-29 22:48:16 +00002496 From = ImpCastExprToType(From, ToType,
2497 isFloatingComplex ? CK_FloatingRealToComplex
2498 : CK_IntegralRealToComplex).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002499
2500 // Case 2. _Complex x -> y
2501 } else {
2502 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2503 assert(FromComplex);
2504
2505 QualType ElType = FromComplex->getElementType();
2506 bool isFloatingComplex = ElType->isRealFloatingType();
2507
2508 // _Complex x -> x
Richard Smithc8d7f582011-11-29 22:48:16 +00002509 From = ImpCastExprToType(From, ElType,
2510 isFloatingComplex ? CK_FloatingComplexToReal
2511 : CK_IntegralComplexToReal,
2512 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002513
2514 // x -> y
2515 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2516 // do nothing
2517 } else if (ToType->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002518 From = ImpCastExprToType(From, ToType,
2519 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2520 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002521 } else {
2522 assert(ToType->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002523 From = ImpCastExprToType(From, ToType,
2524 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2525 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002526 }
2527 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002528 break;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002529
2530 case ICK_Block_Pointer_Conversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002531 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2532 VK_RValue, /*BasePath=*/0, CCK).take();
John McCallf85e1932011-06-15 23:02:42 +00002533 break;
2534 }
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002535
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002536 case ICK_TransparentUnionConversion: {
John Wiegley429bb272011-04-08 18:41:53 +00002537 ExprResult FromRes = Owned(From);
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002538 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002539 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2540 if (FromRes.isInvalid())
2541 return ExprError();
2542 From = FromRes.take();
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002543 assert ((ConvTy == Sema::Compatible) &&
2544 "Improper transparent union conversion");
2545 (void)ConvTy;
2546 break;
2547 }
2548
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002549 case ICK_Lvalue_To_Rvalue:
2550 case ICK_Array_To_Pointer:
2551 case ICK_Function_To_Pointer:
2552 case ICK_Qualification:
2553 case ICK_Num_Conversion_Kinds:
David Blaikieb219cfc2011-09-23 05:06:16 +00002554 llvm_unreachable("Improper second standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002555 }
2556
2557 switch (SCS.Third) {
2558 case ICK_Identity:
2559 // Nothing to do.
2560 break;
2561
Sebastian Redl906082e2010-07-20 04:20:21 +00002562 case ICK_Qualification: {
2563 // The qualification keeps the category of the inner expression, unless the
2564 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002565 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002566 From->getValueKind() : VK_RValue;
Richard Smithc8d7f582011-11-29 22:48:16 +00002567 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2568 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
Douglas Gregora9bff302010-02-28 18:30:25 +00002569
Douglas Gregor069a6da2011-03-14 16:13:32 +00002570 if (SCS.DeprecatedStringLiteralToCharPtr &&
2571 !getLangOptions().WritableStrings)
Douglas Gregora9bff302010-02-28 18:30:25 +00002572 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2573 << ToType.getNonReferenceType();
2574
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002575 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002576 }
2577
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002578 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002579 llvm_unreachable("Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002580 }
2581
John Wiegley429bb272011-04-08 18:41:53 +00002582 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002583}
2584
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002585ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002586 SourceLocation KWLoc,
2587 ParsedType Ty,
2588 SourceLocation RParen) {
2589 TypeSourceInfo *TSInfo;
2590 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002591
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002592 if (!TSInfo)
2593 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002594 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002595}
2596
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002597/// \brief Check the completeness of a type in a unary type trait.
2598///
2599/// If the particular type trait requires a complete type, tries to complete
2600/// it. If completing the type fails, a diagnostic is emitted and false
2601/// returned. If completing the type succeeds or no completion was required,
2602/// returns true.
2603static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2604 UnaryTypeTrait UTT,
2605 SourceLocation Loc,
2606 QualType ArgTy) {
2607 // C++0x [meta.unary.prop]p3:
2608 // For all of the class templates X declared in this Clause, instantiating
2609 // that template with a template argument that is a class template
2610 // specialization may result in the implicit instantiation of the template
2611 // argument if and only if the semantics of X require that the argument
2612 // must be a complete type.
2613 // We apply this rule to all the type trait expressions used to implement
2614 // these class templates. We also try to follow any GCC documented behavior
2615 // in these expressions to ensure portability of standard libraries.
2616 switch (UTT) {
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002617 // is_complete_type somewhat obviously cannot require a complete type.
2618 case UTT_IsCompleteType:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002619 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002620
2621 // These traits are modeled on the type predicates in C++0x
2622 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2623 // requiring a complete type, as whether or not they return true cannot be
2624 // impacted by the completeness of the type.
2625 case UTT_IsVoid:
2626 case UTT_IsIntegral:
2627 case UTT_IsFloatingPoint:
2628 case UTT_IsArray:
2629 case UTT_IsPointer:
2630 case UTT_IsLvalueReference:
2631 case UTT_IsRvalueReference:
2632 case UTT_IsMemberFunctionPointer:
2633 case UTT_IsMemberObjectPointer:
2634 case UTT_IsEnum:
2635 case UTT_IsUnion:
2636 case UTT_IsClass:
2637 case UTT_IsFunction:
2638 case UTT_IsReference:
2639 case UTT_IsArithmetic:
2640 case UTT_IsFundamental:
2641 case UTT_IsObject:
2642 case UTT_IsScalar:
2643 case UTT_IsCompound:
2644 case UTT_IsMemberPointer:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002645 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002646
2647 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2648 // which requires some of its traits to have the complete type. However,
2649 // the completeness of the type cannot impact these traits' semantics, and
2650 // so they don't require it. This matches the comments on these traits in
2651 // Table 49.
2652 case UTT_IsConst:
2653 case UTT_IsVolatile:
2654 case UTT_IsSigned:
2655 case UTT_IsUnsigned:
2656 return true;
2657
2658 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002659 // applied to a complete type.
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002660 case UTT_IsTrivial:
Sean Huntfeb375d2011-05-13 00:31:07 +00002661 case UTT_IsTriviallyCopyable:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002662 case UTT_IsStandardLayout:
2663 case UTT_IsPOD:
2664 case UTT_IsLiteral:
2665 case UTT_IsEmpty:
2666 case UTT_IsPolymorphic:
2667 case UTT_IsAbstract:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002668 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002669
Douglas Gregor5e9392b2011-12-03 18:14:24 +00002670 // These traits require a complete type.
2671 case UTT_IsFinal:
2672
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002673 // These trait expressions are designed to help implement predicates in
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002674 // [meta.unary.prop] despite not being named the same. They are specified
2675 // by both GCC and the Embarcadero C++ compiler, and require the complete
2676 // type due to the overarching C++0x type predicates being implemented
2677 // requiring the complete type.
2678 case UTT_HasNothrowAssign:
2679 case UTT_HasNothrowConstructor:
2680 case UTT_HasNothrowCopy:
2681 case UTT_HasTrivialAssign:
Sean Hunt023df372011-05-09 18:22:59 +00002682 case UTT_HasTrivialDefaultConstructor:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002683 case UTT_HasTrivialCopy:
2684 case UTT_HasTrivialDestructor:
2685 case UTT_HasVirtualDestructor:
2686 // Arrays of unknown bound are expressly allowed.
2687 QualType ElTy = ArgTy;
2688 if (ArgTy->isIncompleteArrayType())
2689 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2690
2691 // The void type is expressly allowed.
2692 if (ElTy->isVoidType())
2693 return true;
2694
2695 return !S.RequireCompleteType(
2696 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleycf566412011-04-28 02:06:46 +00002697 }
Chandler Carruth73e0a912011-05-01 07:23:17 +00002698 llvm_unreachable("Type trait not handled by switch");
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002699}
2700
2701static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2702 SourceLocation KeyLoc, QualType T) {
Chandler Carruthd064c702011-05-01 08:41:10 +00002703 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleycf566412011-04-28 02:06:46 +00002704
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002705 ASTContext &C = Self.Context;
2706 switch(UTT) {
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002707 // Type trait expressions corresponding to the primary type category
2708 // predicates in C++0x [meta.unary.cat].
2709 case UTT_IsVoid:
2710 return T->isVoidType();
2711 case UTT_IsIntegral:
2712 return T->isIntegralType(C);
2713 case UTT_IsFloatingPoint:
2714 return T->isFloatingType();
2715 case UTT_IsArray:
2716 return T->isArrayType();
2717 case UTT_IsPointer:
2718 return T->isPointerType();
2719 case UTT_IsLvalueReference:
2720 return T->isLValueReferenceType();
2721 case UTT_IsRvalueReference:
2722 return T->isRValueReferenceType();
2723 case UTT_IsMemberFunctionPointer:
2724 return T->isMemberFunctionPointerType();
2725 case UTT_IsMemberObjectPointer:
2726 return T->isMemberDataPointerType();
2727 case UTT_IsEnum:
2728 return T->isEnumeralType();
Chandler Carruth28eeb382011-05-01 06:11:03 +00002729 case UTT_IsUnion:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002730 return T->isUnionType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002731 case UTT_IsClass:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002732 return T->isClassType() || T->isStructureType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002733 case UTT_IsFunction:
2734 return T->isFunctionType();
2735
2736 // Type trait expressions which correspond to the convenient composition
2737 // predicates in C++0x [meta.unary.comp].
2738 case UTT_IsReference:
2739 return T->isReferenceType();
2740 case UTT_IsArithmetic:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002741 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002742 case UTT_IsFundamental:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002743 return T->isFundamentalType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002744 case UTT_IsObject:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002745 return T->isObjectType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002746 case UTT_IsScalar:
John McCallf85e1932011-06-15 23:02:42 +00002747 // Note: semantic analysis depends on Objective-C lifetime types to be
2748 // considered scalar types. However, such types do not actually behave
2749 // like scalar types at run time (since they may require retain/release
2750 // operations), so we report them as non-scalar.
2751 if (T->isObjCLifetimeType()) {
2752 switch (T.getObjCLifetime()) {
2753 case Qualifiers::OCL_None:
2754 case Qualifiers::OCL_ExplicitNone:
2755 return true;
2756
2757 case Qualifiers::OCL_Strong:
2758 case Qualifiers::OCL_Weak:
2759 case Qualifiers::OCL_Autoreleasing:
2760 return false;
2761 }
2762 }
2763
Chandler Carruthcec0ced2011-05-01 09:29:55 +00002764 return T->isScalarType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002765 case UTT_IsCompound:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002766 return T->isCompoundType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002767 case UTT_IsMemberPointer:
2768 return T->isMemberPointerType();
2769
2770 // Type trait expressions which correspond to the type property predicates
2771 // in C++0x [meta.unary.prop].
2772 case UTT_IsConst:
2773 return T.isConstQualified();
2774 case UTT_IsVolatile:
2775 return T.isVolatileQualified();
2776 case UTT_IsTrivial:
John McCallf85e1932011-06-15 23:02:42 +00002777 return T.isTrivialType(Self.Context);
Sean Huntfeb375d2011-05-13 00:31:07 +00002778 case UTT_IsTriviallyCopyable:
John McCallf85e1932011-06-15 23:02:42 +00002779 return T.isTriviallyCopyableType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002780 case UTT_IsStandardLayout:
2781 return T->isStandardLayoutType();
2782 case UTT_IsPOD:
John McCallf85e1932011-06-15 23:02:42 +00002783 return T.isPODType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002784 case UTT_IsLiteral:
2785 return T->isLiteralType();
2786 case UTT_IsEmpty:
2787 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2788 return !RD->isUnion() && RD->isEmpty();
2789 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002790 case UTT_IsPolymorphic:
Chandler Carruth28eeb382011-05-01 06:11:03 +00002791 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2792 return RD->isPolymorphic();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002793 return false;
2794 case UTT_IsAbstract:
Chandler Carruth28eeb382011-05-01 06:11:03 +00002795 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2796 return RD->isAbstract();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002797 return false;
Douglas Gregor5e9392b2011-12-03 18:14:24 +00002798 case UTT_IsFinal:
2799 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2800 return RD->hasAttr<FinalAttr>();
2801 return false;
John Wiegley20c0da72011-04-27 23:09:49 +00002802 case UTT_IsSigned:
2803 return T->isSignedIntegerType();
John Wiegley20c0da72011-04-27 23:09:49 +00002804 case UTT_IsUnsigned:
2805 return T->isUnsignedIntegerType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002806
2807 // Type trait expressions which query classes regarding their construction,
2808 // destruction, and copying. Rather than being based directly on the
2809 // related type predicates in the standard, they are specified by both
2810 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
2811 // specifications.
2812 //
2813 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
2814 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Sean Hunt023df372011-05-09 18:22:59 +00002815 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002816 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2817 // If __is_pod (type) is true then the trait is true, else if type is
2818 // a cv class or union type (or array thereof) with a trivial default
2819 // constructor ([class.ctor]) then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002820 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002821 return true;
2822 if (const RecordType *RT =
2823 C.getBaseElementType(T)->getAs<RecordType>())
Sean Hunt023df372011-05-09 18:22:59 +00002824 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002825 return false;
2826 case UTT_HasTrivialCopy:
2827 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2828 // If __is_pod (type) is true or type is a reference type then
2829 // the trait is true, else if type is a cv class or union type
2830 // with a trivial copy constructor ([class.copy]) then the trait
2831 // is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002832 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002833 return true;
2834 if (const RecordType *RT = T->getAs<RecordType>())
2835 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2836 return false;
2837 case UTT_HasTrivialAssign:
2838 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2839 // If type is const qualified or is a reference type then the
2840 // trait is false. Otherwise if __is_pod (type) is true then the
2841 // trait is true, else if type is a cv class or union type with
2842 // a trivial copy assignment ([class.copy]) then the trait is
2843 // true, else it is false.
2844 // Note: the const and reference restrictions are interesting,
2845 // given that const and reference members don't prevent a class
2846 // from having a trivial copy assignment operator (but do cause
2847 // errors if the copy assignment operator is actually used, q.v.
2848 // [class.copy]p12).
2849
2850 if (C.getBaseElementType(T).isConstQualified())
2851 return false;
John McCallf85e1932011-06-15 23:02:42 +00002852 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002853 return true;
2854 if (const RecordType *RT = T->getAs<RecordType>())
2855 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2856 return false;
2857 case UTT_HasTrivialDestructor:
2858 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2859 // If __is_pod (type) is true or type is a reference type
2860 // then the trait is true, else if type is a cv class or union
2861 // type (or array thereof) with a trivial destructor
2862 // ([class.dtor]) then the trait is true, else it is
2863 // false.
John McCallf85e1932011-06-15 23:02:42 +00002864 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002865 return true;
John McCallf85e1932011-06-15 23:02:42 +00002866
2867 // Objective-C++ ARC: autorelease types don't require destruction.
2868 if (T->isObjCLifetimeType() &&
2869 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
2870 return true;
2871
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002872 if (const RecordType *RT =
2873 C.getBaseElementType(T)->getAs<RecordType>())
2874 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2875 return false;
2876 // TODO: Propagate nothrowness for implicitly declared special members.
2877 case UTT_HasNothrowAssign:
2878 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2879 // If type is const qualified or is a reference type then the
2880 // trait is false. Otherwise if __has_trivial_assign (type)
2881 // is true then the trait is true, else if type is a cv class
2882 // or union type with copy assignment operators that are known
2883 // not to throw an exception then the trait is true, else it is
2884 // false.
2885 if (C.getBaseElementType(T).isConstQualified())
2886 return false;
2887 if (T->isReferenceType())
2888 return false;
John McCallf85e1932011-06-15 23:02:42 +00002889 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
2890 return true;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002891 if (const RecordType *RT = T->getAs<RecordType>()) {
2892 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2893 if (RD->hasTrivialCopyAssignment())
2894 return true;
2895
2896 bool FoundAssign = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002897 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00002898 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2899 Sema::LookupOrdinaryName);
2900 if (Self.LookupQualifiedName(Res, RD)) {
Douglas Gregord41679d2011-10-12 15:40:49 +00002901 Res.suppressDiagnostics();
Sebastian Redlf8aca862010-09-14 23:40:14 +00002902 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2903 Op != OpEnd; ++Op) {
Douglas Gregord41679d2011-10-12 15:40:49 +00002904 if (isa<FunctionTemplateDecl>(*Op))
2905 continue;
2906
Sebastian Redlf8aca862010-09-14 23:40:14 +00002907 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2908 if (Operator->isCopyAssignmentOperator()) {
2909 FoundAssign = true;
2910 const FunctionProtoType *CPT
2911 = Operator->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00002912 if (CPT->getExceptionSpecType() == EST_Delayed)
2913 return false;
2914 if (!CPT->isNothrow(Self.Context))
2915 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002916 }
2917 }
2918 }
Douglas Gregord41679d2011-10-12 15:40:49 +00002919
Richard Smith7a614d82011-06-11 17:19:42 +00002920 return FoundAssign;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002921 }
2922 return false;
2923 case UTT_HasNothrowCopy:
2924 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2925 // If __has_trivial_copy (type) is true then the trait is true, else
2926 // if type is a cv class or union type with copy constructors that are
2927 // known not to throw an exception then the trait is true, else it is
2928 // false.
John McCallf85e1932011-06-15 23:02:42 +00002929 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002930 return true;
2931 if (const RecordType *RT = T->getAs<RecordType>()) {
2932 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2933 if (RD->hasTrivialCopyConstructor())
2934 return true;
2935
2936 bool FoundConstructor = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002937 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002938 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00002939 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002940 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002941 // A template constructor is never a copy constructor.
2942 // FIXME: However, it may actually be selected at the actual overload
2943 // resolution point.
2944 if (isa<FunctionTemplateDecl>(*Con))
2945 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002946 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2947 if (Constructor->isCopyConstructor(FoundTQs)) {
2948 FoundConstructor = true;
2949 const FunctionProtoType *CPT
2950 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00002951 if (CPT->getExceptionSpecType() == EST_Delayed)
2952 return false;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002953 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redl751025d2010-09-13 22:02:47 +00002954 // For now, we'll be conservative and assume that they can throw.
Richard Smith7a614d82011-06-11 17:19:42 +00002955 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
2956 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002957 }
2958 }
2959
Richard Smith7a614d82011-06-11 17:19:42 +00002960 return FoundConstructor;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002961 }
2962 return false;
2963 case UTT_HasNothrowConstructor:
2964 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2965 // If __has_trivial_constructor (type) is true then the trait is
2966 // true, else if type is a cv class or union type (or array
2967 // thereof) with a default constructor that is known not to
2968 // throw an exception then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002969 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002970 return true;
2971 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2972 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Hunt023df372011-05-09 18:22:59 +00002973 if (RD->hasTrivialDefaultConstructor())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002974 return true;
2975
Sebastian Redl751025d2010-09-13 22:02:47 +00002976 DeclContext::lookup_const_iterator Con, ConEnd;
2977 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2978 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002979 // FIXME: In C++0x, a constructor template can be a default constructor.
2980 if (isa<FunctionTemplateDecl>(*Con))
2981 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00002982 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2983 if (Constructor->isDefaultConstructor()) {
2984 const FunctionProtoType *CPT
2985 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00002986 if (CPT->getExceptionSpecType() == EST_Delayed)
2987 return false;
Sebastian Redl751025d2010-09-13 22:02:47 +00002988 // TODO: check whether evaluating default arguments can throw.
2989 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002990 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
Sebastian Redl751025d2010-09-13 22:02:47 +00002991 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002992 }
2993 }
2994 return false;
2995 case UTT_HasVirtualDestructor:
2996 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2997 // If type is a class type with a virtual destructor ([class.dtor])
2998 // then the trait is true, else it is false.
2999 if (const RecordType *Record = T->getAs<RecordType>()) {
3000 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00003001 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003002 return Destructor->isVirtual();
3003 }
3004 return false;
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003005
3006 // These type trait expressions are modeled on the specifications for the
3007 // Embarcadero C++0x type trait functions:
3008 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3009 case UTT_IsCompleteType:
3010 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3011 // Returns True if and only if T is a complete type at the point of the
3012 // function call.
3013 return !T->isIncompleteType();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003014 }
Chandler Carruth83f563c2011-05-01 07:44:17 +00003015 llvm_unreachable("Type trait not covered by switch");
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003016}
3017
3018ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00003019 SourceLocation KWLoc,
3020 TypeSourceInfo *TSInfo,
3021 SourceLocation RParen) {
3022 QualType T = TSInfo->getType();
Chandler Carrutheb65a102011-04-30 10:07:32 +00003023 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
3024 return ExprError();
Sebastian Redl64b45f72009-01-05 20:52:13 +00003025
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003026 bool Value = false;
3027 if (!T->isDependentType())
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00003028 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003029
3030 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00003031 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00003032}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003033
Francois Pichet6ad6f282010-12-07 00:08:36 +00003034ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
3035 SourceLocation KWLoc,
3036 ParsedType LhsTy,
3037 ParsedType RhsTy,
3038 SourceLocation RParen) {
3039 TypeSourceInfo *LhsTSInfo;
3040 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3041 if (!LhsTSInfo)
3042 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3043
3044 TypeSourceInfo *RhsTSInfo;
3045 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3046 if (!RhsTSInfo)
3047 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3048
3049 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3050}
3051
3052static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3053 QualType LhsT, QualType RhsT,
3054 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003055 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3056 "Cannot evaluate traits of dependent types");
Francois Pichet6ad6f282010-12-07 00:08:36 +00003057
3058 switch(BTT) {
John McCalld89d30f2011-01-28 22:02:36 +00003059 case BTT_IsBaseOf: {
Francois Pichet6ad6f282010-12-07 00:08:36 +00003060 // C++0x [meta.rel]p2
John McCalld89d30f2011-01-28 22:02:36 +00003061 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet6ad6f282010-12-07 00:08:36 +00003062 // Base and Derived are not unions and name the same class type without
3063 // regard to cv-qualifiers.
Francois Pichet6ad6f282010-12-07 00:08:36 +00003064
John McCalld89d30f2011-01-28 22:02:36 +00003065 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3066 if (!lhsRecord) return false;
3067
3068 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3069 if (!rhsRecord) return false;
3070
3071 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3072 == (lhsRecord == rhsRecord));
3073
3074 if (lhsRecord == rhsRecord)
3075 return !lhsRecord->getDecl()->isUnion();
3076
3077 // C++0x [meta.rel]p2:
3078 // If Base and Derived are class types and are different types
3079 // (ignoring possible cv-qualifiers) then Derived shall be a
3080 // complete type.
3081 if (Self.RequireCompleteType(KeyLoc, RhsT,
3082 diag::err_incomplete_type_used_in_type_trait_expr))
3083 return false;
3084
3085 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3086 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3087 }
John Wiegley20c0da72011-04-27 23:09:49 +00003088 case BTT_IsSame:
3089 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichetf1872372010-12-08 22:35:30 +00003090 case BTT_TypeCompatible:
3091 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3092 RhsT.getUnqualifiedType());
John Wiegley20c0da72011-04-27 23:09:49 +00003093 case BTT_IsConvertible:
Douglas Gregor9f361132011-01-27 20:28:01 +00003094 case BTT_IsConvertibleTo: {
3095 // C++0x [meta.rel]p4:
3096 // Given the following function prototype:
3097 //
3098 // template <class T>
3099 // typename add_rvalue_reference<T>::type create();
3100 //
3101 // the predicate condition for a template specialization
3102 // is_convertible<From, To> shall be satisfied if and only if
3103 // the return expression in the following code would be
3104 // well-formed, including any implicit conversions to the return
3105 // type of the function:
3106 //
3107 // To test() {
3108 // return create<From>();
3109 // }
3110 //
3111 // Access checking is performed as if in a context unrelated to To and
3112 // From. Only the validity of the immediate context of the expression
3113 // of the return-statement (including conversions to the return type)
3114 // is considered.
3115 //
3116 // We model the initialization as a copy-initialization of a temporary
3117 // of the appropriate type, which for this expression is identical to the
3118 // return statement (since NRVO doesn't apply).
3119 if (LhsT->isObjectType() || LhsT->isFunctionType())
3120 LhsT = Self.Context.getRValueReferenceType(LhsT);
3121
3122 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorb608b982011-01-28 02:26:04 +00003123 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor9f361132011-01-27 20:28:01 +00003124 Expr::getValueKindForType(LhsT));
3125 Expr *FromPtr = &From;
3126 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3127 SourceLocation()));
3128
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003129 // Perform the initialization within a SFINAE trap at translation unit
3130 // scope.
3131 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3132 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor9f361132011-01-27 20:28:01 +00003133 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003134 if (Init.Failed())
Douglas Gregor9f361132011-01-27 20:28:01 +00003135 return false;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003136
Douglas Gregor9f361132011-01-27 20:28:01 +00003137 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
3138 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3139 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003140 }
3141 llvm_unreachable("Unknown type trait or not implemented");
3142}
3143
3144ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3145 SourceLocation KWLoc,
3146 TypeSourceInfo *LhsTSInfo,
3147 TypeSourceInfo *RhsTSInfo,
3148 SourceLocation RParen) {
3149 QualType LhsT = LhsTSInfo->getType();
3150 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003151
John McCalld89d30f2011-01-28 22:02:36 +00003152 if (BTT == BTT_TypeCompatible) {
Francois Pichetf1872372010-12-08 22:35:30 +00003153 if (getLangOptions().CPlusPlus) {
3154 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3155 << SourceRange(KWLoc, RParen);
3156 return ExprError();
3157 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003158 }
3159
3160 bool Value = false;
3161 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3162 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3163
Francois Pichetf1872372010-12-08 22:35:30 +00003164 // Select trait result type.
3165 QualType ResultType;
3166 switch (BTT) {
Francois Pichetf1872372010-12-08 22:35:30 +00003167 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
John Wiegley20c0da72011-04-27 23:09:49 +00003168 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3169 case BTT_IsSame: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003170 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor9f361132011-01-27 20:28:01 +00003171 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003172 }
3173
Francois Pichet6ad6f282010-12-07 00:08:36 +00003174 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3175 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00003176 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00003177}
3178
John Wiegley21ff2e52011-04-28 00:16:57 +00003179ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3180 SourceLocation KWLoc,
3181 ParsedType Ty,
3182 Expr* DimExpr,
3183 SourceLocation RParen) {
3184 TypeSourceInfo *TSInfo;
3185 QualType T = GetTypeFromParser(Ty, &TSInfo);
3186 if (!TSInfo)
3187 TSInfo = Context.getTrivialTypeSourceInfo(T);
3188
3189 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3190}
3191
3192static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3193 QualType T, Expr *DimExpr,
3194 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003195 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley21ff2e52011-04-28 00:16:57 +00003196
3197 switch(ATT) {
3198 case ATT_ArrayRank:
3199 if (T->isArrayType()) {
3200 unsigned Dim = 0;
3201 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3202 ++Dim;
3203 T = AT->getElementType();
3204 }
3205 return Dim;
John Wiegley21ff2e52011-04-28 00:16:57 +00003206 }
John Wiegleycf566412011-04-28 02:06:46 +00003207 return 0;
3208
John Wiegley21ff2e52011-04-28 00:16:57 +00003209 case ATT_ArrayExtent: {
3210 llvm::APSInt Value;
3211 uint64_t Dim;
John Wiegleycf566412011-04-28 02:06:46 +00003212 if (DimExpr->isIntegerConstantExpr(Value, Self.Context, 0, false)) {
3213 if (Value < llvm::APSInt(Value.getBitWidth(), Value.isUnsigned())) {
3214 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3215 DimExpr->getSourceRange();
3216 return false;
3217 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003218 Dim = Value.getLimitedValue();
John Wiegleycf566412011-04-28 02:06:46 +00003219 } else {
3220 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3221 DimExpr->getSourceRange();
3222 return false;
3223 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003224
3225 if (T->isArrayType()) {
3226 unsigned D = 0;
3227 bool Matched = false;
3228 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3229 if (Dim == D) {
3230 Matched = true;
3231 break;
3232 }
3233 ++D;
3234 T = AT->getElementType();
3235 }
3236
John Wiegleycf566412011-04-28 02:06:46 +00003237 if (Matched && T->isArrayType()) {
3238 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3239 return CAT->getSize().getLimitedValue();
3240 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003241 }
John Wiegleycf566412011-04-28 02:06:46 +00003242 return 0;
John Wiegley21ff2e52011-04-28 00:16:57 +00003243 }
3244 }
3245 llvm_unreachable("Unknown type trait or not implemented");
3246}
3247
3248ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3249 SourceLocation KWLoc,
3250 TypeSourceInfo *TSInfo,
3251 Expr* DimExpr,
3252 SourceLocation RParen) {
3253 QualType T = TSInfo->getType();
John Wiegley21ff2e52011-04-28 00:16:57 +00003254
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003255 // FIXME: This should likely be tracked as an APInt to remove any host
3256 // assumptions about the width of size_t on the target.
Chandler Carruthd064c702011-05-01 08:41:10 +00003257 uint64_t Value = 0;
3258 if (!T->isDependentType())
3259 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3260
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003261 // While the specification for these traits from the Embarcadero C++
3262 // compiler's documentation says the return type is 'unsigned int', Clang
3263 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3264 // compiler, there is no difference. On several other platforms this is an
3265 // important distinction.
John Wiegley21ff2e52011-04-28 00:16:57 +00003266 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
Chandler Carruth06207f62011-05-01 07:49:26 +00003267 DimExpr, RParen,
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003268 Context.getSizeType()));
John Wiegley21ff2e52011-04-28 00:16:57 +00003269}
3270
John Wiegley55262202011-04-25 06:54:41 +00003271ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003272 SourceLocation KWLoc,
3273 Expr *Queried,
3274 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003275 // If error parsing the expression, ignore.
3276 if (!Queried)
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003277 return ExprError();
John Wiegley55262202011-04-25 06:54:41 +00003278
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003279 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegley55262202011-04-25 06:54:41 +00003280
3281 return move(Result);
3282}
3283
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003284static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3285 switch (ET) {
3286 case ET_IsLValueExpr: return E->isLValue();
3287 case ET_IsRValueExpr: return E->isRValue();
3288 }
3289 llvm_unreachable("Expression trait not covered by switch");
3290}
3291
John Wiegley55262202011-04-25 06:54:41 +00003292ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003293 SourceLocation KWLoc,
3294 Expr *Queried,
3295 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003296 if (Queried->isTypeDependent()) {
3297 // Delay type-checking for type-dependent expressions.
3298 } else if (Queried->getType()->isPlaceholderType()) {
3299 ExprResult PE = CheckPlaceholderExpr(Queried);
3300 if (PE.isInvalid()) return ExprError();
3301 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3302 }
3303
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003304 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf7ef0002011-05-01 08:48:19 +00003305
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003306 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3307 RParen, Context.BoolTy));
John Wiegley55262202011-04-25 06:54:41 +00003308}
3309
Richard Trieudd225092011-09-15 21:56:47 +00003310QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCallf89e55a2010-11-18 06:31:45 +00003311 ExprValueKind &VK,
3312 SourceLocation Loc,
3313 bool isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003314 assert(!LHS.get()->getType()->isPlaceholderType() &&
3315 !RHS.get()->getType()->isPlaceholderType() &&
John McCallea4aba02011-06-30 17:15:34 +00003316 "placeholders should have been weeded out by now");
3317
3318 // The LHS undergoes lvalue conversions if this is ->*.
3319 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003320 LHS = DefaultLvalueConversion(LHS.take());
3321 if (LHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003322 }
3323
3324 // The RHS always undergoes lvalue conversions.
Richard Trieudd225092011-09-15 21:56:47 +00003325 RHS = DefaultLvalueConversion(RHS.take());
3326 if (RHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003327
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003328 const char *OpSpelling = isIndirect ? "->*" : ".*";
3329 // C++ 5.5p2
3330 // The binary operator .* [p3: ->*] binds its second operand, which shall
3331 // be of type "pointer to member of T" (where T is a completely-defined
3332 // class type) [...]
Richard Trieudd225092011-09-15 21:56:47 +00003333 QualType RHSType = RHS.get()->getType();
3334 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00003335 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003336 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieudd225092011-09-15 21:56:47 +00003337 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003338 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00003339 }
Douglas Gregore7450f52009-03-24 19:52:54 +00003340
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003341 QualType Class(MemPtr->getClass(), 0);
3342
Douglas Gregor7d520ba2010-10-13 20:41:14 +00003343 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3344 // member pointer points must be completely-defined. However, there is no
3345 // reason for this semantic distinction, and the rule is not enforced by
3346 // other compilers. Therefore, we do not check this property, as it is
3347 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00003348
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003349 // C++ 5.5p2
3350 // [...] to its first operand, which shall be of class T or of a class of
3351 // which T is an unambiguous and accessible base class. [p3: a pointer to
3352 // such a class]
Richard Trieudd225092011-09-15 21:56:47 +00003353 QualType LHSType = LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003354 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003355 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
3356 LHSType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003357 else {
3358 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieudd225092011-09-15 21:56:47 +00003359 << OpSpelling << 1 << LHSType
Douglas Gregor849b2432010-03-31 17:46:05 +00003360 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003361 return QualType();
3362 }
3363 }
3364
Richard Trieudd225092011-09-15 21:56:47 +00003365 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00003366 // If we want to check the hierarchy, we need a complete type.
Richard Trieudd225092011-09-15 21:56:47 +00003367 if (RequireCompleteType(Loc, LHSType, PDiag(diag::err_bad_memptr_lhs)
Sebastian Redl17e1d352010-04-23 17:18:26 +00003368 << OpSpelling << (int)isIndirect)) {
3369 return QualType();
3370 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003371 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00003372 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00003373 // FIXME: Would it be useful to print full ambiguity paths, or is that
3374 // overkill?
Richard Trieudd225092011-09-15 21:56:47 +00003375 if (!IsDerivedFrom(LHSType, Class, Paths) ||
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003376 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3377 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieudd225092011-09-15 21:56:47 +00003378 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003379 return QualType();
3380 }
Eli Friedman3005efe2010-01-16 00:00:48 +00003381 // Cast LHS to type of use.
3382 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00003383 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00003384
John McCallf871d0c2010-08-07 06:22:56 +00003385 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003386 BuildBasePathArray(Paths, BasePath);
Richard Trieudd225092011-09-15 21:56:47 +00003387 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
3388 &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003389 }
3390
Richard Trieudd225092011-09-15 21:56:47 +00003391 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00003392 // Diagnose use of pointer-to-member type which when used as
3393 // the functional cast in a pointer-to-member expression.
3394 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3395 return QualType();
3396 }
John McCallf89e55a2010-11-18 06:31:45 +00003397
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003398 // C++ 5.5p2
3399 // The result is an object or a function of the type specified by the
3400 // second operand.
3401 // The cv qualifiers are the union of those in the pointer and the left side,
3402 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003403 QualType Result = MemPtr->getPointeeType();
Richard Trieudd225092011-09-15 21:56:47 +00003404 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00003405
Douglas Gregor6b4df912011-01-26 16:40:18 +00003406 // C++0x [expr.mptr.oper]p6:
3407 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003408 // ill-formed if the second operand is a pointer to member function with
3409 // ref-qualifier &. In a ->* expression or in a .* expression whose object
3410 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor6b4df912011-01-26 16:40:18 +00003411 // is a pointer to member function with ref-qualifier &&.
3412 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3413 switch (Proto->getRefQualifier()) {
3414 case RQ_None:
3415 // Do nothing
3416 break;
3417
3418 case RQ_LValue:
Richard Trieudd225092011-09-15 21:56:47 +00003419 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003420 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003421 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003422 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003423
Douglas Gregor6b4df912011-01-26 16:40:18 +00003424 case RQ_RValue:
Richard Trieudd225092011-09-15 21:56:47 +00003425 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003426 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003427 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003428 break;
3429 }
3430 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003431
John McCallf89e55a2010-11-18 06:31:45 +00003432 // C++ [expr.mptr.oper]p6:
3433 // The result of a .* expression whose second operand is a pointer
3434 // to a data member is of the same value category as its
3435 // first operand. The result of a .* expression whose second
3436 // operand is a pointer to a member function is a prvalue. The
3437 // result of an ->* expression is an lvalue if its second operand
3438 // is a pointer to data member and a prvalue otherwise.
John McCall864c0412011-04-26 20:42:42 +00003439 if (Result->isFunctionType()) {
John McCallf89e55a2010-11-18 06:31:45 +00003440 VK = VK_RValue;
John McCall864c0412011-04-26 20:42:42 +00003441 return Context.BoundMemberTy;
3442 } else if (isIndirect) {
John McCallf89e55a2010-11-18 06:31:45 +00003443 VK = VK_LValue;
John McCall864c0412011-04-26 20:42:42 +00003444 } else {
Richard Trieudd225092011-09-15 21:56:47 +00003445 VK = LHS.get()->getValueKind();
John McCall864c0412011-04-26 20:42:42 +00003446 }
John McCallf89e55a2010-11-18 06:31:45 +00003447
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003448 return Result;
3449}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003450
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003451/// \brief Try to convert a type to another according to C++0x 5.16p3.
3452///
3453/// This is part of the parameter validation for the ? operator. If either
3454/// value operand is a class type, the two operands are attempted to be
3455/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003456/// It returns true if the program is ill-formed and has already been diagnosed
3457/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003458static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3459 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00003460 bool &HaveConversion,
3461 QualType &ToType) {
3462 HaveConversion = false;
3463 ToType = To->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003464
3465 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003466 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003467 // C++0x 5.16p3
3468 // The process for determining whether an operand expression E1 of type T1
3469 // can be converted to match an operand expression E2 of type T2 is defined
3470 // as follows:
3471 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00003472 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003473 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003474 // E1 can be converted to match E2 if E1 can be implicitly converted to
3475 // type "lvalue reference to T2", subject to the constraint that in the
3476 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003477 QualType T = Self.Context.getLValueReferenceType(ToType);
3478 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003479
Douglas Gregorb70cf442010-03-26 20:14:36 +00003480 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3481 if (InitSeq.isDirectReferenceBinding()) {
3482 ToType = T;
3483 HaveConversion = true;
3484 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003485 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003486
Douglas Gregorb70cf442010-03-26 20:14:36 +00003487 if (InitSeq.isAmbiguous())
3488 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003489 }
John McCallb1bdc622010-02-25 01:37:24 +00003490
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003491 // -- If E2 is an rvalue, or if the conversion above cannot be done:
3492 // -- if E1 and E2 have class type, and the underlying class types are
3493 // the same or one is a base class of the other:
3494 QualType FTy = From->getType();
3495 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003496 const RecordType *FRec = FTy->getAs<RecordType>();
3497 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003498 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003499 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003500 if (FRec && TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003501 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003502 // E1 can be converted to match E2 if the class of T2 is the
3503 // same type as, or a base class of, the class of T1, and
3504 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00003505 if (FRec == TRec || FDerivedFromT) {
3506 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003507 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3508 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003509 if (InitSeq) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003510 HaveConversion = true;
3511 return false;
3512 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003513
Douglas Gregorb70cf442010-03-26 20:14:36 +00003514 if (InitSeq.isAmbiguous())
3515 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003516 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003517 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003518
Douglas Gregorb70cf442010-03-26 20:14:36 +00003519 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003520 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003521
Douglas Gregorb70cf442010-03-26 20:14:36 +00003522 // -- Otherwise: E1 can be converted to match E2 if E1 can be
3523 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003524 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003525 // an rvalue).
3526 //
3527 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3528 // to the array-to-pointer or function-to-pointer conversions.
3529 if (!TTy->getAs<TagType>())
3530 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003531
Douglas Gregorb70cf442010-03-26 20:14:36 +00003532 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3533 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003534 HaveConversion = !InitSeq.Failed();
Douglas Gregorb70cf442010-03-26 20:14:36 +00003535 ToType = TTy;
3536 if (InitSeq.isAmbiguous())
3537 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3538
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003539 return false;
3540}
3541
3542/// \brief Try to find a common type for two according to C++0x 5.16p5.
3543///
3544/// This is part of the parameter validation for the ? operator. If either
3545/// value operand is a class type, overload resolution is used to find a
3546/// conversion to a common type.
John Wiegley429bb272011-04-08 18:41:53 +00003547static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth82214a82011-02-18 23:54:50 +00003548 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00003549 Expr *Args[2] = { LHS.get(), RHS.get() };
Chandler Carruth82214a82011-02-18 23:54:50 +00003550 OverloadCandidateSet CandidateSet(QuestionLoc);
3551 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3552 CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003553
3554 OverloadCandidateSet::iterator Best;
Chandler Carruth82214a82011-02-18 23:54:50 +00003555 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley429bb272011-04-08 18:41:53 +00003556 case OR_Success: {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003557 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley429bb272011-04-08 18:41:53 +00003558 ExprResult LHSRes =
3559 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3560 Best->Conversions[0], Sema::AA_Converting);
3561 if (LHSRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003562 break;
John Wiegley429bb272011-04-08 18:41:53 +00003563 LHS = move(LHSRes);
3564
3565 ExprResult RHSRes =
3566 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3567 Best->Conversions[1], Sema::AA_Converting);
3568 if (RHSRes.isInvalid())
3569 break;
3570 RHS = move(RHSRes);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003571 if (Best->Function)
3572 Self.MarkDeclarationReferenced(QuestionLoc, Best->Function);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003573 return false;
John Wiegley429bb272011-04-08 18:41:53 +00003574 }
3575
Douglas Gregor20093b42009-12-09 23:02:17 +00003576 case OR_No_Viable_Function:
Chandler Carruth82214a82011-02-18 23:54:50 +00003577
3578 // Emit a better diagnostic if one of the expressions is a null pointer
3579 // constant and the other is a pointer type. In this case, the user most
3580 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00003581 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00003582 return true;
3583
3584 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003585 << LHS.get()->getType() << RHS.get()->getType()
3586 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003587 return true;
3588
Douglas Gregor20093b42009-12-09 23:02:17 +00003589 case OR_Ambiguous:
Chandler Carruth82214a82011-02-18 23:54:50 +00003590 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley429bb272011-04-08 18:41:53 +00003591 << LHS.get()->getType() << RHS.get()->getType()
3592 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00003593 // FIXME: Print the possible common types by printing the return types of
3594 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003595 break;
3596
Douglas Gregor20093b42009-12-09 23:02:17 +00003597 case OR_Deleted:
David Blaikieb219cfc2011-09-23 05:06:16 +00003598 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003599 }
3600 return true;
3601}
3602
Sebastian Redl76458502009-04-17 16:30:52 +00003603/// \brief Perform an "extended" implicit conversion as returned by
3604/// TryClassUnification.
John Wiegley429bb272011-04-08 18:41:53 +00003605static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003606 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley429bb272011-04-08 18:41:53 +00003607 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003608 SourceLocation());
John Wiegley429bb272011-04-08 18:41:53 +00003609 Expr *Arg = E.take();
3610 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
3611 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00003612 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00003613 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003614
John Wiegley429bb272011-04-08 18:41:53 +00003615 E = Result;
Sebastian Redl76458502009-04-17 16:30:52 +00003616 return false;
3617}
3618
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003619/// \brief Check the operands of ?: under C++ semantics.
3620///
3621/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
3622/// extension. In this case, LHS == Cond. (But they're not aliases.)
John Wiegley429bb272011-04-08 18:41:53 +00003623QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCall56ca35d2011-02-17 10:25:35 +00003624 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003625 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00003626 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
3627 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003628
3629 // C++0x 5.16p1
3630 // The first expression is contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00003631 if (!Cond.get()->isTypeDependent()) {
3632 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
3633 if (CondRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003634 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003635 Cond = move(CondRes);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003636 }
3637
John McCallf89e55a2010-11-18 06:31:45 +00003638 // Assume r-value.
3639 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00003640 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00003641
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003642 // Either of the arguments dependent?
John Wiegley429bb272011-04-08 18:41:53 +00003643 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003644 return Context.DependentTy;
3645
3646 // C++0x 5.16p2
3647 // If either the second or the third operand has type (cv) void, ...
John Wiegley429bb272011-04-08 18:41:53 +00003648 QualType LTy = LHS.get()->getType();
3649 QualType RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003650 bool LVoid = LTy->isVoidType();
3651 bool RVoid = RTy->isVoidType();
3652 if (LVoid || RVoid) {
3653 // ... then the [l2r] conversions are performed on the second and third
3654 // operands ...
John Wiegley429bb272011-04-08 18:41:53 +00003655 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3656 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3657 if (LHS.isInvalid() || RHS.isInvalid())
3658 return QualType();
3659 LTy = LHS.get()->getType();
3660 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003661
3662 // ... and one of the following shall hold:
3663 // -- The second or the third operand (but not both) is a throw-
3664 // expression; the result is of the type of the other and is an rvalue.
John Wiegley429bb272011-04-08 18:41:53 +00003665 bool LThrow = isa<CXXThrowExpr>(LHS.get());
3666 bool RThrow = isa<CXXThrowExpr>(RHS.get());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003667 if (LThrow && !RThrow)
3668 return RTy;
3669 if (RThrow && !LThrow)
3670 return LTy;
3671
3672 // -- Both the second and third operands have type void; the result is of
3673 // type void and is an rvalue.
3674 if (LVoid && RVoid)
3675 return Context.VoidTy;
3676
3677 // Neither holds, error.
3678 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3679 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley429bb272011-04-08 18:41:53 +00003680 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003681 return QualType();
3682 }
3683
3684 // Neither is void.
3685
3686 // C++0x 5.16p3
3687 // Otherwise, if the second and third operand have different types, and
3688 // either has (cv) class type, and attempt is made to convert each of those
3689 // operands to the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003690 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003691 (LTy->isRecordType() || RTy->isRecordType())) {
3692 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3693 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003694 QualType L2RType, R2LType;
3695 bool HaveL2R, HaveR2L;
John Wiegley429bb272011-04-08 18:41:53 +00003696 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003697 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003698 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003699 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003700
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003701 // If both can be converted, [...] the program is ill-formed.
3702 if (HaveL2R && HaveR2L) {
3703 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley429bb272011-04-08 18:41:53 +00003704 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003705 return QualType();
3706 }
3707
3708 // If exactly one conversion is possible, that conversion is applied to
3709 // the chosen operand and the converted operands are used in place of the
3710 // original operands for the remainder of this section.
3711 if (HaveL2R) {
John Wiegley429bb272011-04-08 18:41:53 +00003712 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003713 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003714 LTy = LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003715 } else if (HaveR2L) {
John Wiegley429bb272011-04-08 18:41:53 +00003716 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003717 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003718 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003719 }
3720 }
3721
3722 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00003723 // If the second and third operands are glvalues of the same value
3724 // category and have the same type, the result is of that type and
3725 // value category and it is a bit-field if the second or the third
3726 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00003727 // We only extend this to bitfields, not to the crazy other kinds of
3728 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003729 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00003730 if (Same &&
John Wiegley429bb272011-04-08 18:41:53 +00003731 LHS.get()->isGLValue() &&
3732 LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
3733 LHS.get()->isOrdinaryOrBitFieldObject() &&
3734 RHS.get()->isOrdinaryOrBitFieldObject()) {
3735 VK = LHS.get()->getValueKind();
3736 if (LHS.get()->getObjectKind() == OK_BitField ||
3737 RHS.get()->getObjectKind() == OK_BitField)
John McCall09431682010-11-18 19:01:18 +00003738 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00003739 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00003740 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003741
3742 // C++0x 5.16p5
3743 // Otherwise, the result is an rvalue. If the second and third operands
3744 // do not have the same type, and either has (cv) class type, ...
3745 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3746 // ... overload resolution is used to determine the conversions (if any)
3747 // to be applied to the operands. If the overload resolution fails, the
3748 // program is ill-formed.
3749 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3750 return QualType();
3751 }
3752
3753 // C++0x 5.16p6
3754 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3755 // conversions are performed on the second and third operands.
John Wiegley429bb272011-04-08 18:41:53 +00003756 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3757 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3758 if (LHS.isInvalid() || RHS.isInvalid())
3759 return QualType();
3760 LTy = LHS.get()->getType();
3761 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003762
3763 // After those conversions, one of the following shall hold:
3764 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00003765 // is of that type. If the operands have class type, the result
3766 // is a prvalue temporary of the result type, which is
3767 // copy-initialized from either the second operand or the third
3768 // operand depending on the value of the first operand.
3769 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3770 if (LTy->isRecordType()) {
3771 // The operands have class type. Make a temporary copy.
3772 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003773 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3774 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00003775 LHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00003776 if (LHSCopy.isInvalid())
3777 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003778
3779 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3780 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00003781 RHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00003782 if (RHSCopy.isInvalid())
3783 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003784
John Wiegley429bb272011-04-08 18:41:53 +00003785 LHS = LHSCopy;
3786 RHS = RHSCopy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003787 }
3788
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003789 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003790 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003791
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003792 // Extension: conditional operator involving vector types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003793 if (LTy->isVectorType() || RTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00003794 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003795
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003796 // -- The second and third operands have arithmetic or enumeration type;
3797 // the usual arithmetic conversions are performed to bring them to a
3798 // common type, and the result is of that type.
3799 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3800 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00003801 if (LHS.isInvalid() || RHS.isInvalid())
3802 return QualType();
3803 return LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003804 }
3805
3806 // -- The second and third operands have pointer type, or one has pointer
3807 // type and the other is a null pointer constant; pointer conversions
3808 // and qualification conversions are performed to bring them to their
3809 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00003810 // -- The second and third operands have pointer to member type, or one has
3811 // pointer to member type and the other is a null pointer constant;
3812 // pointer to member conversions and qualification conversions are
3813 // performed to bring them to a common type, whose cv-qualification
3814 // shall match the cv-qualification of either the second or the third
3815 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003816 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003817 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003818 isSFINAEContext()? 0 : &NonStandardCompositeType);
3819 if (!Composite.isNull()) {
3820 if (NonStandardCompositeType)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003821 Diag(QuestionLoc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003822 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3823 << LTy << RTy << Composite
John Wiegley429bb272011-04-08 18:41:53 +00003824 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003825
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003826 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003827 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003828
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003829 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00003830 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3831 if (!Composite.isNull())
3832 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003833
Chandler Carruth7ef93242011-02-19 00:13:59 +00003834 // Check if we are using a null with a non-pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00003835 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth7ef93242011-02-19 00:13:59 +00003836 return QualType();
3837
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003838 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003839 << LHS.get()->getType() << RHS.get()->getType()
3840 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003841 return QualType();
3842}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003843
3844/// \brief Find a merged pointer type and convert the two expressions to it.
3845///
Douglas Gregor20b3e992009-08-24 17:42:35 +00003846/// This finds the composite pointer type (or member pointer type) for @p E1
3847/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3848/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003849/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003850///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003851/// \param Loc The location of the operator requiring these two expressions to
3852/// be converted to the composite pointer type.
3853///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003854/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3855/// a non-standard (but still sane) composite type to which both expressions
3856/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3857/// will be set true.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003858QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003859 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003860 bool *NonStandardCompositeType) {
3861 if (NonStandardCompositeType)
3862 *NonStandardCompositeType = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003863
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003864 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3865 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003866
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00003867 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3868 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00003869 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003870
3871 // C++0x 5.9p2
3872 // Pointer conversions and qualification conversions are performed on
3873 // pointer operands to bring them to their composite pointer type. If
3874 // one operand is a null pointer constant, the composite pointer type is
3875 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00003876 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003877 if (T2->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00003878 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003879 else
John Wiegley429bb272011-04-08 18:41:53 +00003880 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003881 return T2;
3882 }
Douglas Gregorce940492009-09-25 04:25:58 +00003883 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003884 if (T1->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00003885 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003886 else
John Wiegley429bb272011-04-08 18:41:53 +00003887 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003888 return T1;
3889 }
Mike Stump1eb44332009-09-09 15:08:12 +00003890
Douglas Gregor20b3e992009-08-24 17:42:35 +00003891 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003892 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3893 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003894 return QualType();
3895
3896 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3897 // the other has type "pointer to cv2 T" and the composite pointer type is
3898 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3899 // Otherwise, the composite pointer type is a pointer type similar to the
3900 // type of one of the operands, with a cv-qualification signature that is
3901 // the union of the cv-qualification signatures of the operand types.
3902 // In practice, the first part here is redundant; it's subsumed by the second.
3903 // What we do here is, we build the two possible composite types, and try the
3904 // conversions in both directions. If only one works, or if the two composite
3905 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00003906 // FIXME: extended qualifiers?
Chris Lattner5f9e2722011-07-23 10:55:15 +00003907 typedef SmallVector<unsigned, 4> QualifierVector;
Sebastian Redla439e6f2009-11-16 21:03:45 +00003908 QualifierVector QualifierUnion;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003909 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
Sebastian Redla439e6f2009-11-16 21:03:45 +00003910 ContainingClassVector;
3911 ContainingClassVector MemberOfClass;
3912 QualType Composite1 = Context.getCanonicalType(T1),
3913 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003914 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00003915 do {
3916 const PointerType *Ptr1, *Ptr2;
3917 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3918 (Ptr2 = Composite2->getAs<PointerType>())) {
3919 Composite1 = Ptr1->getPointeeType();
3920 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003921
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003922 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003923 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003924 if (NonStandardCompositeType &&
3925 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3926 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003927
Douglas Gregor20b3e992009-08-24 17:42:35 +00003928 QualifierUnion.push_back(
3929 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3930 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3931 continue;
3932 }
Mike Stump1eb44332009-09-09 15:08:12 +00003933
Douglas Gregor20b3e992009-08-24 17:42:35 +00003934 const MemberPointerType *MemPtr1, *MemPtr2;
3935 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3936 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3937 Composite1 = MemPtr1->getPointeeType();
3938 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003939
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003940 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003941 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003942 if (NonStandardCompositeType &&
3943 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3944 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003945
Douglas Gregor20b3e992009-08-24 17:42:35 +00003946 QualifierUnion.push_back(
3947 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3948 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3949 MemPtr2->getClass()));
3950 continue;
3951 }
Mike Stump1eb44332009-09-09 15:08:12 +00003952
Douglas Gregor20b3e992009-08-24 17:42:35 +00003953 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00003954
Douglas Gregor20b3e992009-08-24 17:42:35 +00003955 // Cannot unwrap any more types.
3956 break;
3957 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00003958
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003959 if (NeedConstBefore && NonStandardCompositeType) {
3960 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003961 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003962 // requirements of C++ [conv.qual]p4 bullet 3.
3963 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3964 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3965 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3966 *NonStandardCompositeType = true;
3967 }
3968 }
3969 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003970
Douglas Gregor20b3e992009-08-24 17:42:35 +00003971 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003972 ContainingClassVector::reverse_iterator MOC
3973 = MemberOfClass.rbegin();
3974 for (QualifierVector::reverse_iterator
3975 I = QualifierUnion.rbegin(),
3976 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00003977 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00003978 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003979 if (MOC->first && MOC->second) {
3980 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00003981 Composite1 = Context.getMemberPointerType(
3982 Context.getQualifiedType(Composite1, Quals),
3983 MOC->first);
3984 Composite2 = Context.getMemberPointerType(
3985 Context.getQualifiedType(Composite2, Quals),
3986 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003987 } else {
3988 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00003989 Composite1
3990 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3991 Composite2
3992 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00003993 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003994 }
3995
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003996 // Try to convert to the first composite pointer type.
3997 InitializedEntity Entity1
3998 = InitializedEntity::InitializeTemporary(Composite1);
3999 InitializationKind Kind
4000 = InitializationKind::CreateCopy(Loc, SourceLocation());
4001 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
4002 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00004003
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004004 if (E1ToC1 && E2ToC1) {
4005 // Conversion to Composite1 is viable.
4006 if (!Context.hasSameType(Composite1, Composite2)) {
4007 // Composite2 is a different type from Composite1. Check whether
4008 // Composite2 is also viable.
4009 InitializedEntity Entity2
4010 = InitializedEntity::InitializeTemporary(Composite2);
4011 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4012 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4013 if (E1ToC2 && E2ToC2) {
4014 // Both Composite1 and Composite2 are viable and are different;
4015 // this is an ambiguity.
4016 return QualType();
4017 }
4018 }
4019
4020 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004021 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004022 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004023 if (E1Result.isInvalid())
4024 return QualType();
4025 E1 = E1Result.takeAs<Expr>();
4026
4027 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004028 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004029 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004030 if (E2Result.isInvalid())
4031 return QualType();
4032 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004033
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004034 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004035 }
4036
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004037 // Check whether Composite2 is viable.
4038 InitializedEntity Entity2
4039 = InitializedEntity::InitializeTemporary(Composite2);
4040 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4041 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4042 if (!E1ToC2 || !E2ToC2)
4043 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004044
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004045 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004046 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004047 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004048 if (E1Result.isInvalid())
4049 return QualType();
4050 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004051
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004052 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004053 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004054 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004055 if (E2Result.isInvalid())
4056 return QualType();
4057 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004058
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004059 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004060}
Anders Carlsson165a0a02009-05-17 18:41:29 +00004061
John McCall60d7b3a2010-08-24 06:29:42 +00004062ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00004063 if (!E)
4064 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004065
John McCallf85e1932011-06-15 23:02:42 +00004066 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4067
4068 // If the result is a glvalue, we shouldn't bind it.
4069 if (!E->isRValue())
Anders Carlsson089c2602009-08-15 23:41:35 +00004070 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004071
John McCallf85e1932011-06-15 23:02:42 +00004072 // In ARC, calls that return a retainable type can return retained,
4073 // in which case we have to insert a consuming cast.
4074 if (getLangOptions().ObjCAutoRefCount &&
4075 E->getType()->isObjCRetainableType()) {
4076
4077 bool ReturnsRetained;
4078
4079 // For actual calls, we compute this by examining the type of the
4080 // called value.
4081 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4082 Expr *Callee = Call->getCallee()->IgnoreParens();
4083 QualType T = Callee->getType();
4084
4085 if (T == Context.BoundMemberTy) {
4086 // Handle pointer-to-members.
4087 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4088 T = BinOp->getRHS()->getType();
4089 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4090 T = Mem->getMemberDecl()->getType();
4091 }
4092
4093 if (const PointerType *Ptr = T->getAs<PointerType>())
4094 T = Ptr->getPointeeType();
4095 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4096 T = Ptr->getPointeeType();
4097 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4098 T = MemPtr->getPointeeType();
4099
4100 const FunctionType *FTy = T->getAs<FunctionType>();
4101 assert(FTy && "call to value not of function type?");
4102 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4103
4104 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4105 // type always produce a +1 object.
4106 } else if (isa<StmtExpr>(E)) {
4107 ReturnsRetained = true;
4108
4109 // For message sends and property references, we try to find an
4110 // actual method. FIXME: we should infer retention by selector in
4111 // cases where we don't have an actual method.
4112 } else {
John McCallfc4b1912011-08-03 07:02:44 +00004113 ObjCMethodDecl *D = 0;
John McCallf85e1932011-06-15 23:02:42 +00004114 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4115 D = Send->getMethodDecl();
John McCallf85e1932011-06-15 23:02:42 +00004116 }
4117
4118 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCallfc4b1912011-08-03 07:02:44 +00004119
4120 // Don't do reclaims on performSelector calls; despite their
4121 // return type, the invoked method doesn't necessarily actually
4122 // return an object.
4123 if (!ReturnsRetained &&
4124 D && D->getMethodFamily() == OMF_performSelector)
4125 return Owned(E);
John McCallf85e1932011-06-15 23:02:42 +00004126 }
4127
John McCall567c5862011-11-14 19:53:16 +00004128 // Don't reclaim an object of Class type.
4129 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4130 return Owned(E);
4131
John McCall7e5e5f42011-07-07 06:58:02 +00004132 ExprNeedsCleanups = true;
4133
John McCall33e56f32011-09-10 06:18:15 +00004134 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4135 : CK_ARCReclaimReturnedObject);
John McCall7e5e5f42011-07-07 06:58:02 +00004136 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4137 VK_RValue));
John McCallf85e1932011-06-15 23:02:42 +00004138 }
4139
4140 if (!getLangOptions().CPlusPlus)
4141 return Owned(E);
Douglas Gregor51326552009-12-24 18:51:59 +00004142
Peter Collingbournebceb7552011-11-27 22:09:28 +00004143 QualType ET = Context.getBaseElementType(E->getType());
4144 const RecordType *RT = ET->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00004145 if (!RT)
4146 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004147
John McCall86ff3082010-02-04 22:26:26 +00004148 // That should be enough to guarantee that this type is complete.
4149 // If it has a trivial destructor, we can avoid the extra copy.
Jeffrey Yasskinb7ee2e52011-01-27 19:17:54 +00004150 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall507384f2010-08-12 02:40:37 +00004151 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00004152 return Owned(E);
4153
John McCallf85e1932011-06-15 23:02:42 +00004154 CXXDestructorDecl *Destructor = LookupDestructor(RD);
4155
4156 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
4157 if (Destructor) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00004158 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00004159 CheckDestructorAccess(E->getExprLoc(), Destructor,
4160 PDiag(diag::err_access_dtor_temp)
4161 << E->getType());
John McCallf85e1932011-06-15 23:02:42 +00004162
John McCall80ee6e82011-11-10 05:35:25 +00004163 // We need a cleanup, but we don't need to remember the temporary.
John McCallf85e1932011-06-15 23:02:42 +00004164 ExprNeedsCleanups = true;
John McCallc91cc662010-04-07 00:41:46 +00004165 }
Anders Carlssondef11992009-05-30 20:36:53 +00004166 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
4167}
4168
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004169ExprResult
John McCall4765fa02010-12-06 08:20:24 +00004170Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004171 if (SubExpr.isInvalid())
4172 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004173
John McCall4765fa02010-12-06 08:20:24 +00004174 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00004175}
4176
John McCall80ee6e82011-11-10 05:35:25 +00004177Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
4178 assert(SubExpr && "sub expression can't be null!");
4179
4180 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
4181 assert(ExprCleanupObjects.size() >= FirstCleanup);
4182 assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
4183 if (!ExprNeedsCleanups)
4184 return SubExpr;
4185
4186 ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
4187 = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
4188 ExprCleanupObjects.size() - FirstCleanup);
4189
4190 Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
4191 DiscardCleanupsInEvaluationContext();
4192
4193 return E;
4194}
4195
John McCall4765fa02010-12-06 08:20:24 +00004196Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004197 assert(SubStmt && "sub statement can't be null!");
4198
John McCallf85e1932011-06-15 23:02:42 +00004199 if (!ExprNeedsCleanups)
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004200 return SubStmt;
4201
4202 // FIXME: In order to attach the temporaries, wrap the statement into
4203 // a StmtExpr; currently this is only used for asm statements.
4204 // This is hacky, either create a new CXXStmtWithTemporaries statement or
4205 // a new AsmStmtWithTemporaries.
4206 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
4207 SourceLocation(),
4208 SourceLocation());
4209 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
4210 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00004211 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004212}
4213
John McCall60d7b3a2010-08-24 06:29:42 +00004214ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004215Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00004216 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00004217 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004218 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004219 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004220 if (Result.isInvalid()) return ExprError();
4221 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004222
John McCall3c3b7f92011-10-25 17:37:35 +00004223 Result = CheckPlaceholderExpr(Base);
4224 if (Result.isInvalid()) return ExprError();
4225 Base = Result.take();
4226
John McCall9ae2f072010-08-23 23:25:46 +00004227 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004228 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004229 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00004230 // If we have a pointer to a dependent type and are using the -> operator,
4231 // the object type is the type that the pointer points to. We might still
4232 // have enough information about that type to do something useful.
4233 if (OpKind == tok::arrow)
4234 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4235 BaseType = Ptr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004236
John McCallb3d87482010-08-24 05:47:05 +00004237 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00004238 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004239 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004240 }
Mike Stump1eb44332009-09-09 15:08:12 +00004241
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004242 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00004243 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004244 // returned, with the original second operand.
4245 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00004246 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00004247 llvm::SmallPtrSet<CanQualType,8> CTypes;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004248 SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00004249 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004250
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004251 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00004252 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
4253 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004254 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00004255 Base = Result.get();
4256 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00004257 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00004258 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00004259 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00004260 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004261 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00004262 for (unsigned i = 0; i < Locations.size(); i++)
4263 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004264 return ExprError();
4265 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004266 }
Mike Stump1eb44332009-09-09 15:08:12 +00004267
Douglas Gregor31658df2009-11-20 19:58:21 +00004268 if (BaseType->isPointerType())
4269 BaseType = BaseType->getPointeeType();
4270 }
Mike Stump1eb44332009-09-09 15:08:12 +00004271
4272 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004273 // vector types or Objective-C interfaces. Just return early and let
4274 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00004275 if (!BaseType->isRecordType()) {
4276 // C++ [basic.lookup.classref]p2:
4277 // [...] If the type of the object expression is of pointer to scalar
4278 // type, the unqualified-id is looked up in the context of the complete
4279 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00004280 //
4281 // This also indicates that we should be parsing a
4282 // pseudo-destructor-name.
John McCallb3d87482010-08-24 05:47:05 +00004283 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004284 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004285 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00004286 }
Mike Stump1eb44332009-09-09 15:08:12 +00004287
Douglas Gregor03c57052009-11-17 05:17:33 +00004288 // The object type must be complete (or dependent).
4289 if (!BaseType->isDependentType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004290 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor03c57052009-11-17 05:17:33 +00004291 PDiag(diag::err_incomplete_member_access)))
4292 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004293
Douglas Gregorc68afe22009-09-03 21:38:09 +00004294 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004295 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00004296 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00004297 // type C (or of pointer to a class type C), the unqualified-id is looked
4298 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00004299 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00004300 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004301}
4302
John McCall60d7b3a2010-08-24 06:29:42 +00004303ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00004304 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00004305 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00004306 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
4307 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00004308 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004309
Douglas Gregor77549082010-02-24 21:29:12 +00004310 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00004311 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00004312 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00004313 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00004314 /*RPLoc*/ ExpectedLParenLoc);
4315}
Douglas Gregord4dca082010-02-24 18:44:31 +00004316
David Blaikie91ec7892011-12-16 16:03:09 +00004317static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *Base,
4318 tok::TokenKind& OpKind, SourceLocation OpLoc) {
4319 // C++ [expr.pseudo]p2:
4320 // The left-hand side of the dot operator shall be of scalar type. The
4321 // left-hand side of the arrow operator shall be of pointer to scalar type.
4322 // This scalar type is the object type.
4323 if (OpKind == tok::arrow) {
4324 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4325 ObjectType = Ptr->getPointeeType();
4326 } else if (!Base->isTypeDependent()) {
4327 // The user wrote "p->" when she probably meant "p."; fix it.
4328 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4329 << ObjectType << true
4330 << FixItHint::CreateReplacement(OpLoc, ".");
4331 if (S.isSFINAEContext())
4332 return true;
4333
4334 OpKind = tok::period;
4335 }
4336 }
4337
4338 return false;
4339}
4340
John McCall60d7b3a2010-08-24 06:29:42 +00004341ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004342 SourceLocation OpLoc,
4343 tok::TokenKind OpKind,
4344 const CXXScopeSpec &SS,
4345 TypeSourceInfo *ScopeTypeInfo,
4346 SourceLocation CCLoc,
4347 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004348 PseudoDestructorTypeStorage Destructed,
John McCall2d9f5fa2011-02-25 05:21:17 +00004349 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004350 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004351
John McCall9ae2f072010-08-23 23:25:46 +00004352 QualType ObjectType = Base->getType();
David Blaikie91ec7892011-12-16 16:03:09 +00004353 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4354 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004355
Douglas Gregorb57fb492010-02-24 22:38:50 +00004356 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
4357 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCall9ae2f072010-08-23 23:25:46 +00004358 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00004359 return ExprError();
4360 }
4361
4362 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004363 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb57fb492010-02-24 22:38:50 +00004364 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004365 if (DestructedTypeInfo) {
4366 QualType DestructedType = DestructedTypeInfo->getType();
4367 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004368 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCallf85e1932011-06-15 23:02:42 +00004369 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
4370 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
4371 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
4372 << ObjectType << DestructedType << Base->getSourceRange()
4373 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004374
John McCallf85e1932011-06-15 23:02:42 +00004375 // Recover by setting the destructed type to the object type.
4376 DestructedType = ObjectType;
4377 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004378 DestructedTypeStart);
John McCallf85e1932011-06-15 23:02:42 +00004379 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4380 } else if (DestructedType.getObjCLifetime() !=
4381 ObjectType.getObjCLifetime()) {
4382
4383 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
4384 // Okay: just pretend that the user provided the correctly-qualified
4385 // type.
4386 } else {
4387 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
4388 << ObjectType << DestructedType << Base->getSourceRange()
4389 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4390 }
4391
4392 // Recover by setting the destructed type to the object type.
4393 DestructedType = ObjectType;
4394 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4395 DestructedTypeStart);
4396 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4397 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004398 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00004399 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004400
Douglas Gregorb57fb492010-02-24 22:38:50 +00004401 // C++ [expr.pseudo]p2:
4402 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4403 // form
4404 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004405 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb57fb492010-02-24 22:38:50 +00004406 //
4407 // shall designate the same scalar type.
4408 if (ScopeTypeInfo) {
4409 QualType ScopeType = ScopeTypeInfo->getType();
4410 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00004411 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004412
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004413 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00004414 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00004415 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004416 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004417
Douglas Gregorb57fb492010-02-24 22:38:50 +00004418 ScopeType = QualType();
4419 ScopeTypeInfo = 0;
4420 }
4421 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004422
John McCall9ae2f072010-08-23 23:25:46 +00004423 Expr *Result
4424 = new (Context) CXXPseudoDestructorExpr(Context, Base,
4425 OpKind == tok::arrow, OpLoc,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004426 SS.getWithLocInContext(Context),
John McCall9ae2f072010-08-23 23:25:46 +00004427 ScopeTypeInfo,
4428 CCLoc,
4429 TildeLoc,
4430 Destructed);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004431
Douglas Gregorb57fb492010-02-24 22:38:50 +00004432 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00004433 return Owned(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004434
John McCall9ae2f072010-08-23 23:25:46 +00004435 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00004436}
4437
John McCall60d7b3a2010-08-24 06:29:42 +00004438ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004439 SourceLocation OpLoc,
4440 tok::TokenKind OpKind,
4441 CXXScopeSpec &SS,
4442 UnqualifiedId &FirstTypeName,
4443 SourceLocation CCLoc,
4444 SourceLocation TildeLoc,
4445 UnqualifiedId &SecondTypeName,
4446 bool HasTrailingLParen) {
Douglas Gregor77549082010-02-24 21:29:12 +00004447 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4448 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4449 "Invalid first type name in pseudo-destructor");
4450 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4451 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4452 "Invalid second type name in pseudo-destructor");
4453
John McCall9ae2f072010-08-23 23:25:46 +00004454 QualType ObjectType = Base->getType();
David Blaikie91ec7892011-12-16 16:03:09 +00004455 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4456 return ExprError();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004457
4458 // Compute the object type that we should use for name lookup purposes. Only
4459 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00004460 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004461 if (!SS.isSet()) {
John McCall2d9f5fa2011-02-25 05:21:17 +00004462 if (ObjectType->isRecordType())
4463 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallb3d87482010-08-24 05:47:05 +00004464 else if (ObjectType->isDependentType())
4465 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004466 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004467
4468 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb57fb492010-02-24 22:38:50 +00004469 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00004470 QualType DestructedType;
4471 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004472 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00004473 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004474 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00004475 SecondTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00004476 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004477 if (!T &&
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004478 ((SS.isSet() && !computeDeclContext(SS, false)) ||
4479 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004480 // The name of the type being destroyed is a dependent name, and we
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004481 // couldn't find anything useful in scope. Just store the identifier and
4482 // it's location, and we'll perform (qualified) name lookup again at
4483 // template instantiation time.
4484 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
4485 SecondTypeName.StartLocation);
4486 } else if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004487 Diag(SecondTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00004488 diag::err_pseudo_dtor_destructor_non_type)
4489 << SecondTypeName.Identifier << ObjectType;
4490 if (isSFINAEContext())
4491 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004492
Douglas Gregor77549082010-02-24 21:29:12 +00004493 // Recover by assuming we had the right type all along.
4494 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004495 } else
Douglas Gregor77549082010-02-24 21:29:12 +00004496 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004497 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004498 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00004499 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004500 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4501 TemplateId->getTemplateArgs(),
4502 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00004503 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4504 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004505 TemplateId->TemplateNameLoc,
4506 TemplateId->LAngleLoc,
4507 TemplateArgsPtr,
4508 TemplateId->RAngleLoc);
4509 if (T.isInvalid() || !T.get()) {
4510 // Recover by assuming we had the right type all along.
4511 DestructedType = ObjectType;
4512 } else
4513 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004514 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004515
4516 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb57fb492010-02-24 22:38:50 +00004517 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004518 if (!DestructedType.isNull()) {
4519 if (!DestructedTypeInfo)
4520 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004521 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004522 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4523 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004524
Douglas Gregorb57fb492010-02-24 22:38:50 +00004525 // Convert the name of the scope type (the type prior to '::') into a type.
4526 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00004527 QualType ScopeType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004528 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor77549082010-02-24 21:29:12 +00004529 FirstTypeName.Identifier) {
4530 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004531 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00004532 FirstTypeName.StartLocation,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004533 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00004534 if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004535 Diag(FirstTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00004536 diag::err_pseudo_dtor_destructor_non_type)
4537 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004538
Douglas Gregorb57fb492010-02-24 22:38:50 +00004539 if (isSFINAEContext())
4540 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004541
Douglas Gregorb57fb492010-02-24 22:38:50 +00004542 // Just drop this type. It's unnecessary anyway.
4543 ScopeType = QualType();
4544 } else
4545 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004546 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004547 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00004548 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004549 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4550 TemplateId->getTemplateArgs(),
4551 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00004552 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4553 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004554 TemplateId->TemplateNameLoc,
4555 TemplateId->LAngleLoc,
4556 TemplateArgsPtr,
4557 TemplateId->RAngleLoc);
4558 if (T.isInvalid() || !T.get()) {
4559 // Recover by dropping this type.
4560 ScopeType = QualType();
4561 } else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004562 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004563 }
4564 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004565
Douglas Gregorb4a418f2010-02-24 23:02:30 +00004566 if (!ScopeType.isNull() && !ScopeTypeInfo)
4567 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
4568 FirstTypeName.StartLocation);
4569
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004570
John McCall9ae2f072010-08-23 23:25:46 +00004571 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00004572 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004573 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00004574}
4575
David Blaikie91ec7892011-12-16 16:03:09 +00004576ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4577 SourceLocation OpLoc,
4578 tok::TokenKind OpKind,
4579 SourceLocation TildeLoc,
4580 const DeclSpec& DS,
4581 bool HasTrailingLParen) {
4582
4583 QualType ObjectType = Base->getType();
4584 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4585 return ExprError();
4586
4587 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4588
4589 TypeLocBuilder TLB;
4590 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
4591 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
4592 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
4593 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
4594
4595 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
4596 0, SourceLocation(), TildeLoc,
4597 Destructed, HasTrailingLParen);
4598}
4599
John Wiegley429bb272011-04-08 18:41:53 +00004600ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004601 CXXMethodDecl *Method,
4602 bool HadMultipleCandidates) {
John Wiegley429bb272011-04-08 18:41:53 +00004603 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
4604 FoundDecl, Method);
4605 if (Exp.isInvalid())
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004606 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00004607
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004608 MemberExpr *ME =
John Wiegley429bb272011-04-08 18:41:53 +00004609 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
Abramo Bagnara960809e2011-11-16 22:46:05 +00004610 SourceLocation(), Context.BoundMemberTy,
John McCallf89e55a2010-11-18 06:31:45 +00004611 VK_RValue, OK_Ordinary);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004612 if (HadMultipleCandidates)
4613 ME->setHadMultipleCandidates(true);
4614
John McCallf89e55a2010-11-18 06:31:45 +00004615 QualType ResultType = Method->getResultType();
4616 ExprValueKind VK = Expr::getValueKindForType(ResultType);
4617 ResultType = ResultType.getNonLValueExprType(Context);
4618
John Wiegley429bb272011-04-08 18:41:53 +00004619 MarkDeclarationReferenced(Exp.get()->getLocStart(), Method);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004620 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00004621 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
John Wiegley429bb272011-04-08 18:41:53 +00004622 Exp.get()->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00004623 return CE;
4624}
4625
Sebastian Redl2e156222010-09-10 20:55:43 +00004626ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4627 SourceLocation RParen) {
Sebastian Redl2e156222010-09-10 20:55:43 +00004628 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
4629 Operand->CanThrow(Context),
4630 KeyLoc, RParen));
4631}
4632
4633ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
4634 Expr *Operand, SourceLocation RParen) {
4635 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00004636}
4637
John McCallf6a16482010-12-04 03:47:34 +00004638/// Perform the conversions required for an expression used in a
4639/// context that ignores the result.
John Wiegley429bb272011-04-08 18:41:53 +00004640ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall3c3b7f92011-10-25 17:37:35 +00004641 if (E->hasPlaceholderType()) {
4642 ExprResult result = CheckPlaceholderExpr(E);
4643 if (result.isInvalid()) return Owned(E);
4644 E = result.take();
4645 }
4646
John McCalla878cda2010-12-02 02:07:15 +00004647 // C99 6.3.2.1:
4648 // [Except in specific positions,] an lvalue that does not have
4649 // array type is converted to the value stored in the
4650 // designated object (and is no longer an lvalue).
John McCalle6d134b2011-06-27 21:24:11 +00004651 if (E->isRValue()) {
4652 // In C, function designators (i.e. expressions of function type)
4653 // are r-values, but we still want to do function-to-pointer decay
4654 // on them. This is both technically correct and convenient for
4655 // some clients.
4656 if (!getLangOptions().CPlusPlus && E->getType()->isFunctionType())
4657 return DefaultFunctionArrayConversion(E);
4658
4659 return Owned(E);
4660 }
John McCalla878cda2010-12-02 02:07:15 +00004661
John McCallf6a16482010-12-04 03:47:34 +00004662 // Otherwise, this rule does not apply in C++, at least not for the moment.
John Wiegley429bb272011-04-08 18:41:53 +00004663 if (getLangOptions().CPlusPlus) return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004664
4665 // GCC seems to also exclude expressions of incomplete enum type.
4666 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
4667 if (!T->getDecl()->isComplete()) {
4668 // FIXME: stupid workaround for a codegen bug!
John Wiegley429bb272011-04-08 18:41:53 +00004669 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
4670 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004671 }
4672 }
4673
John Wiegley429bb272011-04-08 18:41:53 +00004674 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
4675 if (Res.isInvalid())
4676 return Owned(E);
4677 E = Res.take();
4678
John McCall85515d62010-12-04 12:29:11 +00004679 if (!E->getType()->isVoidType())
4680 RequireCompleteType(E->getExprLoc(), E->getType(),
4681 diag::err_incomplete_type);
John Wiegley429bb272011-04-08 18:41:53 +00004682 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004683}
4684
John Wiegley429bb272011-04-08 18:41:53 +00004685ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
4686 ExprResult FullExpr = Owned(FE);
4687
4688 if (!FullExpr.get())
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00004689 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00004690
John Wiegley429bb272011-04-08 18:41:53 +00004691 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregord0937222010-12-13 22:49:22 +00004692 return ExprError();
4693
Douglas Gregor5e3a8be2011-12-15 00:53:32 +00004694 // Top-level message sends default to 'id' when we're in a debugger.
4695 if (getLangOptions().DebuggerSupport &&
4696 FullExpr.get()->getType() == Context.UnknownAnyTy &&
4697 isa<ObjCMessageExpr>(FullExpr.get())) {
4698 FullExpr = forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdType());
4699 if (FullExpr.isInvalid())
4700 return ExprError();
4701 }
4702
John McCallfb8721c2011-04-10 19:13:55 +00004703 FullExpr = CheckPlaceholderExpr(FullExpr.take());
4704 if (FullExpr.isInvalid())
4705 return ExprError();
Douglas Gregor353ee242011-03-07 02:05:23 +00004706
John Wiegley429bb272011-04-08 18:41:53 +00004707 FullExpr = IgnoredValueConversions(FullExpr.take());
4708 if (FullExpr.isInvalid())
4709 return ExprError();
4710
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004711 CheckImplicitConversions(FullExpr.get(), FullExpr.get()->getExprLoc());
John McCall4765fa02010-12-06 08:20:24 +00004712 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00004713}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004714
4715StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
4716 if (!FullStmt) return StmtError();
4717
John McCall4765fa02010-12-06 08:20:24 +00004718 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004719}
Francois Pichet1e862692011-05-06 20:48:22 +00004720
Douglas Gregorba0513d2011-10-25 01:33:02 +00004721Sema::IfExistsResult
4722Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
4723 CXXScopeSpec &SS,
4724 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet1e862692011-05-06 20:48:22 +00004725 DeclarationName TargetName = TargetNameInfo.getName();
4726 if (!TargetName)
Douglas Gregor3896fc52011-10-24 22:31:10 +00004727 return IER_DoesNotExist;
Douglas Gregorba0513d2011-10-25 01:33:02 +00004728
Douglas Gregor3896fc52011-10-24 22:31:10 +00004729 // If the name itself is dependent, then the result is dependent.
4730 if (TargetName.isDependentName())
4731 return IER_Dependent;
Douglas Gregorba0513d2011-10-25 01:33:02 +00004732
Francois Pichet1e862692011-05-06 20:48:22 +00004733 // Do the redeclaration lookup in the current scope.
4734 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
4735 Sema::NotForRedeclaration);
Douglas Gregor3896fc52011-10-24 22:31:10 +00004736 LookupParsedName(R, S, &SS);
Francois Pichet1e862692011-05-06 20:48:22 +00004737 R.suppressDiagnostics();
Douglas Gregor3896fc52011-10-24 22:31:10 +00004738
4739 switch (R.getResultKind()) {
4740 case LookupResult::Found:
4741 case LookupResult::FoundOverloaded:
4742 case LookupResult::FoundUnresolvedValue:
4743 case LookupResult::Ambiguous:
4744 return IER_Exists;
4745
4746 case LookupResult::NotFound:
4747 return IER_DoesNotExist;
4748
4749 case LookupResult::NotFoundInCurrentInstantiation:
4750 return IER_Dependent;
4751 }
4752
Douglas Gregorba0513d2011-10-25 01:33:02 +00004753 return IER_DoesNotExist;
Francois Pichet1e862692011-05-06 20:48:22 +00004754}
Douglas Gregorba0513d2011-10-25 01:33:02 +00004755
Douglas Gregor65019ac2011-10-25 03:44:56 +00004756Sema::IfExistsResult
4757Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4758 bool IsIfExists, CXXScopeSpec &SS,
4759 UnqualifiedId &Name) {
Douglas Gregorba0513d2011-10-25 01:33:02 +00004760 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Douglas Gregor65019ac2011-10-25 03:44:56 +00004761
4762 // Check for unexpanded parameter packs.
4763 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
4764 collectUnexpandedParameterPacks(SS, Unexpanded);
4765 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
4766 if (!Unexpanded.empty()) {
4767 DiagnoseUnexpandedParameterPacks(KeywordLoc,
4768 IsIfExists? UPPC_IfExists
4769 : UPPC_IfNotExists,
4770 Unexpanded);
4771 return IER_Error;
4772 }
4773
Douglas Gregorba0513d2011-10-25 01:33:02 +00004774 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
4775}
4776