blob: 0db8cd494ee08a4b900f5da175507cd82f7f6742 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall2a7fb272010-08-25 05:32:35 +000015#include "clang/Sema/DeclSpec.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/ParsedTemplate.h"
John McCall469a1eb2011-02-02 13:00:07 +000019#include "clang/Sema/ScopeInfo.h"
Richard Smith7a614d82011-06-11 17:19:42 +000020#include "clang/Sema/Scope.h"
John McCall2a7fb272010-08-25 05:32:35 +000021#include "clang/Sema/TemplateDeduction.h"
Steve Naroff210679c2007-08-25 14:02:58 +000022#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000024#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000025#include "clang/AST/ExprCXX.h"
Fariborz Jahaniand4266622010-06-16 18:56:04 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregorb57fb492010-02-24 22:38:50 +000027#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000029#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000030#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Chandler Carruth73e0a912011-05-01 07:23:17 +000032#include "llvm/Support/ErrorHandling.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000034using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000035
John McCallb3d87482010-08-24 05:47:05 +000036ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000037 IdentifierInfo &II,
John McCallb3d87482010-08-24 05:47:05 +000038 SourceLocation NameLoc,
39 Scope *S, CXXScopeSpec &SS,
40 ParsedType ObjectTypePtr,
41 bool EnteringContext) {
Douglas Gregor124b8782010-02-16 19:09:40 +000042 // Determine where to perform name lookup.
43
44 // FIXME: This area of the standard is very messy, and the current
45 // wording is rather unclear about which scopes we search for the
46 // destructor name; see core issues 399 and 555. Issue 399 in
47 // particular shows where the current description of destructor name
48 // lookup is completely out of line with existing practice, e.g.,
49 // this appears to be ill-formed:
50 //
51 // namespace N {
52 // template <typename T> struct S {
53 // ~S();
54 // };
55 // }
56 //
57 // void f(N::S<int>* s) {
58 // s->N::S<int>::~S();
59 // }
60 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000061 // See also PR6358 and PR6359.
Sebastian Redlc0fee502010-07-07 23:17:38 +000062 // For this reason, we're currently only doing the C++03 version of this
63 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregor124b8782010-02-16 19:09:40 +000064 QualType SearchType;
65 DeclContext *LookupCtx = 0;
66 bool isDependent = false;
67 bool LookInScope = false;
68
69 // If we have an object type, it's because we are in a
70 // pseudo-destructor-expression or a member access expression, and
71 // we know what type we're looking for.
72 if (ObjectTypePtr)
73 SearchType = GetTypeFromParser(ObjectTypePtr);
74
75 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000076 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000077
Douglas Gregor93649fd2010-02-23 00:15:22 +000078 bool AlreadySearched = false;
79 bool LookAtPrefix = true;
Sebastian Redlc0fee502010-07-07 23:17:38 +000080 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000081 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redlc0fee502010-07-07 23:17:38 +000082 // the type-names are looked up as types in the scope designated by the
83 // nested-name-specifier. In a qualified-id of the form:
NAKAMURA Takumi00995302011-01-27 07:09:49 +000084 //
85 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redlc0fee502010-07-07 23:17:38 +000086 //
87 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth5e895a82010-02-21 10:19:54 +000088 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +000089 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +000090 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregor124b8782010-02-16 19:09:40 +000091 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000092 // the class-names are looked up as types in the scope designated by
Sebastian Redlc0fee502010-07-07 23:17:38 +000093 // the nested-name-specifier.
Douglas Gregor124b8782010-02-16 19:09:40 +000094 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000095 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000096 // code below is permitted to look at the prefix of the
Sebastian Redlc0fee502010-07-07 23:17:38 +000097 // nested-name-specifier.
98 DeclContext *DC = computeDeclContext(SS, EnteringContext);
99 if (DC && DC->isFileContext()) {
100 AlreadySearched = true;
101 LookupCtx = DC;
102 isDependent = false;
103 } else if (DC && isa<CXXRecordDecl>(DC))
104 LookAtPrefix = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000105
Sebastian Redlc0fee502010-07-07 23:17:38 +0000106 // The second case from the C++03 rules quoted further above.
Douglas Gregor93649fd2010-02-23 00:15:22 +0000107 NestedNameSpecifier *Prefix = 0;
108 if (AlreadySearched) {
109 // Nothing left to do.
110 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
111 CXXScopeSpec PrefixSS;
Douglas Gregor7e384942011-02-25 16:07:42 +0000112 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor93649fd2010-02-23 00:15:22 +0000113 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
114 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000115 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000116 LookupCtx = computeDeclContext(SearchType);
117 isDependent = SearchType->isDependentType();
118 } else {
119 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000120 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000121 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000122
Douglas Gregoredc90502010-02-25 04:46:04 +0000123 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000124 } else if (ObjectTypePtr) {
125 // C++ [basic.lookup.classref]p3:
126 // If the unqualified-id is ~type-name, the type-name is looked up
127 // in the context of the entire postfix-expression. If the type T
128 // of the object expression is of a class type C, the type-name is
129 // also looked up in the scope of class C. At least one of the
130 // lookups shall find a name that refers to (possibly
131 // cv-qualified) T.
132 LookupCtx = computeDeclContext(SearchType);
133 isDependent = SearchType->isDependentType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000134 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregor124b8782010-02-16 19:09:40 +0000135 "Caller should have completed object type");
136
137 LookInScope = true;
138 } else {
139 // Perform lookup into the current scope (only).
140 LookInScope = true;
141 }
142
Douglas Gregor7ec18732011-03-04 22:32:08 +0000143 TypeDecl *NonMatchingTypeDecl = 0;
Douglas Gregor124b8782010-02-16 19:09:40 +0000144 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
145 for (unsigned Step = 0; Step != 2; ++Step) {
146 // Look for the name first in the computed lookup context (if we
Douglas Gregor7ec18732011-03-04 22:32:08 +0000147 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregor124b8782010-02-16 19:09:40 +0000148 // we're allowed to look there).
149 Found.clear();
150 if (Step == 0 && LookupCtx)
151 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000152 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000153 LookupName(Found, S);
154 else
155 continue;
156
157 // FIXME: Should we be suppressing ambiguities here?
158 if (Found.isAmbiguous())
John McCallb3d87482010-08-24 05:47:05 +0000159 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000160
161 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
162 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000163
164 if (SearchType.isNull() || SearchType->isDependentType() ||
165 Context.hasSameUnqualifiedType(T, SearchType)) {
166 // We found our type!
167
John McCallb3d87482010-08-24 05:47:05 +0000168 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000169 }
John Wiegley36784e72011-03-08 08:13:22 +0000170
Douglas Gregor7ec18732011-03-04 22:32:08 +0000171 if (!SearchType.isNull())
172 NonMatchingTypeDecl = Type;
Douglas Gregor124b8782010-02-16 19:09:40 +0000173 }
174
175 // If the name that we found is a class template name, and it is
176 // the same name as the template name in the last part of the
177 // nested-name-specifier (if present) or the object type, then
178 // this is the destructor for that class.
179 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000180 // issue 399, for which there isn't even an obvious direction.
Douglas Gregor124b8782010-02-16 19:09:40 +0000181 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
182 QualType MemberOfType;
183 if (SS.isSet()) {
184 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
185 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000186 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
187 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000188 }
189 }
190 if (MemberOfType.isNull())
191 MemberOfType = SearchType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000192
Douglas Gregor124b8782010-02-16 19:09:40 +0000193 if (MemberOfType.isNull())
194 continue;
195
196 // We're referring into a class template specialization. If the
197 // class template we found is the same as the template being
198 // specialized, we found what we are looking for.
199 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
200 if (ClassTemplateSpecializationDecl *Spec
201 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
202 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
203 Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000204 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000205 }
206
207 continue;
208 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000209
Douglas Gregor124b8782010-02-16 19:09:40 +0000210 // We're referring to an unresolved class template
211 // specialization. Determine whether we class template we found
212 // is the same as the template being specialized or, if we don't
213 // know which template is being specialized, that it at least
214 // has the same name.
215 if (const TemplateSpecializationType *SpecType
216 = MemberOfType->getAs<TemplateSpecializationType>()) {
217 TemplateName SpecName = SpecType->getTemplateName();
218
219 // The class template we found is the same template being
220 // specialized.
221 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
222 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000223 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000224
225 continue;
226 }
227
228 // The class template we found has the same name as the
229 // (dependent) template name being specialized.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000230 if (DependentTemplateName *DepTemplate
Douglas Gregor124b8782010-02-16 19:09:40 +0000231 = SpecName.getAsDependentTemplateName()) {
232 if (DepTemplate->isIdentifier() &&
233 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallb3d87482010-08-24 05:47:05 +0000234 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000235
236 continue;
237 }
238 }
239 }
240 }
241
242 if (isDependent) {
243 // We didn't find our type, but that's okay: it's dependent
244 // anyway.
Douglas Gregore29425b2011-02-28 22:42:13 +0000245
246 // FIXME: What if we have no nested-name-specifier?
247 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
248 SS.getWithLocInContext(Context),
249 II, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000250 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000251 }
252
Douglas Gregor7ec18732011-03-04 22:32:08 +0000253 if (NonMatchingTypeDecl) {
254 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
255 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
256 << T << SearchType;
257 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
258 << T;
259 } else if (ObjectTypePtr)
260 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000261 << &II;
Douglas Gregor124b8782010-02-16 19:09:40 +0000262 else
263 Diag(NameLoc, diag::err_destructor_class_name);
264
John McCallb3d87482010-08-24 05:47:05 +0000265 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000266}
267
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000268/// \brief Build a C++ typeid expression with a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000269ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000270 SourceLocation TypeidLoc,
271 TypeSourceInfo *Operand,
272 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000273 // C++ [expr.typeid]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000274 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000275 // that is the operand of typeid are always ignored.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000276 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000277 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000278 Qualifiers Quals;
279 QualType T
280 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
281 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000282 if (T->getAs<RecordType>() &&
283 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
284 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000285
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000286 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
287 Operand,
288 SourceRange(TypeidLoc, RParenLoc)));
289}
290
291/// \brief Build a C++ typeid expression with an expression operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000292ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000293 SourceLocation TypeidLoc,
294 Expr *E,
295 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000296 bool isUnevaluatedOperand = true;
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000297 if (E && !E->isTypeDependent()) {
298 QualType T = E->getType();
299 if (const RecordType *RecordT = T->getAs<RecordType>()) {
300 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
301 // C++ [expr.typeid]p3:
302 // [...] If the type of the expression is a class type, the class
303 // shall be completely-defined.
304 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
305 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000306
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000307 // C++ [expr.typeid]p3:
Sebastian Redl906082e2010-07-20 04:20:21 +0000308 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000309 // polymorphic class type [...] [the] expression is an unevaluated
310 // operand. [...]
Sebastian Redl906082e2010-07-20 04:20:21 +0000311 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000312 isUnevaluatedOperand = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000313
314 // We require a vtable to query the type at run time.
315 MarkVTableUsed(TypeidLoc, RecordD);
316 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000317 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000318
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000319 // C++ [expr.typeid]p4:
320 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000321 // cv-qualified type, the result of the typeid expression refers to a
322 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000323 // type.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000324 Qualifiers Quals;
325 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
326 if (!Context.hasSameType(T, UnqualT)) {
327 T = UnqualT;
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +0000328 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take();
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000329 }
330 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000331
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000332 // If this is an unevaluated operand, clear out the set of
333 // declaration references we have been computing and eliminate any
334 // temporaries introduced in its computation.
335 if (isUnevaluatedOperand)
336 ExprEvalContexts.back().Context = Unevaluated;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000337
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000338 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCall9ae2f072010-08-23 23:25:46 +0000339 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000340 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000341}
342
343/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCall60d7b3a2010-08-24 06:29:42 +0000344ExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000345Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
346 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000347 // Find the std::type_info type.
Sebastian Redlce0682f2011-03-31 19:29:24 +0000348 if (!getStdNamespace())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000349 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000350
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000351 if (!CXXTypeInfoDecl) {
352 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
353 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
354 LookupQualifiedName(R, getStdNamespace());
355 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
356 if (!CXXTypeInfoDecl)
357 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
358 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000359
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000360 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000361
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000362 if (isType) {
363 // The operand is a type; handle it as such.
364 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +0000365 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
366 &TInfo);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000367 if (T.isNull())
368 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000369
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000370 if (!TInfo)
371 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000372
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000373 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000374 }
Mike Stump1eb44332009-09-09 15:08:12 +0000375
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000376 // The operand is an expression.
John McCall9ae2f072010-08-23 23:25:46 +0000377 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000378}
379
Francois Pichet6915c522010-12-27 01:32:00 +0000380/// Retrieve the UuidAttr associated with QT.
381static UuidAttr *GetUuidAttrOfType(QualType QT) {
382 // Optionally remove one level of pointer, reference or array indirection.
John McCallf4c73712011-01-19 06:33:43 +0000383 const Type *Ty = QT.getTypePtr();;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000384 if (QT->isPointerType() || QT->isReferenceType())
385 Ty = QT->getPointeeType().getTypePtr();
386 else if (QT->isArrayType())
387 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
388
Francois Pichet8db75a22011-05-08 10:02:20 +0000389 // Loop all record redeclaration looking for an uuid attribute.
Francois Pichet6915c522010-12-27 01:32:00 +0000390 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Francois Pichet8db75a22011-05-08 10:02:20 +0000391 for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(),
392 E = RD->redecls_end(); I != E; ++I) {
393 if (UuidAttr *Uuid = I->getAttr<UuidAttr>())
Francois Pichet6915c522010-12-27 01:32:00 +0000394 return Uuid;
Francois Pichet6915c522010-12-27 01:32:00 +0000395 }
Francois Pichet8db75a22011-05-08 10:02:20 +0000396
Francois Pichet6915c522010-12-27 01:32:00 +0000397 return 0;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000398}
399
Francois Pichet01b7c302010-09-08 12:20:18 +0000400/// \brief Build a Microsoft __uuidof expression with a type operand.
401ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
402 SourceLocation TypeidLoc,
403 TypeSourceInfo *Operand,
404 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000405 if (!Operand->getType()->isDependentType()) {
406 if (!GetUuidAttrOfType(Operand->getType()))
407 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
408 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000409
Francois Pichet01b7c302010-09-08 12:20:18 +0000410 // FIXME: add __uuidof semantic analysis for type operand.
411 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
412 Operand,
413 SourceRange(TypeidLoc, RParenLoc)));
414}
415
416/// \brief Build a Microsoft __uuidof expression with an expression operand.
417ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
418 SourceLocation TypeidLoc,
419 Expr *E,
420 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000421 if (!E->getType()->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000422 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichet6915c522010-12-27 01:32:00 +0000423 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
424 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
425 }
426 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet01b7c302010-09-08 12:20:18 +0000427 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
428 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000429 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet01b7c302010-09-08 12:20:18 +0000430}
431
432/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
433ExprResult
434Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
435 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000436 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet01b7c302010-09-08 12:20:18 +0000437 if (!MSVCGuidDecl) {
438 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
439 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
440 LookupQualifiedName(R, Context.getTranslationUnitDecl());
441 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
442 if (!MSVCGuidDecl)
443 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000444 }
445
Francois Pichet01b7c302010-09-08 12:20:18 +0000446 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000447
Francois Pichet01b7c302010-09-08 12:20:18 +0000448 if (isType) {
449 // The operand is a type; handle it as such.
450 TypeSourceInfo *TInfo = 0;
451 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
452 &TInfo);
453 if (T.isNull())
454 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000455
Francois Pichet01b7c302010-09-08 12:20:18 +0000456 if (!TInfo)
457 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
458
459 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
460 }
461
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000462 // The operand is an expression.
Francois Pichet01b7c302010-09-08 12:20:18 +0000463 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
464}
465
Steve Naroff1b273c42007-09-16 14:56:35 +0000466/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCall60d7b3a2010-08-24 06:29:42 +0000467ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000468Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000469 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000470 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000471 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
472 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000473}
Chris Lattner50dd2892008-02-26 00:51:44 +0000474
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000475/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCall60d7b3a2010-08-24 06:29:42 +0000476ExprResult
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000477Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
478 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
479}
480
Chris Lattner50dd2892008-02-26 00:51:44 +0000481/// ActOnCXXThrow - Parse throw expressions.
John McCall60d7b3a2010-08-24 06:29:42 +0000482ExprResult
Douglas Gregorbca01b42011-07-06 22:04:06 +0000483Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
484 bool IsThrownVarInScope = false;
485 if (Ex) {
486 // C++0x [class.copymove]p31:
487 // When certain criteria are met, an implementation is allowed to omit the
488 // copy/move construction of a class object [...]
489 //
490 // - in a throw-expression, when the operand is the name of a
491 // non-volatile automatic object (other than a function or catch-
492 // clause parameter) whose scope does not extend beyond the end of the
493 // innermost enclosing try-block (if there is one), the copy/move
494 // operation from the operand to the exception object (15.1) can be
495 // omitted by constructing the automatic object directly into the
496 // exception object
497 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
498 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
499 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
500 for( ; S; S = S->getParent()) {
501 if (S->isDeclScope(Var)) {
502 IsThrownVarInScope = true;
503 break;
504 }
505
506 if (S->getFlags() &
507 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
508 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
509 Scope::TryScope))
510 break;
511 }
512 }
513 }
514 }
515
516 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
517}
518
519ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
520 bool IsThrownVarInScope) {
Anders Carlsson729b8532011-02-23 03:46:46 +0000521 // Don't report an error if 'throw' is used in system headers.
Anders Carlsson15348ae2011-02-28 02:27:16 +0000522 if (!getLangOptions().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +0000523 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb1fba312011-02-19 21:53:09 +0000524 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Douglas Gregorbca01b42011-07-06 22:04:06 +0000525
John Wiegley429bb272011-04-08 18:41:53 +0000526 if (Ex && !Ex->isTypeDependent()) {
Douglas Gregorbca01b42011-07-06 22:04:06 +0000527 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
John Wiegley429bb272011-04-08 18:41:53 +0000528 if (ExRes.isInvalid())
529 return ExprError();
530 Ex = ExRes.take();
531 }
Douglas Gregorbca01b42011-07-06 22:04:06 +0000532
533 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
534 IsThrownVarInScope));
Sebastian Redl972041f2009-04-27 20:27:31 +0000535}
536
537/// CheckCXXThrowOperand - Validate the operand of a throw.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000538ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
539 bool IsThrownVarInScope) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000540 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000541 // A throw-expression initializes a temporary object, called the exception
542 // object, the type of which is determined by removing any top-level
543 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000544 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor154fe982009-12-23 22:04:40 +0000545 // or "pointer to function returning T", [...]
546 if (E->getType().hasQualifiers())
John Wiegley429bb272011-04-08 18:41:53 +0000547 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +0000548 E->getValueKind()).take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000549
John Wiegley429bb272011-04-08 18:41:53 +0000550 ExprResult Res = DefaultFunctionArrayConversion(E);
551 if (Res.isInvalid())
552 return ExprError();
553 E = Res.take();
Sebastian Redl972041f2009-04-27 20:27:31 +0000554
555 // If the type of the exception would be an incomplete type or a pointer
556 // to an incomplete type other than (cv) void the program is ill-formed.
557 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000558 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000559 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000560 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000561 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000562 }
563 if (!isPointer || !Ty->isVoidType()) {
564 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000565 PDiag(isPointer ? diag::err_throw_incomplete_ptr
566 : diag::err_throw_incomplete)
567 << E->getSourceRange()))
John Wiegley429bb272011-04-08 18:41:53 +0000568 return ExprError();
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000569
Douglas Gregorbf422f92010-04-15 18:05:39 +0000570 if (RequireNonAbstractType(ThrowLoc, E->getType(),
571 PDiag(diag::err_throw_abstract_type)
572 << E->getSourceRange()))
John Wiegley429bb272011-04-08 18:41:53 +0000573 return ExprError();
Sebastian Redl972041f2009-04-27 20:27:31 +0000574 }
575
John McCallac418162010-04-22 01:10:34 +0000576 // Initialize the exception result. This implicitly weeds out
577 // abstract types or types with inaccessible copy constructors.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000578
579 // C++0x [class.copymove]p31:
580 // When certain criteria are met, an implementation is allowed to omit the
581 // copy/move construction of a class object [...]
582 //
583 // - in a throw-expression, when the operand is the name of a
584 // non-volatile automatic object (other than a function or catch-clause
585 // parameter) whose scope does not extend beyond the end of the
586 // innermost enclosing try-block (if there is one), the copy/move
587 // operation from the operand to the exception object (15.1) can be
588 // omitted by constructing the automatic object directly into the
589 // exception object
590 const VarDecl *NRVOVariable = 0;
591 if (IsThrownVarInScope)
592 NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
593
John McCallac418162010-04-22 01:10:34 +0000594 InitializedEntity Entity =
Douglas Gregor72dfa272011-01-21 22:46:35 +0000595 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
Douglas Gregorbca01b42011-07-06 22:04:06 +0000596 /*NRVO=*/NRVOVariable != 0);
John Wiegley429bb272011-04-08 18:41:53 +0000597 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregorbca01b42011-07-06 22:04:06 +0000598 QualType(), E,
599 IsThrownVarInScope);
John McCallac418162010-04-22 01:10:34 +0000600 if (Res.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000601 return ExprError();
602 E = Res.take();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000603
Eli Friedman5ed9b932010-06-03 20:39:03 +0000604 // If the exception has class type, we need additional handling.
605 const RecordType *RecordTy = Ty->getAs<RecordType>();
606 if (!RecordTy)
John Wiegley429bb272011-04-08 18:41:53 +0000607 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000608 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
609
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000610 // If we are throwing a polymorphic class type or pointer thereof,
611 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000612 MarkVTableUsed(ThrowLoc, RD);
613
Eli Friedman98efb9f2010-10-12 20:32:36 +0000614 // If a pointer is thrown, the referenced object will not be destroyed.
615 if (isPointer)
John Wiegley429bb272011-04-08 18:41:53 +0000616 return Owned(E);
Eli Friedman98efb9f2010-10-12 20:32:36 +0000617
Eli Friedman5ed9b932010-06-03 20:39:03 +0000618 // If the class has a non-trivial destructor, we must be able to call it.
619 if (RD->hasTrivialDestructor())
John Wiegley429bb272011-04-08 18:41:53 +0000620 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000621
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000622 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +0000623 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman5ed9b932010-06-03 20:39:03 +0000624 if (!Destructor)
John Wiegley429bb272011-04-08 18:41:53 +0000625 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000626
627 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
628 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000629 PDiag(diag::err_access_dtor_exception) << Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000630 return Owned(E);
Chris Lattner50dd2892008-02-26 00:51:44 +0000631}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000632
Richard Smith7a614d82011-06-11 17:19:42 +0000633QualType Sema::getAndCaptureCurrentThisType() {
John McCall5808ce42011-02-03 08:15:49 +0000634 // Ignore block scopes: we can capture through them.
635 // Ignore nested enum scopes: we'll diagnose non-constant expressions
636 // where they're invalid, and other uses are legitimate.
637 // Don't ignore nested class scopes: you can't use 'this' in a local class.
John McCall469a1eb2011-02-02 13:00:07 +0000638 DeclContext *DC = CurContext;
Richard Smith7a614d82011-06-11 17:19:42 +0000639 unsigned NumBlocks = 0;
John McCall5808ce42011-02-03 08:15:49 +0000640 while (true) {
Richard Smith7a614d82011-06-11 17:19:42 +0000641 if (isa<BlockDecl>(DC)) {
642 DC = cast<BlockDecl>(DC)->getDeclContext();
643 ++NumBlocks;
644 } else if (isa<EnumDecl>(DC))
645 DC = cast<EnumDecl>(DC)->getDeclContext();
John McCall5808ce42011-02-03 08:15:49 +0000646 else break;
647 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000648
Richard Smith7a614d82011-06-11 17:19:42 +0000649 QualType ThisTy;
650 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
651 if (method && method->isInstance())
652 ThisTy = method->getThisType(Context);
653 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
654 // C++0x [expr.prim]p4:
655 // Otherwise, if a member-declarator declares a non-static data member
656 // of a class X, the expression this is a prvalue of type "pointer to X"
657 // within the optional brace-or-equal-initializer.
658 Scope *S = getScopeForContext(DC);
659 if (!S || S->getFlags() & Scope::ThisScope)
660 ThisTy = Context.getPointerType(Context.getRecordType(RD));
661 }
John McCall469a1eb2011-02-02 13:00:07 +0000662
Richard Smith7a614d82011-06-11 17:19:42 +0000663 // Mark that we're closing on 'this' in all the block scopes we ignored.
664 if (!ThisTy.isNull())
665 for (unsigned idx = FunctionScopes.size() - 1;
666 NumBlocks; --idx, --NumBlocks)
667 cast<BlockScopeInfo>(FunctionScopes[idx])->CapturesCXXThis = true;
John McCall469a1eb2011-02-02 13:00:07 +0000668
Richard Smith7a614d82011-06-11 17:19:42 +0000669 return ThisTy;
John McCall5808ce42011-02-03 08:15:49 +0000670}
671
Richard Smith7a614d82011-06-11 17:19:42 +0000672ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCall5808ce42011-02-03 08:15:49 +0000673 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
674 /// is a non-lvalue expression whose value is the address of the object for
675 /// which the function is called.
676
Richard Smith7a614d82011-06-11 17:19:42 +0000677 QualType ThisTy = getAndCaptureCurrentThisType();
678 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCall5808ce42011-02-03 08:15:49 +0000679
Richard Smith7a614d82011-06-11 17:19:42 +0000680 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000681}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000682
John McCall60d7b3a2010-08-24 06:29:42 +0000683ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000684Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000685 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000686 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000687 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000688 if (!TypeRep)
689 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000690
John McCall9d125032010-01-15 18:39:57 +0000691 TypeSourceInfo *TInfo;
692 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
693 if (!TInfo)
694 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000695
696 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
697}
698
699/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
700/// Can be interpreted either as function-style casting ("int(x)")
701/// or class type construction ("ClassType(x,y,z)")
702/// or creation of a value-initialized type ("int()").
703ExprResult
704Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
705 SourceLocation LParenLoc,
706 MultiExprArg exprs,
707 SourceLocation RParenLoc) {
708 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000709 unsigned NumExprs = exprs.size();
710 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000711 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000712 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
713
Sebastian Redlf53597f2009-03-15 17:47:39 +0000714 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000715 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000716 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Douglas Gregorab6677e2010-09-08 00:15:04 +0000718 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000719 LParenLoc,
720 Exprs, NumExprs,
721 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000722 }
723
Anders Carlssonbb60a502009-08-27 03:53:50 +0000724 if (Ty->isArrayType())
725 return ExprError(Diag(TyBeginLoc,
726 diag::err_value_init_for_array_type) << FullRange);
727 if (!Ty->isVoidType() &&
728 RequireCompleteType(TyBeginLoc, Ty,
729 PDiag(diag::err_invalid_incomplete_type_use)
730 << FullRange))
731 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000732
Anders Carlssonbb60a502009-08-27 03:53:50 +0000733 if (RequireNonAbstractType(TyBeginLoc, Ty,
734 diag::err_allocation_of_abstract_type))
735 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000736
737
Douglas Gregor506ae412009-01-16 18:33:17 +0000738 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000739 // If the expression list is a single expression, the type conversion
740 // expression is equivalent (in definedness, and if defined in meaning) to the
741 // corresponding cast expression.
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000742 if (NumExprs == 1) {
John McCallb45ae252011-10-05 07:41:44 +0000743 Expr *Arg = Exprs[0];
Anders Carlsson0aebc812009-09-09 21:33:21 +0000744 exprs.release();
John McCallb45ae252011-10-05 07:41:44 +0000745 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000746 }
747
Douglas Gregor19311e72010-09-08 21:40:08 +0000748 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
749 InitializationKind Kind
750 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
751 LParenLoc, RParenLoc)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000752 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor19311e72010-09-08 21:40:08 +0000753 LParenLoc, RParenLoc);
754 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
755 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000756
Douglas Gregor19311e72010-09-08 21:40:08 +0000757 // FIXME: Improve AST representation?
758 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000759}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000760
John McCall6ec278d2011-01-27 09:37:56 +0000761/// doesUsualArrayDeleteWantSize - Answers whether the usual
762/// operator delete[] for the given type has a size_t parameter.
763static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
764 QualType allocType) {
765 const RecordType *record =
766 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
767 if (!record) return false;
768
769 // Try to find an operator delete[] in class scope.
770
771 DeclarationName deleteName =
772 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
773 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
774 S.LookupQualifiedName(ops, record->getDecl());
775
776 // We're just doing this for information.
777 ops.suppressDiagnostics();
778
779 // Very likely: there's no operator delete[].
780 if (ops.empty()) return false;
781
782 // If it's ambiguous, it should be illegal to call operator delete[]
783 // on this thing, so it doesn't matter if we allocate extra space or not.
784 if (ops.isAmbiguous()) return false;
785
786 LookupResult::Filter filter = ops.makeFilter();
787 while (filter.hasNext()) {
788 NamedDecl *del = filter.next()->getUnderlyingDecl();
789
790 // C++0x [basic.stc.dynamic.deallocation]p2:
791 // A template instance is never a usual deallocation function,
792 // regardless of its signature.
793 if (isa<FunctionTemplateDecl>(del)) {
794 filter.erase();
795 continue;
796 }
797
798 // C++0x [basic.stc.dynamic.deallocation]p2:
799 // If class T does not declare [an operator delete[] with one
800 // parameter] but does declare a member deallocation function
801 // named operator delete[] with exactly two parameters, the
802 // second of which has type std::size_t, then this function
803 // is a usual deallocation function.
804 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
805 filter.erase();
806 continue;
807 }
808 }
809 filter.done();
810
811 if (!ops.isSingleResult()) return false;
812
813 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
814 return (del->getNumParams() == 2);
815}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000816
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000817/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
818/// @code new (memory) int[size][4] @endcode
819/// or
820/// @code ::new Foo(23, "hello") @endcode
821/// For the interpretation of this heap of arguments, consult the base version.
John McCall60d7b3a2010-08-24 06:29:42 +0000822ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000823Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000824 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000825 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000826 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000827 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000828 SourceLocation ConstructorRParen) {
Richard Smith34b41d92011-02-20 03:19:35 +0000829 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
830
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000831 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000832 // If the specified type is an array, unwrap it and save the expression.
833 if (D.getNumTypeObjects() > 0 &&
834 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
835 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith34b41d92011-02-20 03:19:35 +0000836 if (TypeContainsAuto)
837 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
838 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000839 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000840 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
841 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000842 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000843 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
844 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000845
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000846 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000847 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000848 }
849
Douglas Gregor043cad22009-09-11 00:18:58 +0000850 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000851 if (ArraySize) {
852 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000853 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
854 break;
855
856 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
857 if (Expr *NumElts = (Expr *)Array.NumElts) {
858 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
859 !NumElts->isIntegerConstantExpr(Context)) {
860 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
861 << NumElts->getSourceRange();
862 return ExprError();
863 }
864 }
865 }
866 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000867
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +0000868 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
John McCallbf1a0282010-06-04 23:28:52 +0000869 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000870 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000871 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000872
Mike Stump1eb44332009-09-09 15:08:12 +0000873 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000874 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000875 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000876 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000877 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000878 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000879 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000880 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000881 ConstructorLParen,
882 move(ConstructorArgs),
Richard Smith34b41d92011-02-20 03:19:35 +0000883 ConstructorRParen,
884 TypeContainsAuto);
Douglas Gregor3433cf72009-05-21 00:00:09 +0000885}
886
John McCall60d7b3a2010-08-24 06:29:42 +0000887ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000888Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
889 SourceLocation PlacementLParen,
890 MultiExprArg PlacementArgs,
891 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000892 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000893 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000894 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000895 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000896 SourceLocation ConstructorLParen,
897 MultiExprArg ConstructorArgs,
Richard Smith34b41d92011-02-20 03:19:35 +0000898 SourceLocation ConstructorRParen,
899 bool TypeMayContainAuto) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000900 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000901
Richard Smith34b41d92011-02-20 03:19:35 +0000902 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
903 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
904 if (ConstructorArgs.size() == 0)
905 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
906 << AllocType << TypeRange);
907 if (ConstructorArgs.size() != 1) {
908 Expr *FirstBad = ConstructorArgs.get()[1];
909 return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
910 diag::err_auto_new_ctor_multiple_expressions)
911 << AllocType << TypeRange);
912 }
Richard Smitha085da82011-03-17 16:11:59 +0000913 TypeSourceInfo *DeducedType = 0;
914 if (!DeduceAutoType(AllocTypeInfo, ConstructorArgs.get()[0], DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +0000915 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
916 << AllocType
917 << ConstructorArgs.get()[0]->getType()
918 << TypeRange
919 << ConstructorArgs.get()[0]->getSourceRange());
Richard Smitha085da82011-03-17 16:11:59 +0000920 if (!DeducedType)
921 return ExprError();
Richard Smith34b41d92011-02-20 03:19:35 +0000922
Richard Smitha085da82011-03-17 16:11:59 +0000923 AllocTypeInfo = DeducedType;
924 AllocType = AllocTypeInfo->getType();
Richard Smith34b41d92011-02-20 03:19:35 +0000925 }
926
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000927 // Per C++0x [expr.new]p5, the type being constructed may be a
928 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +0000929 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000930 if (const ConstantArrayType *Array
931 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000932 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
933 Context.getSizeType(),
934 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000935 AllocType = Array->getElementType();
936 }
937 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000938
Douglas Gregora0750762010-10-06 16:00:31 +0000939 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
940 return ExprError();
941
John McCallf85e1932011-06-15 23:02:42 +0000942 // In ARC, infer 'retaining' for the allocated
943 if (getLangOptions().ObjCAutoRefCount &&
944 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
945 AllocType->isObjCLifetimeType()) {
946 AllocType = Context.getLifetimeQualifiedType(AllocType,
947 AllocType->getObjCARCImplicitLifetime());
948 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000949
John McCallf85e1932011-06-15 23:02:42 +0000950 QualType ResultType = Context.getPointerType(AllocType);
951
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000952 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
953 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000954 if (ArraySize && !ArraySize->isTypeDependent()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000955
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000956 QualType SizeType = ArraySize->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000957
John McCall60d7b3a2010-08-24 06:29:42 +0000958 ExprResult ConvertedSize
John McCall9ae2f072010-08-23 23:25:46 +0000959 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000960 PDiag(diag::err_array_size_not_integral),
961 PDiag(diag::err_array_size_incomplete_type)
962 << ArraySize->getSourceRange(),
963 PDiag(diag::err_array_size_explicit_conversion),
964 PDiag(diag::note_array_size_conversion),
965 PDiag(diag::err_array_size_ambiguous_conversion),
966 PDiag(diag::note_array_size_conversion),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000967 PDiag(getLangOptions().CPlusPlus0x? 0
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000968 : diag::ext_array_size_conversion));
969 if (ConvertedSize.isInvalid())
970 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000971
John McCall9ae2f072010-08-23 23:25:46 +0000972 ArraySize = ConvertedSize.take();
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000973 SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000974 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000975 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000976
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000977 // Let's see if this is a constant < 0. If so, we reject it out of hand.
978 // We don't care about special rules, so we tell the machinery it's not
979 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000980 if (!ArraySize->isValueDependent()) {
981 llvm::APSInt Value;
982 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
983 if (Value < llvm::APSInt(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000984 llvm::APInt::getNullValue(Value.getBitWidth()),
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000985 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000986 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000987 diag::err_typecheck_negative_array_size)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000988 << ArraySize->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000989
Douglas Gregor2767ce22010-08-18 00:39:00 +0000990 if (!AllocType->isDependentType()) {
991 unsigned ActiveSizeBits
992 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
993 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000994 Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000995 diag::err_array_too_large)
996 << Value.toString(10)
997 << ArraySize->getSourceRange();
998 return ExprError();
999 }
1000 }
Douglas Gregor4bd40312010-07-13 15:54:32 +00001001 } else if (TypeIdParens.isValid()) {
1002 // Can't have dynamic array size when the type-id is in parentheses.
1003 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1004 << ArraySize->getSourceRange()
1005 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1006 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001007
Douglas Gregor4bd40312010-07-13 15:54:32 +00001008 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +00001009 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001010 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001011
John McCallf85e1932011-06-15 23:02:42 +00001012 // ARC: warn about ABI issues.
1013 if (getLangOptions().ObjCAutoRefCount) {
1014 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1015 if (BaseAllocType.hasStrongOrWeakObjCLifetime())
1016 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1017 << 0 << BaseAllocType;
1018 }
1019
John McCall7d166272011-05-15 07:14:44 +00001020 // Note that we do *not* convert the argument in any way. It can
1021 // be signed, larger than size_t, whatever.
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001022 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001023
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001024 FunctionDecl *OperatorNew = 0;
1025 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001026 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
1027 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001028
Sebastian Redl28507842009-02-26 14:39:58 +00001029 if (!AllocType->isDependentType() &&
1030 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
1031 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +00001032 SourceRange(PlacementLParen, PlacementRParen),
1033 UseGlobal, AllocType, ArraySize, PlaceArgs,
1034 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +00001035 return ExprError();
John McCall6ec278d2011-01-27 09:37:56 +00001036
1037 // If this is an array allocation, compute whether the usual array
1038 // deallocation function for the type has a size_t parameter.
1039 bool UsualArrayDeleteWantsSize = false;
1040 if (ArraySize && !AllocType->isDependentType())
1041 UsualArrayDeleteWantsSize
1042 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1043
Chris Lattner5f9e2722011-07-23 10:55:15 +00001044 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001045 if (OperatorNew) {
1046 // Add default arguments, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001047 const FunctionProtoType *Proto =
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001048 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001049 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00001050 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001051
Anders Carlsson28e94832010-05-03 02:07:56 +00001052 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001053 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlsson28e94832010-05-03 02:07:56 +00001054 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001055 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001056
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001057 NumPlaceArgs = AllPlaceArgs.size();
1058 if (NumPlaceArgs > 0)
1059 PlaceArgs = &AllPlaceArgs[0];
1060 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001061
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001062 bool Init = ConstructorLParen.isValid();
1063 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001064 CXXConstructorDecl *Constructor = 0;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001065 bool HadMultipleCandidates = false;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001066 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
1067 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +00001068 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +00001069
Anders Carlsson48c95012010-05-03 15:45:23 +00001070 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +00001071 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +00001072 SourceRange InitRange(ConsArgs[0]->getLocStart(),
1073 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001074
Anders Carlsson48c95012010-05-03 15:45:23 +00001075 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1076 return ExprError();
1077 }
1078
Douglas Gregor99a2e602009-12-16 01:38:02 +00001079 if (!AllocType->isDependentType() &&
1080 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
1081 // C++0x [expr.new]p15:
1082 // A new-expression that creates an object of type T initializes that
1083 // object as follows:
1084 InitializationKind Kind
1085 // - If the new-initializer is omitted, the object is default-
1086 // initialized (8.5); if no initialization is performed,
1087 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001088 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001089 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor99a2e602009-12-16 01:38:02 +00001090 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001091 : InitializationKind::CreateDirect(TypeRange.getBegin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001092 ConstructorLParen,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001093 ConstructorRParen);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001094
Douglas Gregor99a2e602009-12-16 01:38:02 +00001095 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00001096 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001097 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001098 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001099 move(ConstructorArgs));
1100 if (FullInit.isInvalid())
1101 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001102
1103 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor99a2e602009-12-16 01:38:02 +00001104 // constructor call, which CXXNewExpr handles directly.
1105 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1106 if (CXXBindTemporaryExpr *Binder
1107 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1108 FullInitExpr = Binder->getSubExpr();
1109 if (CXXConstructExpr *Construct
1110 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1111 Constructor = Construct->getConstructor();
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001112 HadMultipleCandidates = Construct->hadMultipleCandidates();
Douglas Gregor99a2e602009-12-16 01:38:02 +00001113 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1114 AEnd = Construct->arg_end();
1115 A != AEnd; ++A)
John McCall3fa5cae2010-10-26 07:05:15 +00001116 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001117 } else {
1118 // Take the converted initializer.
1119 ConvertedConstructorArgs.push_back(FullInit.release());
1120 }
1121 } else {
1122 // No initialization required.
1123 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001124
Douglas Gregor99a2e602009-12-16 01:38:02 +00001125 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001126 NumConsArgs = ConvertedConstructorArgs.size();
1127 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001128 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001129
Douglas Gregor6d908702010-02-26 05:06:18 +00001130 // Mark the new and delete operators as referenced.
1131 if (OperatorNew)
1132 MarkDeclarationReferenced(StartLoc, OperatorNew);
1133 if (OperatorDelete)
1134 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1135
John McCall84ff0fc2011-07-13 20:12:57 +00001136 // C++0x [expr.new]p17:
1137 // If the new expression creates an array of objects of class type,
1138 // access and ambiguity control are done for the destructor.
1139 if (ArraySize && Constructor) {
1140 if (CXXDestructorDecl *dtor = LookupDestructor(Constructor->getParent())) {
1141 MarkDeclarationReferenced(StartLoc, dtor);
1142 CheckDestructorAccess(StartLoc, dtor,
1143 PDiag(diag::err_access_dtor)
1144 << Context.getBaseElementType(AllocType));
1145 }
1146 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001147
Sebastian Redlf53597f2009-03-15 17:47:39 +00001148 PlacementArgs.release();
1149 ConstructorArgs.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001150
Ted Kremenekad7fe862010-02-11 22:51:03 +00001151 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001152 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001153 ArraySize, Constructor, Init,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001154 ConsArgs, NumConsArgs,
1155 HadMultipleCandidates,
1156 OperatorDelete,
John McCall6ec278d2011-01-27 09:37:56 +00001157 UsualArrayDeleteWantsSize,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001158 ResultType, AllocTypeInfo,
1159 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001160 Init ? ConstructorRParen :
Chandler Carruth428edaf2010-10-25 08:47:36 +00001161 TypeRange.getEnd(),
1162 ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001163}
1164
1165/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1166/// in a new-expression.
1167/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +00001168bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00001169 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001170 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1171 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +00001172 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001173 return Diag(Loc, diag::err_bad_new_type)
1174 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001175 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001176 return Diag(Loc, diag::err_bad_new_type)
1177 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001178 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +00001179 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001180 PDiag(diag::err_new_incomplete_type)
1181 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001182 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +00001183 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +00001184 diag::err_allocation_of_abstract_type))
1185 return true;
Douglas Gregora0750762010-10-06 16:00:31 +00001186 else if (AllocType->isVariablyModifiedType())
1187 return Diag(Loc, diag::err_variably_modified_new_type)
1188 << AllocType;
Douglas Gregor5666d362011-04-15 19:46:20 +00001189 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1190 return Diag(Loc, diag::err_address_space_qualified_new)
1191 << AllocType.getUnqualifiedType() << AddressSpace;
John McCallf85e1932011-06-15 23:02:42 +00001192 else if (getLangOptions().ObjCAutoRefCount) {
1193 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1194 QualType BaseAllocType = Context.getBaseElementType(AT);
1195 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1196 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001197 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001198 << BaseAllocType;
1199 }
1200 }
Douglas Gregor5666d362011-04-15 19:46:20 +00001201
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001202 return false;
1203}
1204
Douglas Gregor6d908702010-02-26 05:06:18 +00001205/// \brief Determine whether the given function is a non-placement
1206/// deallocation function.
1207static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1208 if (FD->isInvalidDecl())
1209 return false;
1210
1211 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1212 return Method->isUsualDeallocationFunction();
1213
1214 return ((FD->getOverloadedOperator() == OO_Delete ||
1215 FD->getOverloadedOperator() == OO_Array_Delete) &&
1216 FD->getNumParams() == 1);
1217}
1218
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001219/// FindAllocationFunctions - Finds the overloads of operator new and delete
1220/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001221bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1222 bool UseGlobal, QualType AllocType,
1223 bool IsArray, Expr **PlaceArgs,
1224 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001225 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +00001226 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001227 // --- Choosing an allocation function ---
1228 // C++ 5.3.4p8 - 14 & 18
1229 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1230 // in the scope of the allocated class.
1231 // 2) If an array size is given, look for operator new[], else look for
1232 // operator new.
1233 // 3) The first argument is always size_t. Append the arguments from the
1234 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001235
Chris Lattner5f9e2722011-07-23 10:55:15 +00001236 SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001237 // We don't care about the actual value of this argument.
1238 // FIXME: Should the Sema create the expression and embed it in the syntax
1239 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001240 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001241 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssond67c4c32009-08-16 20:29:29 +00001242 Context.getSizeType(),
1243 SourceLocation());
1244 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001245 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1246
Douglas Gregor6d908702010-02-26 05:06:18 +00001247 // C++ [expr.new]p8:
1248 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001249 // function's name is operator new and the deallocation function's
Douglas Gregor6d908702010-02-26 05:06:18 +00001250 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001251 // type, the allocation function's name is operator new[] and the
1252 // deallocation function's name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001253 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1254 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001255 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1256 IsArray ? OO_Array_Delete : OO_Delete);
1257
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001258 QualType AllocElemType = Context.getBaseElementType(AllocType);
1259
1260 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001261 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001262 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001263 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001264 AllocArgs.size(), Record, /*AllowMissing=*/true,
1265 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001266 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001267 }
1268 if (!OperatorNew) {
1269 // Didn't find a member overload. Look for a global one.
1270 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001271 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001272 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001273 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1274 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001275 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001276 }
1277
John McCall9c82afc2010-04-20 02:18:25 +00001278 // We don't need an operator delete if we're running under
1279 // -fno-exceptions.
1280 if (!getLangOptions().Exceptions) {
1281 OperatorDelete = 0;
1282 return false;
1283 }
1284
Anders Carlssond9583892009-05-31 20:26:12 +00001285 // FindAllocationOverload can change the passed in arguments, so we need to
1286 // copy them back.
1287 if (NumPlaceArgs > 0)
1288 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001289
Douglas Gregor6d908702010-02-26 05:06:18 +00001290 // C++ [expr.new]p19:
1291 //
1292 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001293 // deallocation function's name is looked up in the global
Douglas Gregor6d908702010-02-26 05:06:18 +00001294 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001295 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6d908702010-02-26 05:06:18 +00001296 // the scope of T. If this lookup fails to find the name, or if
1297 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001298 // deallocation function's name is looked up in the global scope.
Douglas Gregor6d908702010-02-26 05:06:18 +00001299 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001300 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001301 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001302 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001303 LookupQualifiedName(FoundDelete, RD);
1304 }
John McCall90c8c572010-03-18 08:19:33 +00001305 if (FoundDelete.isAmbiguous())
1306 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001307
1308 if (FoundDelete.empty()) {
1309 DeclareGlobalNewDelete();
1310 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1311 }
1312
1313 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001314
Chris Lattner5f9e2722011-07-23 10:55:15 +00001315 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCall9aa472c2010-03-19 07:35:19 +00001316
John McCalledeb6c92010-09-14 21:34:24 +00001317 // Whether we're looking for a placement operator delete is dictated
1318 // by whether we selected a placement operator new, not by whether
1319 // we had explicit placement arguments. This matters for things like
1320 // struct A { void *operator new(size_t, int = 0); ... };
1321 // A *a = new A()
1322 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1323
1324 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001325 // C++ [expr.new]p20:
1326 // A declaration of a placement deallocation function matches the
1327 // declaration of a placement allocation function if it has the
1328 // same number of parameters and, after parameter transformations
1329 // (8.3.5), all parameter types except the first are
1330 // identical. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001331 //
Douglas Gregor6d908702010-02-26 05:06:18 +00001332 // To perform this comparison, we compute the function type that
1333 // the deallocation function should have, and use that type both
1334 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001335 //
1336 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001337 QualType ExpectedFunctionType;
1338 {
1339 const FunctionProtoType *Proto
1340 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001341
Chris Lattner5f9e2722011-07-23 10:55:15 +00001342 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001343 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6d908702010-02-26 05:06:18 +00001344 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1345 ArgTypes.push_back(Proto->getArgType(I));
1346
John McCalle23cf432010-12-14 08:05:40 +00001347 FunctionProtoType::ExtProtoInfo EPI;
1348 EPI.Variadic = Proto->isVariadic();
1349
Douglas Gregor6d908702010-02-26 05:06:18 +00001350 ExpectedFunctionType
1351 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalle23cf432010-12-14 08:05:40 +00001352 ArgTypes.size(), EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001353 }
1354
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001355 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001356 DEnd = FoundDelete.end();
1357 D != DEnd; ++D) {
1358 FunctionDecl *Fn = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001359 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6d908702010-02-26 05:06:18 +00001360 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1361 // Perform template argument deduction to try to match the
1362 // expected function type.
1363 TemplateDeductionInfo Info(Context, StartLoc);
1364 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1365 continue;
1366 } else
1367 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1368
1369 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001370 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001371 }
1372 } else {
1373 // C++ [expr.new]p20:
1374 // [...] Any non-placement deallocation function matches a
1375 // non-placement allocation function. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001376 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001377 DEnd = FoundDelete.end();
1378 D != DEnd; ++D) {
1379 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1380 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001381 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001382 }
1383 }
1384
1385 // C++ [expr.new]p20:
1386 // [...] If the lookup finds a single matching deallocation
1387 // function, that function will be called; otherwise, no
1388 // deallocation function will be called.
1389 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001390 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001391
1392 // C++0x [expr.new]p20:
1393 // If the lookup finds the two-parameter form of a usual
1394 // deallocation function (3.7.4.2) and that function, considered
1395 // as a placement deallocation function, would have been
1396 // selected as a match for the allocation function, the program
1397 // is ill-formed.
1398 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1399 isNonPlacementDeallocationFunction(OperatorDelete)) {
1400 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001401 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001402 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1403 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1404 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001405 } else {
1406 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001407 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001408 }
1409 }
1410
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001411 return false;
1412}
1413
Sebastian Redl7f662392008-12-04 22:20:51 +00001414/// FindAllocationOverload - Find an fitting overload for the allocation
1415/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001416bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1417 DeclarationName Name, Expr** Args,
1418 unsigned NumArgs, DeclContext *Ctx,
Sean Hunt2be7e902011-05-12 22:46:29 +00001419 bool AllowMissing, FunctionDecl *&Operator,
1420 bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001421 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1422 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001423 if (R.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001424 if (AllowMissing || !Diagnose)
Sebastian Redl7f662392008-12-04 22:20:51 +00001425 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001426 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001427 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001428 }
1429
John McCall90c8c572010-03-18 08:19:33 +00001430 if (R.isAmbiguous())
1431 return true;
1432
1433 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001434
John McCall5769d612010-02-08 23:07:23 +00001435 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001436 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001437 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001438 // Even member operator new/delete are implicitly treated as
1439 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001440 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001441
John McCall9aa472c2010-03-19 07:35:19 +00001442 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1443 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001444 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1445 Candidates,
1446 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001447 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001448 }
1449
John McCall9aa472c2010-03-19 07:35:19 +00001450 FunctionDecl *Fn = cast<FunctionDecl>(D);
1451 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001452 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001453 }
1454
1455 // Do the resolution.
1456 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001457 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001458 case OR_Success: {
1459 // Got one!
1460 FunctionDecl *FnDecl = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00001461 MarkDeclarationReferenced(StartLoc, FnDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001462 // The first argument is size_t, and the first parameter must be size_t,
1463 // too. This is checked on declaration and can be assumed. (It can't be
1464 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001465 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001466 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1467 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001468 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1469 FnDecl->getParamDecl(i));
1470
1471 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1472 return true;
1473
John McCall60d7b3a2010-08-24 06:29:42 +00001474 ExprResult Result
Sean Hunt2be7e902011-05-12 22:46:29 +00001475 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001476 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001477 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001478
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001479 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001480 }
1481 Operator = FnDecl;
Sean Hunt2be7e902011-05-12 22:46:29 +00001482 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl,
1483 Diagnose);
Sebastian Redl7f662392008-12-04 22:20:51 +00001484 return false;
1485 }
1486
1487 case OR_No_Viable_Function:
Chandler Carruth361d3802011-06-08 10:26:03 +00001488 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001489 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1490 << Name << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001491 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1492 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001493 return true;
1494
1495 case OR_Ambiguous:
Chandler Carruth361d3802011-06-08 10:26:03 +00001496 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001497 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1498 << Name << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001499 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
1500 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001501 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001502
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001503 case OR_Deleted: {
Chandler Carruth361d3802011-06-08 10:26:03 +00001504 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001505 Diag(StartLoc, diag::err_ovl_deleted_call)
1506 << Best->Function->isDeleted()
1507 << Name
1508 << getDeletedOrUnavailableSuffix(Best->Function)
1509 << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001510 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1511 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001512 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001513 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001514 }
David Blaikieb219cfc2011-09-23 05:06:16 +00001515 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Sebastian Redl7f662392008-12-04 22:20:51 +00001516}
1517
1518
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001519/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1520/// delete. These are:
1521/// @code
Sebastian Redl8999fe12011-03-14 18:08:30 +00001522/// // C++03:
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001523/// void* operator new(std::size_t) throw(std::bad_alloc);
1524/// void* operator new[](std::size_t) throw(std::bad_alloc);
1525/// void operator delete(void *) throw();
1526/// void operator delete[](void *) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001527/// // C++0x:
1528/// void* operator new(std::size_t);
1529/// void* operator new[](std::size_t);
1530/// void operator delete(void *);
1531/// void operator delete[](void *);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001532/// @endcode
Sebastian Redl8999fe12011-03-14 18:08:30 +00001533/// C++0x operator delete is implicitly noexcept.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001534/// Note that the placement and nothrow forms of new are *not* implicitly
1535/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001536void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001537 if (GlobalNewDeleteDeclared)
1538 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001539
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001540 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001541 // [...] The following allocation and deallocation functions (18.4) are
1542 // implicitly declared in global scope in each translation unit of a
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001543 // program
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001544 //
Sebastian Redl8999fe12011-03-14 18:08:30 +00001545 // C++03:
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001546 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001547 // void* operator new[](std::size_t) throw(std::bad_alloc);
1548 // void operator delete(void*) throw();
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001549 // void operator delete[](void*) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001550 // C++0x:
1551 // void* operator new(std::size_t);
1552 // void* operator new[](std::size_t);
1553 // void operator delete(void*);
1554 // void operator delete[](void*);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001555 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001556 // These implicit declarations introduce only the function names operator
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001557 // new, operator new[], operator delete, operator delete[].
1558 //
1559 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1560 // "std" or "bad_alloc" as necessary to form the exception specification.
1561 // However, we do not make these implicit declarations visible to name
1562 // lookup.
Sebastian Redl8999fe12011-03-14 18:08:30 +00001563 // Note that the C++0x versions of operator delete are deallocation functions,
1564 // and thus are implicitly noexcept.
1565 if (!StdBadAlloc && !getLangOptions().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001566 // The "std::bad_alloc" class has not yet been declared, so build it
1567 // implicitly.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001568 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1569 getOrCreateStdNamespace(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001570 SourceLocation(), SourceLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001571 &PP.getIdentifierTable().get("bad_alloc"),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001572 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001573 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001574 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001575
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001576 GlobalNewDeleteDeclared = true;
1577
1578 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1579 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001580 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001581
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001582 DeclareGlobalAllocationFunction(
1583 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001584 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001585 DeclareGlobalAllocationFunction(
1586 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001587 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001588 DeclareGlobalAllocationFunction(
1589 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1590 Context.VoidTy, VoidPtr);
1591 DeclareGlobalAllocationFunction(
1592 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1593 Context.VoidTy, VoidPtr);
1594}
1595
1596/// DeclareGlobalAllocationFunction - Declares a single implicit global
1597/// allocation function if it doesn't already exist.
1598void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001599 QualType Return, QualType Argument,
1600 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001601 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1602
1603 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001604 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001605 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001606 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001607 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001608 // Only look at non-template functions, as it is the predefined,
1609 // non-templated allocation function we are trying to declare here.
1610 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1611 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001612 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001613 Func->getParamDecl(0)->getType().getUnqualifiedType());
1614 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001615 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1616 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001617 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001618 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001619 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001620 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001621 }
1622 }
1623
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001624 QualType BadAllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001625 bool HasBadAllocExceptionSpec
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001626 = (Name.getCXXOverloadedOperator() == OO_New ||
1627 Name.getCXXOverloadedOperator() == OO_Array_New);
Sebastian Redl8999fe12011-03-14 18:08:30 +00001628 if (HasBadAllocExceptionSpec && !getLangOptions().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001629 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001630 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001631 }
John McCalle23cf432010-12-14 08:05:40 +00001632
1633 FunctionProtoType::ExtProtoInfo EPI;
John McCalle23cf432010-12-14 08:05:40 +00001634 if (HasBadAllocExceptionSpec) {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001635 if (!getLangOptions().CPlusPlus0x) {
1636 EPI.ExceptionSpecType = EST_Dynamic;
1637 EPI.NumExceptions = 1;
1638 EPI.Exceptions = &BadAllocType;
1639 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00001640 } else {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001641 EPI.ExceptionSpecType = getLangOptions().CPlusPlus0x ?
1642 EST_BasicNoexcept : EST_DynamicNone;
John McCalle23cf432010-12-14 08:05:40 +00001643 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001644
John McCalle23cf432010-12-14 08:05:40 +00001645 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001646 FunctionDecl *Alloc =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001647 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1648 SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001649 FnType, /*TInfo=*/0, SC_None,
1650 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001651 Alloc->setImplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001652
Nuno Lopesfc284482009-12-16 16:59:22 +00001653 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001654 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001655
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001656 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001657 SourceLocation(), 0,
1658 Argument, /*TInfo=*/0,
1659 SC_None, SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00001660 Alloc->setParams(Param);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001661
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001662 // FIXME: Also add this declaration to the IdentifierResolver, but
1663 // make sure it is at the end of the chain to coincide with the
1664 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001665 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001666}
1667
Anders Carlsson78f74552009-11-15 18:45:20 +00001668bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1669 DeclarationName Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001670 FunctionDecl* &Operator, bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001671 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001672 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001673 LookupQualifiedName(Found, RD);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001674
John McCalla24dc2e2009-11-17 02:14:36 +00001675 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001676 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001677
Chandler Carruth23893242010-06-28 00:30:51 +00001678 Found.suppressDiagnostics();
1679
Chris Lattner5f9e2722011-07-23 10:55:15 +00001680 SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001681 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1682 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001683 NamedDecl *ND = (*F)->getUnderlyingDecl();
1684
1685 // Ignore template operator delete members from the check for a usual
1686 // deallocation function.
1687 if (isa<FunctionTemplateDecl>(ND))
1688 continue;
1689
1690 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001691 Matches.push_back(F.getPair());
1692 }
1693
1694 // There's exactly one suitable operator; pick it.
1695 if (Matches.size() == 1) {
1696 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
Sean Hunt2be7e902011-05-12 22:46:29 +00001697
1698 if (Operator->isDeleted()) {
1699 if (Diagnose) {
1700 Diag(StartLoc, diag::err_deleted_function_use);
1701 Diag(Operator->getLocation(), diag::note_unavailable_here) << true;
1702 }
1703 return true;
1704 }
1705
John McCall046a7462010-08-04 00:31:26 +00001706 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Sean Hunt2be7e902011-05-12 22:46:29 +00001707 Matches[0], Diagnose);
John McCall046a7462010-08-04 00:31:26 +00001708 return false;
1709
1710 // We found multiple suitable operators; complain about the ambiguity.
1711 } else if (!Matches.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001712 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001713 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1714 << Name << RD;
John McCall046a7462010-08-04 00:31:26 +00001715
Chris Lattner5f9e2722011-07-23 10:55:15 +00001716 for (SmallVectorImpl<DeclAccessPair>::iterator
Sean Huntcb45a0f2011-05-12 22:46:25 +00001717 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1718 Diag((*F)->getUnderlyingDecl()->getLocation(),
1719 diag::note_member_declared_here) << Name;
1720 }
John McCall046a7462010-08-04 00:31:26 +00001721 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001722 }
1723
1724 // We did find operator delete/operator delete[] declarations, but
1725 // none of them were suitable.
1726 if (!Found.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001727 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001728 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1729 << Name << RD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001730
Sean Huntcb45a0f2011-05-12 22:46:25 +00001731 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1732 F != FEnd; ++F)
1733 Diag((*F)->getUnderlyingDecl()->getLocation(),
1734 diag::note_member_declared_here) << Name;
1735 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001736 return true;
1737 }
1738
1739 // Look for a global declaration.
1740 DeclareGlobalNewDelete();
1741 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001742
Anders Carlsson78f74552009-11-15 18:45:20 +00001743 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1744 Expr* DeallocArgs[1];
1745 DeallocArgs[0] = &Null;
1746 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001747 DeallocArgs, 1, TUDecl, !Diagnose,
1748 Operator, Diagnose))
Anders Carlsson78f74552009-11-15 18:45:20 +00001749 return true;
1750
1751 assert(Operator && "Did not find a deallocation function!");
1752 return false;
1753}
1754
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001755/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1756/// @code ::delete ptr; @endcode
1757/// or
1758/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001759ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001760Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley429bb272011-04-08 18:41:53 +00001761 bool ArrayForm, Expr *ExE) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001762 // C++ [expr.delete]p1:
1763 // The operand shall have a pointer type, or a class type having a single
1764 // conversion function to a pointer type. The result has type void.
1765 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001766 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1767
John Wiegley429bb272011-04-08 18:41:53 +00001768 ExprResult Ex = Owned(ExE);
Anders Carlssond67c4c32009-08-16 20:29:29 +00001769 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001770 bool ArrayFormAsWritten = ArrayForm;
John McCall6ec278d2011-01-27 09:37:56 +00001771 bool UsualArrayDeleteWantsSize = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001772
John Wiegley429bb272011-04-08 18:41:53 +00001773 if (!Ex.get()->isTypeDependent()) {
1774 QualType Type = Ex.get()->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001775
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001776 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001777 if (RequireCompleteType(StartLoc, Type,
Douglas Gregor254a9422010-07-29 14:44:35 +00001778 PDiag(diag::err_delete_incomplete_class_type)))
1779 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001780
Chris Lattner5f9e2722011-07-23 10:55:15 +00001781 SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
John McCall32daa422010-03-31 01:36:47 +00001782
Fariborz Jahanian53462782009-09-11 21:44:33 +00001783 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001784 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001785 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001786 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001787 NamedDecl *D = I.getDecl();
1788 if (isa<UsingShadowDecl>(D))
1789 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1790
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001791 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001792 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001793 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001794
John McCall32daa422010-03-31 01:36:47 +00001795 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001796
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001797 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1798 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001799 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001800 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001801 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001802 if (ObjectPtrConversions.size() == 1) {
1803 // We have a single conversion to a pointer-to-object type. Perform
1804 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001805 // TODO: don't redo the conversion calculation.
John Wiegley429bb272011-04-08 18:41:53 +00001806 ExprResult Res =
1807 PerformImplicitConversion(Ex.get(),
John McCall32daa422010-03-31 01:36:47 +00001808 ObjectPtrConversions.front()->getConversionType(),
John Wiegley429bb272011-04-08 18:41:53 +00001809 AA_Converting);
1810 if (Res.isUsable()) {
1811 Ex = move(Res);
1812 Type = Ex.get()->getType();
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001813 }
1814 }
1815 else if (ObjectPtrConversions.size() > 1) {
1816 Diag(StartLoc, diag::err_ambiguous_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001817 << Type << Ex.get()->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001818 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1819 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001820 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001821 }
Sebastian Redl28507842009-02-26 14:39:58 +00001822 }
1823
Sebastian Redlf53597f2009-03-15 17:47:39 +00001824 if (!Type->isPointerType())
1825 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001826 << Type << Ex.get()->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001827
Ted Kremenek6217b802009-07-29 21:53:49 +00001828 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmane52c9142011-07-26 22:25:31 +00001829 QualType PointeeElem = Context.getBaseElementType(Pointee);
1830
1831 if (unsigned AddressSpace = Pointee.getAddressSpace())
1832 return Diag(Ex.get()->getLocStart(),
1833 diag::err_address_space_qualified_delete)
1834 << Pointee.getUnqualifiedType() << AddressSpace;
1835
1836 CXXRecordDecl *PointeeRD = 0;
Douglas Gregor94a61572010-05-24 17:01:56 +00001837 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001838 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregor94a61572010-05-24 17:01:56 +00001839 // effectively bans deletion of "void*". However, most compilers support
1840 // this, so we treat it as a warning unless we're in a SFINAE context.
1841 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001842 << Type << Ex.get()->getSourceRange();
Eli Friedmane52c9142011-07-26 22:25:31 +00001843 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00001844 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001845 << Type << Ex.get()->getSourceRange());
Eli Friedmane52c9142011-07-26 22:25:31 +00001846 } else if (!Pointee->isDependentType()) {
1847 if (!RequireCompleteType(StartLoc, Pointee,
1848 PDiag(diag::warn_delete_incomplete)
1849 << Ex.get()->getSourceRange())) {
1850 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
1851 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
1852 }
1853 }
1854
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001855 // C++ [expr.delete]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001856 // [Note: a pointer to a const type can be the operand of a
1857 // delete-expression; it is not necessary to cast away the constness
1858 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001859 // of the delete-expression. ]
John McCallf85e1932011-06-15 23:02:42 +00001860 if (!Context.hasSameType(Ex.get()->getType(), Context.VoidPtrTy))
1861 Ex = Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy, CK_NoOp,
1862 Ex.take(), 0, VK_RValue));
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001863
1864 if (Pointee->isArrayType() && !ArrayForm) {
1865 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley429bb272011-04-08 18:41:53 +00001866 << Type << Ex.get()->getSourceRange()
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001867 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1868 ArrayForm = true;
1869 }
1870
Anders Carlssond67c4c32009-08-16 20:29:29 +00001871 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1872 ArrayForm ? OO_Array_Delete : OO_Delete);
1873
Eli Friedmane52c9142011-07-26 22:25:31 +00001874 if (PointeeRD) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001875 if (!UseGlobal &&
Eli Friedmane52c9142011-07-26 22:25:31 +00001876 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
1877 OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001878 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001879
John McCall6ec278d2011-01-27 09:37:56 +00001880 // If we're allocating an array of records, check whether the
1881 // usual operator delete[] has a size_t parameter.
1882 if (ArrayForm) {
1883 // If the user specifically asked to use the global allocator,
1884 // we'll need to do the lookup into the class.
1885 if (UseGlobal)
1886 UsualArrayDeleteWantsSize =
1887 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1888
1889 // Otherwise, the usual operator delete[] should be the
1890 // function we just found.
1891 else if (isa<CXXMethodDecl>(OperatorDelete))
1892 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1893 }
1894
Eli Friedmane52c9142011-07-26 22:25:31 +00001895 if (!PointeeRD->hasTrivialDestructor())
1896 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001897 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001898 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00001899 DiagnoseUseOfDecl(Dtor, StartLoc);
1900 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00001901
1902 // C++ [expr.delete]p3:
1903 // In the first alternative (delete object), if the static type of the
1904 // object to be deleted is different from its dynamic type, the static
1905 // type shall be a base class of the dynamic type of the object to be
1906 // deleted and the static type shall have a virtual destructor or the
1907 // behavior is undefined.
1908 //
1909 // Note: a final class cannot be derived from, no issue there
Eli Friedmanef8c79c2011-07-26 23:27:24 +00001910 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
Eli Friedmane52c9142011-07-26 22:25:31 +00001911 CXXDestructorDecl *dtor = PointeeRD->getDestructor();
Eli Friedmanef8c79c2011-07-26 23:27:24 +00001912 if (dtor && !dtor->isVirtual()) {
1913 if (PointeeRD->isAbstract()) {
1914 // If the class is abstract, we warn by default, because we're
1915 // sure the code has undefined behavior.
1916 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
1917 << PointeeElem;
1918 } else if (!ArrayForm) {
1919 // Otherwise, if this is not an array delete, it's a bit suspect,
1920 // but not necessarily wrong.
1921 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
1922 }
1923 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00001924 }
John McCallf85e1932011-06-15 23:02:42 +00001925
1926 } else if (getLangOptions().ObjCAutoRefCount &&
1927 PointeeElem->isObjCLifetimeType() &&
1928 (PointeeElem.getObjCLifetime() == Qualifiers::OCL_Strong ||
1929 PointeeElem.getObjCLifetime() == Qualifiers::OCL_Weak) &&
1930 ArrayForm) {
1931 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1932 << 1 << PointeeElem;
Anders Carlssond67c4c32009-08-16 20:29:29 +00001933 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001934
Anders Carlssond67c4c32009-08-16 20:29:29 +00001935 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001936 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001937 DeclareGlobalNewDelete();
1938 DeclContext *TUDecl = Context.getTranslationUnitDecl();
John Wiegley429bb272011-04-08 18:41:53 +00001939 Expr *Arg = Ex.get();
Mike Stump1eb44332009-09-09 15:08:12 +00001940 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
John Wiegley429bb272011-04-08 18:41:53 +00001941 &Arg, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001942 OperatorDelete))
1943 return ExprError();
1944 }
Mike Stump1eb44332009-09-09 15:08:12 +00001945
John McCall9c82afc2010-04-20 02:18:25 +00001946 MarkDeclarationReferenced(StartLoc, OperatorDelete);
John McCall6ec278d2011-01-27 09:37:56 +00001947
Douglas Gregord880f522011-02-01 15:50:11 +00001948 // Check access and ambiguity of operator delete and destructor.
Eli Friedmane52c9142011-07-26 22:25:31 +00001949 if (PointeeRD) {
1950 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
John Wiegley429bb272011-04-08 18:41:53 +00001951 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregord880f522011-02-01 15:50:11 +00001952 PDiag(diag::err_access_dtor) << PointeeElem);
1953 }
1954 }
1955
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001956 }
1957
Sebastian Redlf53597f2009-03-15 17:47:39 +00001958 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall6ec278d2011-01-27 09:37:56 +00001959 ArrayFormAsWritten,
1960 UsualArrayDeleteWantsSize,
John Wiegley429bb272011-04-08 18:41:53 +00001961 OperatorDelete, Ex.take(), StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001962}
1963
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001964/// \brief Check the use of the given variable as a C++ condition in an if,
1965/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001966ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00001967 SourceLocation StmtLoc,
1968 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001969 QualType T = ConditionVar->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001970
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001971 // C++ [stmt.select]p2:
1972 // The declarator shall not specify a function or an array.
1973 if (T->isFunctionType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001974 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001975 diag::err_invalid_use_of_function_type)
1976 << ConditionVar->getSourceRange());
1977 else if (T->isArrayType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001978 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001979 diag::err_invalid_use_of_array_type)
1980 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001981
John Wiegley429bb272011-04-08 18:41:53 +00001982 ExprResult Condition =
1983 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
Douglas Gregor40d96a62011-02-28 21:54:11 +00001984 ConditionVar,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001985 ConditionVar->getLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00001986 ConditionVar->getType().getNonReferenceType(),
John Wiegley429bb272011-04-08 18:41:53 +00001987 VK_LValue));
1988 if (ConvertToBoolean) {
1989 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
1990 if (Condition.isInvalid())
1991 return ExprError();
1992 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001993
John Wiegley429bb272011-04-08 18:41:53 +00001994 return move(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001995}
1996
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001997/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley429bb272011-04-08 18:41:53 +00001998ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001999 // C++ 6.4p4:
2000 // The value of a condition that is an initialized declaration in a statement
2001 // other than a switch statement is the value of the declared variable
2002 // implicitly converted to type bool. If that conversion is ill-formed, the
2003 // program is ill-formed.
2004 // The value of a condition that is an expression is the value of the
2005 // expression, implicitly converted to bool.
2006 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002007 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002008}
Douglas Gregor77a52232008-09-12 00:47:35 +00002009
2010/// Helper function to determine whether this is the (deprecated) C++
2011/// conversion from a string literal to a pointer to non-const char or
2012/// non-const wchar_t (for narrow and wide string literals,
2013/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00002014bool
Douglas Gregor77a52232008-09-12 00:47:35 +00002015Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2016 // Look inside the implicit cast, if it exists.
2017 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2018 From = Cast->getSubExpr();
2019
2020 // A string literal (2.13.4) that is not a wide string literal can
2021 // be converted to an rvalue of type "pointer to char"; a wide
2022 // string literal can be converted to an rvalue of type "pointer
2023 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00002024 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00002025 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00002026 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00002027 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00002028 // This conversion is considered only when there is an
2029 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregor5cee1192011-07-27 05:40:30 +00002030 if (!ToPtrType->getPointeeType().hasQualifiers()) {
2031 switch (StrLit->getKind()) {
2032 case StringLiteral::UTF8:
2033 case StringLiteral::UTF16:
2034 case StringLiteral::UTF32:
2035 // We don't allow UTF literals to be implicitly converted
2036 break;
2037 case StringLiteral::Ascii:
2038 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2039 ToPointeeType->getKind() == BuiltinType::Char_S);
2040 case StringLiteral::Wide:
2041 return ToPointeeType->isWideCharType();
2042 }
2043 }
Douglas Gregor77a52232008-09-12 00:47:35 +00002044 }
2045
2046 return false;
2047}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002048
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002049static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00002050 SourceLocation CastLoc,
2051 QualType Ty,
2052 CastKind Kind,
2053 CXXMethodDecl *Method,
John McCallca82a822011-09-21 08:36:56 +00002054 DeclAccessPair FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002055 bool HadMultipleCandidates,
John McCall2de56d12010-08-25 11:45:40 +00002056 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002057 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002058 default: llvm_unreachable("Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00002059 case CK_ConstructorConversion: {
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002060 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
John McCallca0408f2010-08-23 06:44:23 +00002061 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002062
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002063 if (S.CompleteConstructorCall(Constructor,
John McCallf312b1e2010-08-26 23:41:50 +00002064 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00002065 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00002066 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002067
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002068 S.CheckConstructorAccess(CastLoc, Constructor, Constructor->getAccess(),
2069 S.PDiag(diag::err_access_ctor));
2070
2071 ExprResult Result
2072 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2073 move_arg(ConstructorArgs),
2074 HadMultipleCandidates, /*ZeroInit*/ false,
2075 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002076 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00002077 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002078
Douglas Gregorba70ab62010-04-16 22:17:36 +00002079 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2080 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002081
John McCall2de56d12010-08-25 11:45:40 +00002082 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002083 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002084
Douglas Gregorba70ab62010-04-16 22:17:36 +00002085 // Create an implicit call expr that calls it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002086 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method,
2087 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002088 if (Result.isInvalid())
2089 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002090
John McCallca82a822011-09-21 08:36:56 +00002091 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2092
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002093 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002094 }
2095 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002096}
Douglas Gregorba70ab62010-04-16 22:17:36 +00002097
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002098/// PerformImplicitConversion - Perform an implicit conversion of the
2099/// expression From to the type ToType using the pre-computed implicit
John Wiegley429bb272011-04-08 18:41:53 +00002100/// conversion sequence ICS. Returns the converted
Douglas Gregor68647482009-12-16 03:45:30 +00002101/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002102/// used in the error message.
John Wiegley429bb272011-04-08 18:41:53 +00002103ExprResult
2104Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002105 const ImplicitConversionSequence &ICS,
John McCallf85e1932011-06-15 23:02:42 +00002106 AssignmentAction Action,
2107 CheckedConversionKind CCK) {
John McCall1d318332010-01-12 00:44:57 +00002108 switch (ICS.getKind()) {
John Wiegley429bb272011-04-08 18:41:53 +00002109 case ImplicitConversionSequence::StandardConversion: {
2110 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
John McCallf85e1932011-06-15 23:02:42 +00002111 Action, CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002112 if (Res.isInvalid())
2113 return ExprError();
2114 From = Res.take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002115 break;
John Wiegley429bb272011-04-08 18:41:53 +00002116 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002117
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002118 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002119
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00002120 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00002121 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002122 QualType BeforeToType;
2123 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00002124 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002125
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002126 // If the user-defined conversion is specified by a conversion function,
2127 // the initial standard conversion sequence converts the source type to
2128 // the implicit object parameter of the conversion function.
2129 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00002130 } else {
2131 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00002132 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002133 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00002134 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002135 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002136 // initial standard conversion sequence converts the source type to the
2137 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00002138 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2139 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002140 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00002141 // Watch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00002142 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley429bb272011-04-08 18:41:53 +00002143 ExprResult Res =
2144 PerformImplicitConversion(From, BeforeToType,
2145 ICS.UserDefined.Before, AA_Converting,
John McCallf85e1932011-06-15 23:02:42 +00002146 CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002147 if (Res.isInvalid())
2148 return ExprError();
2149 From = Res.take();
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002150 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002151
2152 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00002153 = BuildCXXCastArgument(*this,
2154 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00002155 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002156 CastKind, cast<CXXMethodDecl>(FD),
2157 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002158 ICS.UserDefined.HadMultipleCandidates,
John McCall9ae2f072010-08-23 23:25:46 +00002159 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002160
2161 if (CastArg.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00002162 return ExprError();
Eli Friedmand8889622009-11-27 04:41:50 +00002163
John Wiegley429bb272011-04-08 18:41:53 +00002164 From = CastArg.take();
Eli Friedmand8889622009-11-27 04:41:50 +00002165
Eli Friedmand8889622009-11-27 04:41:50 +00002166 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
John McCallf85e1932011-06-15 23:02:42 +00002167 AA_Converting, CCK);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00002168 }
John McCall1d318332010-01-12 00:44:57 +00002169
2170 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00002171 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00002172 PDiag(diag::err_typecheck_ambiguous_condition)
2173 << From->getSourceRange());
John Wiegley429bb272011-04-08 18:41:53 +00002174 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002175
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002176 case ImplicitConversionSequence::EllipsisConversion:
David Blaikieb219cfc2011-09-23 05:06:16 +00002177 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002178
2179 case ImplicitConversionSequence::BadConversion:
John Wiegley429bb272011-04-08 18:41:53 +00002180 return ExprError();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002181 }
2182
2183 // Everything went well.
John Wiegley429bb272011-04-08 18:41:53 +00002184 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002185}
2186
2187/// PerformImplicitConversion - Perform an implicit conversion of the
2188/// expression From to the type ToType by following the standard
John Wiegley429bb272011-04-08 18:41:53 +00002189/// conversion sequence SCS. Returns the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00002190/// expression. Flavor is the context in which we're performing this
2191/// conversion, for use in error messages.
John Wiegley429bb272011-04-08 18:41:53 +00002192ExprResult
2193Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00002194 const StandardConversionSequence& SCS,
John McCallf85e1932011-06-15 23:02:42 +00002195 AssignmentAction Action,
2196 CheckedConversionKind CCK) {
2197 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2198
Mike Stump390b4cc2009-05-16 07:39:55 +00002199 // Overall FIXME: we are recomputing too many types here and doing far too
2200 // much extra work. What this means is that we need to keep track of more
2201 // information that is computed when we try the implicit conversion initially,
2202 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002203 QualType FromType = From->getType();
John McCallf85e1932011-06-15 23:02:42 +00002204
Douglas Gregor225c41e2008-11-03 19:09:14 +00002205 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00002206 // FIXME: When can ToType be a reference type?
2207 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002208 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00002209 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002210 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00002211 MultiExprArg(*this, &From, 1),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002212 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002213 ConstructorArgs))
John Wiegley429bb272011-04-08 18:41:53 +00002214 return ExprError();
2215 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2216 ToType, SCS.CopyConstructor,
2217 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002218 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002219 /*ZeroInit*/ false,
2220 CXXConstructExpr::CK_Complete,
2221 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002222 }
John Wiegley429bb272011-04-08 18:41:53 +00002223 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2224 ToType, SCS.CopyConstructor,
2225 MultiExprArg(*this, &From, 1),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002226 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002227 /*ZeroInit*/ false,
2228 CXXConstructExpr::CK_Complete,
2229 SourceRange());
Douglas Gregor225c41e2008-11-03 19:09:14 +00002230 }
2231
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002232 // Resolve overloaded function references.
2233 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2234 DeclAccessPair Found;
2235 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2236 true, Found);
2237 if (!Fn)
John Wiegley429bb272011-04-08 18:41:53 +00002238 return ExprError();
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002239
2240 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
John Wiegley429bb272011-04-08 18:41:53 +00002241 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002242
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002243 From = FixOverloadedFunctionReference(From, Found, Fn);
2244 FromType = From->getType();
2245 }
2246
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002247 // Perform the first implicit conversion.
2248 switch (SCS.First) {
2249 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002250 // Nothing to do.
2251 break;
2252
John McCallf6a16482010-12-04 03:47:34 +00002253 case ICK_Lvalue_To_Rvalue:
2254 // Should this get its own ICK?
2255 if (From->getObjectKind() == OK_ObjCProperty) {
John Wiegley429bb272011-04-08 18:41:53 +00002256 ExprResult FromRes = ConvertPropertyForRValue(From);
2257 if (FromRes.isInvalid())
2258 return ExprError();
2259 From = FromRes.take();
John McCall241d5582010-12-07 22:54:16 +00002260 if (!From->isGLValue()) break;
John McCallf6a16482010-12-04 03:47:34 +00002261 }
2262
2263 FromType = FromType.getUnqualifiedType();
2264 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2265 From, 0, VK_RValue);
2266 break;
2267
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002268 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002269 FromType = Context.getArrayDecayedType(FromType);
John McCallf85e1932011-06-15 23:02:42 +00002270 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2271 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002272 break;
2273
2274 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002275 FromType = Context.getPointerType(FromType);
John McCallf85e1932011-06-15 23:02:42 +00002276 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2277 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002278 break;
2279
2280 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002281 llvm_unreachable("Improper first standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002282 }
2283
2284 // Perform the second implicit conversion
2285 switch (SCS.Second) {
2286 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002287 // If both sides are functions (or pointers/references to them), there could
2288 // be incompatible exception declarations.
2289 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002290 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002291 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002292 break;
2293
Douglas Gregor43c79c22009-12-09 00:47:37 +00002294 case ICK_NoReturn_Adjustment:
2295 // If both sides are functions (or pointers/references to them), there could
2296 // be incompatible exception declarations.
2297 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002298 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002299
John McCallf85e1932011-06-15 23:02:42 +00002300 From = ImpCastExprToType(From, ToType, CK_NoOp,
2301 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor43c79c22009-12-09 00:47:37 +00002302 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002303
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002304 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002305 case ICK_Integral_Conversion:
John McCallf85e1932011-06-15 23:02:42 +00002306 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2307 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002308 break;
2309
2310 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002311 case ICK_Floating_Conversion:
John McCallf85e1932011-06-15 23:02:42 +00002312 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2313 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002314 break;
2315
2316 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00002317 case ICK_Complex_Conversion: {
2318 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2319 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2320 CastKind CK;
2321 if (FromEl->isRealFloatingType()) {
2322 if (ToEl->isRealFloatingType())
2323 CK = CK_FloatingComplexCast;
2324 else
2325 CK = CK_FloatingComplexToIntegralComplex;
2326 } else if (ToEl->isRealFloatingType()) {
2327 CK = CK_IntegralComplexToFloatingComplex;
2328 } else {
2329 CK = CK_IntegralComplexCast;
2330 }
John McCallf85e1932011-06-15 23:02:42 +00002331 From = ImpCastExprToType(From, ToType, CK,
2332 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002333 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00002334 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002335
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002336 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002337 if (ToType->isRealFloatingType())
John McCallf85e1932011-06-15 23:02:42 +00002338 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2339 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002340 else
John McCallf85e1932011-06-15 23:02:42 +00002341 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2342 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002343 break;
2344
Douglas Gregorf9201e02009-02-11 23:02:49 +00002345 case ICK_Compatible_Conversion:
John McCallf85e1932011-06-15 23:02:42 +00002346 From = ImpCastExprToType(From, ToType, CK_NoOp,
2347 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002348 break;
2349
John McCallf85e1932011-06-15 23:02:42 +00002350 case ICK_Writeback_Conversion:
Anders Carlsson61faec12009-09-12 04:46:44 +00002351 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00002352 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002353 // Diagnose incompatible Objective-C conversions
Douglas Gregor8cf0d222011-06-11 04:42:12 +00002354 if (Action == AA_Initializing || Action == AA_Assigning)
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002355 Diag(From->getSourceRange().getBegin(),
2356 diag::ext_typecheck_convert_incompatible_pointer)
2357 << ToType << From->getType() << Action
Anna Zaks67221552011-07-28 19:51:27 +00002358 << From->getSourceRange() << 0;
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002359 else
2360 Diag(From->getSourceRange().getBegin(),
2361 diag::ext_typecheck_convert_incompatible_pointer)
2362 << From->getType() << ToType << Action
Anna Zaks67221552011-07-28 19:51:27 +00002363 << From->getSourceRange() << 0;
John McCallf85e1932011-06-15 23:02:42 +00002364
Douglas Gregor926df6c2011-06-11 01:09:30 +00002365 if (From->getType()->isObjCObjectPointerType() &&
2366 ToType->isObjCObjectPointerType())
2367 EmitRelatedResultTypeNote(From);
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002368 }
2369 else if (getLangOptions().ObjCAutoRefCount &&
2370 !CheckObjCARCUnavailableWeakConversion(ToType,
2371 From->getType())) {
John McCall7f3a6d32011-09-09 06:12:06 +00002372 if (Action == AA_Initializing)
2373 Diag(From->getSourceRange().getBegin(),
2374 diag::err_arc_weak_unavailable_assign);
2375 else
2376 Diag(From->getSourceRange().getBegin(),
2377 diag::err_arc_convesion_of_weak_unavailable)
2378 << (Action == AA_Casting) << From->getType() << ToType
2379 << From->getSourceRange();
2380 }
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002381
John McCalldaa8e4e2010-11-15 09:13:47 +00002382 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002383 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002384 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002385 return ExprError();
John McCalldc05b112011-09-10 01:16:55 +00002386
2387 // Make sure we extend blocks if necessary.
2388 // FIXME: doing this here is really ugly.
2389 if (Kind == CK_BlockPointerToObjCPointerCast) {
2390 ExprResult E = From;
2391 (void) PrepareCastToObjCObjectPointer(E);
2392 From = E.take();
2393 }
2394
John McCallf85e1932011-06-15 23:02:42 +00002395 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2396 .take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002397 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00002398 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002399
Anders Carlsson61faec12009-09-12 04:46:44 +00002400 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002401 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002402 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002403 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002404 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002405 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002406 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00002407 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2408 .take();
Anders Carlsson61faec12009-09-12 04:46:44 +00002409 break;
2410 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002411
Abramo Bagnara737d5442011-04-07 09:26:19 +00002412 case ICK_Boolean_Conversion:
John Wiegley429bb272011-04-08 18:41:53 +00002413 From = ImpCastExprToType(From, Context.BoolTy,
John McCallf85e1932011-06-15 23:02:42 +00002414 ScalarTypeToBooleanCastKind(FromType),
2415 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002416 break;
2417
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002418 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002419 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002420 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002421 ToType.getNonReferenceType(),
2422 From->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002423 From->getSourceRange(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002424 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002425 CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002426 return ExprError();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002427
John Wiegley429bb272011-04-08 18:41:53 +00002428 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002429 CK_DerivedToBase, From->getValueKind(),
John McCallf85e1932011-06-15 23:02:42 +00002430 &BasePath, CCK).take();
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002431 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002432 }
2433
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002434 case ICK_Vector_Conversion:
John McCallf85e1932011-06-15 23:02:42 +00002435 From = ImpCastExprToType(From, ToType, CK_BitCast,
2436 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002437 break;
2438
2439 case ICK_Vector_Splat:
John McCallf85e1932011-06-15 23:02:42 +00002440 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2441 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002442 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002443
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002444 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002445 // Case 1. x -> _Complex y
2446 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2447 QualType ElType = ToComplex->getElementType();
2448 bool isFloatingComplex = ElType->isRealFloatingType();
2449
2450 // x -> y
2451 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2452 // do nothing
2453 } else if (From->getType()->isRealFloatingType()) {
John Wiegley429bb272011-04-08 18:41:53 +00002454 From = ImpCastExprToType(From, ElType,
2455 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002456 } else {
2457 assert(From->getType()->isIntegerType());
John Wiegley429bb272011-04-08 18:41:53 +00002458 From = ImpCastExprToType(From, ElType,
2459 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002460 }
2461 // y -> _Complex y
John Wiegley429bb272011-04-08 18:41:53 +00002462 From = ImpCastExprToType(From, ToType,
John McCalldaa8e4e2010-11-15 09:13:47 +00002463 isFloatingComplex ? CK_FloatingRealToComplex
John Wiegley429bb272011-04-08 18:41:53 +00002464 : CK_IntegralRealToComplex).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002465
2466 // Case 2. _Complex x -> y
2467 } else {
2468 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2469 assert(FromComplex);
2470
2471 QualType ElType = FromComplex->getElementType();
2472 bool isFloatingComplex = ElType->isRealFloatingType();
2473
2474 // _Complex x -> x
John Wiegley429bb272011-04-08 18:41:53 +00002475 From = ImpCastExprToType(From, ElType,
John McCalldaa8e4e2010-11-15 09:13:47 +00002476 isFloatingComplex ? CK_FloatingComplexToReal
John McCallf85e1932011-06-15 23:02:42 +00002477 : CK_IntegralComplexToReal,
2478 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002479
2480 // x -> y
2481 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2482 // do nothing
2483 } else if (ToType->isRealFloatingType()) {
John Wiegley429bb272011-04-08 18:41:53 +00002484 From = ImpCastExprToType(From, ToType,
John McCallf85e1932011-06-15 23:02:42 +00002485 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2486 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002487 } else {
2488 assert(ToType->isIntegerType());
John Wiegley429bb272011-04-08 18:41:53 +00002489 From = ImpCastExprToType(From, ToType,
John McCallf85e1932011-06-15 23:02:42 +00002490 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2491 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002492 }
2493 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002494 break;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002495
2496 case ICK_Block_Pointer_Conversion: {
John McCallf85e1932011-06-15 23:02:42 +00002497 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2498 VK_RValue, /*BasePath=*/0, CCK).take();
2499 break;
2500 }
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002501
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002502 case ICK_TransparentUnionConversion: {
John Wiegley429bb272011-04-08 18:41:53 +00002503 ExprResult FromRes = Owned(From);
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002504 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002505 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2506 if (FromRes.isInvalid())
2507 return ExprError();
2508 From = FromRes.take();
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002509 assert ((ConvTy == Sema::Compatible) &&
2510 "Improper transparent union conversion");
2511 (void)ConvTy;
2512 break;
2513 }
2514
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002515 case ICK_Lvalue_To_Rvalue:
2516 case ICK_Array_To_Pointer:
2517 case ICK_Function_To_Pointer:
2518 case ICK_Qualification:
2519 case ICK_Num_Conversion_Kinds:
David Blaikieb219cfc2011-09-23 05:06:16 +00002520 llvm_unreachable("Improper second standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002521 }
2522
2523 switch (SCS.Third) {
2524 case ICK_Identity:
2525 // Nothing to do.
2526 break;
2527
Sebastian Redl906082e2010-07-20 04:20:21 +00002528 case ICK_Qualification: {
2529 // The qualification keeps the category of the inner expression, unless the
2530 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002531 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002532 From->getValueKind() : VK_RValue;
John Wiegley429bb272011-04-08 18:41:53 +00002533 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
John McCallf85e1932011-06-15 23:02:42 +00002534 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
Douglas Gregora9bff302010-02-28 18:30:25 +00002535
Douglas Gregor069a6da2011-03-14 16:13:32 +00002536 if (SCS.DeprecatedStringLiteralToCharPtr &&
2537 !getLangOptions().WritableStrings)
Douglas Gregora9bff302010-02-28 18:30:25 +00002538 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2539 << ToType.getNonReferenceType();
2540
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002541 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002542 }
2543
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002544 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002545 llvm_unreachable("Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002546 }
2547
John Wiegley429bb272011-04-08 18:41:53 +00002548 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002549}
2550
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002551ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002552 SourceLocation KWLoc,
2553 ParsedType Ty,
2554 SourceLocation RParen) {
2555 TypeSourceInfo *TSInfo;
2556 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002557
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002558 if (!TSInfo)
2559 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002560 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002561}
2562
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002563/// \brief Check the completeness of a type in a unary type trait.
2564///
2565/// If the particular type trait requires a complete type, tries to complete
2566/// it. If completing the type fails, a diagnostic is emitted and false
2567/// returned. If completing the type succeeds or no completion was required,
2568/// returns true.
2569static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2570 UnaryTypeTrait UTT,
2571 SourceLocation Loc,
2572 QualType ArgTy) {
2573 // C++0x [meta.unary.prop]p3:
2574 // For all of the class templates X declared in this Clause, instantiating
2575 // that template with a template argument that is a class template
2576 // specialization may result in the implicit instantiation of the template
2577 // argument if and only if the semantics of X require that the argument
2578 // must be a complete type.
2579 // We apply this rule to all the type trait expressions used to implement
2580 // these class templates. We also try to follow any GCC documented behavior
2581 // in these expressions to ensure portability of standard libraries.
2582 switch (UTT) {
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002583 // is_complete_type somewhat obviously cannot require a complete type.
2584 case UTT_IsCompleteType:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002585 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002586
2587 // These traits are modeled on the type predicates in C++0x
2588 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2589 // requiring a complete type, as whether or not they return true cannot be
2590 // impacted by the completeness of the type.
2591 case UTT_IsVoid:
2592 case UTT_IsIntegral:
2593 case UTT_IsFloatingPoint:
2594 case UTT_IsArray:
2595 case UTT_IsPointer:
2596 case UTT_IsLvalueReference:
2597 case UTT_IsRvalueReference:
2598 case UTT_IsMemberFunctionPointer:
2599 case UTT_IsMemberObjectPointer:
2600 case UTT_IsEnum:
2601 case UTT_IsUnion:
2602 case UTT_IsClass:
2603 case UTT_IsFunction:
2604 case UTT_IsReference:
2605 case UTT_IsArithmetic:
2606 case UTT_IsFundamental:
2607 case UTT_IsObject:
2608 case UTT_IsScalar:
2609 case UTT_IsCompound:
2610 case UTT_IsMemberPointer:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002611 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002612
2613 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2614 // which requires some of its traits to have the complete type. However,
2615 // the completeness of the type cannot impact these traits' semantics, and
2616 // so they don't require it. This matches the comments on these traits in
2617 // Table 49.
2618 case UTT_IsConst:
2619 case UTT_IsVolatile:
2620 case UTT_IsSigned:
2621 case UTT_IsUnsigned:
2622 return true;
2623
2624 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002625 // applied to a complete type.
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002626 case UTT_IsTrivial:
Sean Huntfeb375d2011-05-13 00:31:07 +00002627 case UTT_IsTriviallyCopyable:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002628 case UTT_IsStandardLayout:
2629 case UTT_IsPOD:
2630 case UTT_IsLiteral:
2631 case UTT_IsEmpty:
2632 case UTT_IsPolymorphic:
2633 case UTT_IsAbstract:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002634 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002635
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002636 // These trait expressions are designed to help implement predicates in
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002637 // [meta.unary.prop] despite not being named the same. They are specified
2638 // by both GCC and the Embarcadero C++ compiler, and require the complete
2639 // type due to the overarching C++0x type predicates being implemented
2640 // requiring the complete type.
2641 case UTT_HasNothrowAssign:
2642 case UTT_HasNothrowConstructor:
2643 case UTT_HasNothrowCopy:
2644 case UTT_HasTrivialAssign:
Sean Hunt023df372011-05-09 18:22:59 +00002645 case UTT_HasTrivialDefaultConstructor:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002646 case UTT_HasTrivialCopy:
2647 case UTT_HasTrivialDestructor:
2648 case UTT_HasVirtualDestructor:
2649 // Arrays of unknown bound are expressly allowed.
2650 QualType ElTy = ArgTy;
2651 if (ArgTy->isIncompleteArrayType())
2652 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2653
2654 // The void type is expressly allowed.
2655 if (ElTy->isVoidType())
2656 return true;
2657
2658 return !S.RequireCompleteType(
2659 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleycf566412011-04-28 02:06:46 +00002660 }
Chandler Carruth73e0a912011-05-01 07:23:17 +00002661 llvm_unreachable("Type trait not handled by switch");
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002662}
2663
2664static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2665 SourceLocation KeyLoc, QualType T) {
Chandler Carruthd064c702011-05-01 08:41:10 +00002666 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleycf566412011-04-28 02:06:46 +00002667
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002668 ASTContext &C = Self.Context;
2669 switch(UTT) {
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002670 // Type trait expressions corresponding to the primary type category
2671 // predicates in C++0x [meta.unary.cat].
2672 case UTT_IsVoid:
2673 return T->isVoidType();
2674 case UTT_IsIntegral:
2675 return T->isIntegralType(C);
2676 case UTT_IsFloatingPoint:
2677 return T->isFloatingType();
2678 case UTT_IsArray:
2679 return T->isArrayType();
2680 case UTT_IsPointer:
2681 return T->isPointerType();
2682 case UTT_IsLvalueReference:
2683 return T->isLValueReferenceType();
2684 case UTT_IsRvalueReference:
2685 return T->isRValueReferenceType();
2686 case UTT_IsMemberFunctionPointer:
2687 return T->isMemberFunctionPointerType();
2688 case UTT_IsMemberObjectPointer:
2689 return T->isMemberDataPointerType();
2690 case UTT_IsEnum:
2691 return T->isEnumeralType();
Chandler Carruth28eeb382011-05-01 06:11:03 +00002692 case UTT_IsUnion:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002693 return T->isUnionType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002694 case UTT_IsClass:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002695 return T->isClassType() || T->isStructureType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002696 case UTT_IsFunction:
2697 return T->isFunctionType();
2698
2699 // Type trait expressions which correspond to the convenient composition
2700 // predicates in C++0x [meta.unary.comp].
2701 case UTT_IsReference:
2702 return T->isReferenceType();
2703 case UTT_IsArithmetic:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002704 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002705 case UTT_IsFundamental:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002706 return T->isFundamentalType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002707 case UTT_IsObject:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002708 return T->isObjectType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002709 case UTT_IsScalar:
John McCallf85e1932011-06-15 23:02:42 +00002710 // Note: semantic analysis depends on Objective-C lifetime types to be
2711 // considered scalar types. However, such types do not actually behave
2712 // like scalar types at run time (since they may require retain/release
2713 // operations), so we report them as non-scalar.
2714 if (T->isObjCLifetimeType()) {
2715 switch (T.getObjCLifetime()) {
2716 case Qualifiers::OCL_None:
2717 case Qualifiers::OCL_ExplicitNone:
2718 return true;
2719
2720 case Qualifiers::OCL_Strong:
2721 case Qualifiers::OCL_Weak:
2722 case Qualifiers::OCL_Autoreleasing:
2723 return false;
2724 }
2725 }
2726
Chandler Carruthcec0ced2011-05-01 09:29:55 +00002727 return T->isScalarType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002728 case UTT_IsCompound:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002729 return T->isCompoundType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002730 case UTT_IsMemberPointer:
2731 return T->isMemberPointerType();
2732
2733 // Type trait expressions which correspond to the type property predicates
2734 // in C++0x [meta.unary.prop].
2735 case UTT_IsConst:
2736 return T.isConstQualified();
2737 case UTT_IsVolatile:
2738 return T.isVolatileQualified();
2739 case UTT_IsTrivial:
John McCallf85e1932011-06-15 23:02:42 +00002740 return T.isTrivialType(Self.Context);
Sean Huntfeb375d2011-05-13 00:31:07 +00002741 case UTT_IsTriviallyCopyable:
John McCallf85e1932011-06-15 23:02:42 +00002742 return T.isTriviallyCopyableType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002743 case UTT_IsStandardLayout:
2744 return T->isStandardLayoutType();
2745 case UTT_IsPOD:
John McCallf85e1932011-06-15 23:02:42 +00002746 return T.isPODType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002747 case UTT_IsLiteral:
2748 return T->isLiteralType();
2749 case UTT_IsEmpty:
2750 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2751 return !RD->isUnion() && RD->isEmpty();
2752 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002753 case UTT_IsPolymorphic:
Chandler Carruth28eeb382011-05-01 06:11:03 +00002754 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2755 return RD->isPolymorphic();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002756 return false;
2757 case UTT_IsAbstract:
Chandler Carruth28eeb382011-05-01 06:11:03 +00002758 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2759 return RD->isAbstract();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002760 return false;
John Wiegley20c0da72011-04-27 23:09:49 +00002761 case UTT_IsSigned:
2762 return T->isSignedIntegerType();
John Wiegley20c0da72011-04-27 23:09:49 +00002763 case UTT_IsUnsigned:
2764 return T->isUnsignedIntegerType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002765
2766 // Type trait expressions which query classes regarding their construction,
2767 // destruction, and copying. Rather than being based directly on the
2768 // related type predicates in the standard, they are specified by both
2769 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
2770 // specifications.
2771 //
2772 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
2773 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Sean Hunt023df372011-05-09 18:22:59 +00002774 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002775 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2776 // If __is_pod (type) is true then the trait is true, else if type is
2777 // a cv class or union type (or array thereof) with a trivial default
2778 // constructor ([class.ctor]) then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002779 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002780 return true;
2781 if (const RecordType *RT =
2782 C.getBaseElementType(T)->getAs<RecordType>())
Sean Hunt023df372011-05-09 18:22:59 +00002783 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002784 return false;
2785 case UTT_HasTrivialCopy:
2786 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2787 // If __is_pod (type) is true or type is a reference type then
2788 // the trait is true, else if type is a cv class or union type
2789 // with a trivial copy constructor ([class.copy]) then the trait
2790 // is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002791 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002792 return true;
2793 if (const RecordType *RT = T->getAs<RecordType>())
2794 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2795 return false;
2796 case UTT_HasTrivialAssign:
2797 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2798 // If type is const qualified or is a reference type then the
2799 // trait is false. Otherwise if __is_pod (type) is true then the
2800 // trait is true, else if type is a cv class or union type with
2801 // a trivial copy assignment ([class.copy]) then the trait is
2802 // true, else it is false.
2803 // Note: the const and reference restrictions are interesting,
2804 // given that const and reference members don't prevent a class
2805 // from having a trivial copy assignment operator (but do cause
2806 // errors if the copy assignment operator is actually used, q.v.
2807 // [class.copy]p12).
2808
2809 if (C.getBaseElementType(T).isConstQualified())
2810 return false;
John McCallf85e1932011-06-15 23:02:42 +00002811 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002812 return true;
2813 if (const RecordType *RT = T->getAs<RecordType>())
2814 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2815 return false;
2816 case UTT_HasTrivialDestructor:
2817 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2818 // If __is_pod (type) is true or type is a reference type
2819 // then the trait is true, else if type is a cv class or union
2820 // type (or array thereof) with a trivial destructor
2821 // ([class.dtor]) then the trait is true, else it is
2822 // false.
John McCallf85e1932011-06-15 23:02:42 +00002823 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002824 return true;
John McCallf85e1932011-06-15 23:02:42 +00002825
2826 // Objective-C++ ARC: autorelease types don't require destruction.
2827 if (T->isObjCLifetimeType() &&
2828 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
2829 return true;
2830
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002831 if (const RecordType *RT =
2832 C.getBaseElementType(T)->getAs<RecordType>())
2833 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2834 return false;
2835 // TODO: Propagate nothrowness for implicitly declared special members.
2836 case UTT_HasNothrowAssign:
2837 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2838 // If type is const qualified or is a reference type then the
2839 // trait is false. Otherwise if __has_trivial_assign (type)
2840 // is true then the trait is true, else if type is a cv class
2841 // or union type with copy assignment operators that are known
2842 // not to throw an exception then the trait is true, else it is
2843 // false.
2844 if (C.getBaseElementType(T).isConstQualified())
2845 return false;
2846 if (T->isReferenceType())
2847 return false;
John McCallf85e1932011-06-15 23:02:42 +00002848 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
2849 return true;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002850 if (const RecordType *RT = T->getAs<RecordType>()) {
2851 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2852 if (RD->hasTrivialCopyAssignment())
2853 return true;
2854
2855 bool FoundAssign = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002856 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00002857 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2858 Sema::LookupOrdinaryName);
2859 if (Self.LookupQualifiedName(Res, RD)) {
2860 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2861 Op != OpEnd; ++Op) {
2862 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2863 if (Operator->isCopyAssignmentOperator()) {
2864 FoundAssign = true;
2865 const FunctionProtoType *CPT
2866 = Operator->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00002867 if (CPT->getExceptionSpecType() == EST_Delayed)
2868 return false;
2869 if (!CPT->isNothrow(Self.Context))
2870 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002871 }
2872 }
2873 }
2874
Richard Smith7a614d82011-06-11 17:19:42 +00002875 return FoundAssign;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002876 }
2877 return false;
2878 case UTT_HasNothrowCopy:
2879 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2880 // If __has_trivial_copy (type) is true then the trait is true, else
2881 // if type is a cv class or union type with copy constructors that are
2882 // known not to throw an exception then the trait is true, else it is
2883 // false.
John McCallf85e1932011-06-15 23:02:42 +00002884 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002885 return true;
2886 if (const RecordType *RT = T->getAs<RecordType>()) {
2887 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2888 if (RD->hasTrivialCopyConstructor())
2889 return true;
2890
2891 bool FoundConstructor = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002892 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002893 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00002894 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002895 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002896 // A template constructor is never a copy constructor.
2897 // FIXME: However, it may actually be selected at the actual overload
2898 // resolution point.
2899 if (isa<FunctionTemplateDecl>(*Con))
2900 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002901 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2902 if (Constructor->isCopyConstructor(FoundTQs)) {
2903 FoundConstructor = true;
2904 const FunctionProtoType *CPT
2905 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00002906 if (CPT->getExceptionSpecType() == EST_Delayed)
2907 return false;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002908 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redl751025d2010-09-13 22:02:47 +00002909 // For now, we'll be conservative and assume that they can throw.
Richard Smith7a614d82011-06-11 17:19:42 +00002910 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
2911 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002912 }
2913 }
2914
Richard Smith7a614d82011-06-11 17:19:42 +00002915 return FoundConstructor;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002916 }
2917 return false;
2918 case UTT_HasNothrowConstructor:
2919 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2920 // If __has_trivial_constructor (type) is true then the trait is
2921 // true, else if type is a cv class or union type (or array
2922 // thereof) with a default constructor that is known not to
2923 // throw an exception then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002924 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002925 return true;
2926 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2927 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Hunt023df372011-05-09 18:22:59 +00002928 if (RD->hasTrivialDefaultConstructor())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002929 return true;
2930
Sebastian Redl751025d2010-09-13 22:02:47 +00002931 DeclContext::lookup_const_iterator Con, ConEnd;
2932 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2933 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002934 // FIXME: In C++0x, a constructor template can be a default constructor.
2935 if (isa<FunctionTemplateDecl>(*Con))
2936 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00002937 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2938 if (Constructor->isDefaultConstructor()) {
2939 const FunctionProtoType *CPT
2940 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00002941 if (CPT->getExceptionSpecType() == EST_Delayed)
2942 return false;
Sebastian Redl751025d2010-09-13 22:02:47 +00002943 // TODO: check whether evaluating default arguments can throw.
2944 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002945 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
Sebastian Redl751025d2010-09-13 22:02:47 +00002946 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002947 }
2948 }
2949 return false;
2950 case UTT_HasVirtualDestructor:
2951 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2952 // If type is a class type with a virtual destructor ([class.dtor])
2953 // then the trait is true, else it is false.
2954 if (const RecordType *Record = T->getAs<RecordType>()) {
2955 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00002956 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002957 return Destructor->isVirtual();
2958 }
2959 return false;
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002960
2961 // These type trait expressions are modeled on the specifications for the
2962 // Embarcadero C++0x type trait functions:
2963 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
2964 case UTT_IsCompleteType:
2965 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
2966 // Returns True if and only if T is a complete type at the point of the
2967 // function call.
2968 return !T->isIncompleteType();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002969 }
Chandler Carruth83f563c2011-05-01 07:44:17 +00002970 llvm_unreachable("Type trait not covered by switch");
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002971}
2972
2973ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002974 SourceLocation KWLoc,
2975 TypeSourceInfo *TSInfo,
2976 SourceLocation RParen) {
2977 QualType T = TSInfo->getType();
Chandler Carrutheb65a102011-04-30 10:07:32 +00002978 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
2979 return ExprError();
Sebastian Redl64b45f72009-01-05 20:52:13 +00002980
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002981 bool Value = false;
2982 if (!T->isDependentType())
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002983 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002984
2985 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002986 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00002987}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002988
Francois Pichet6ad6f282010-12-07 00:08:36 +00002989ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
2990 SourceLocation KWLoc,
2991 ParsedType LhsTy,
2992 ParsedType RhsTy,
2993 SourceLocation RParen) {
2994 TypeSourceInfo *LhsTSInfo;
2995 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
2996 if (!LhsTSInfo)
2997 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
2998
2999 TypeSourceInfo *RhsTSInfo;
3000 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3001 if (!RhsTSInfo)
3002 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3003
3004 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3005}
3006
3007static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3008 QualType LhsT, QualType RhsT,
3009 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003010 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3011 "Cannot evaluate traits of dependent types");
Francois Pichet6ad6f282010-12-07 00:08:36 +00003012
3013 switch(BTT) {
John McCalld89d30f2011-01-28 22:02:36 +00003014 case BTT_IsBaseOf: {
Francois Pichet6ad6f282010-12-07 00:08:36 +00003015 // C++0x [meta.rel]p2
John McCalld89d30f2011-01-28 22:02:36 +00003016 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet6ad6f282010-12-07 00:08:36 +00003017 // Base and Derived are not unions and name the same class type without
3018 // regard to cv-qualifiers.
Francois Pichet6ad6f282010-12-07 00:08:36 +00003019
John McCalld89d30f2011-01-28 22:02:36 +00003020 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3021 if (!lhsRecord) return false;
3022
3023 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3024 if (!rhsRecord) return false;
3025
3026 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3027 == (lhsRecord == rhsRecord));
3028
3029 if (lhsRecord == rhsRecord)
3030 return !lhsRecord->getDecl()->isUnion();
3031
3032 // C++0x [meta.rel]p2:
3033 // If Base and Derived are class types and are different types
3034 // (ignoring possible cv-qualifiers) then Derived shall be a
3035 // complete type.
3036 if (Self.RequireCompleteType(KeyLoc, RhsT,
3037 diag::err_incomplete_type_used_in_type_trait_expr))
3038 return false;
3039
3040 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3041 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3042 }
John Wiegley20c0da72011-04-27 23:09:49 +00003043 case BTT_IsSame:
3044 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichetf1872372010-12-08 22:35:30 +00003045 case BTT_TypeCompatible:
3046 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3047 RhsT.getUnqualifiedType());
John Wiegley20c0da72011-04-27 23:09:49 +00003048 case BTT_IsConvertible:
Douglas Gregor9f361132011-01-27 20:28:01 +00003049 case BTT_IsConvertibleTo: {
3050 // C++0x [meta.rel]p4:
3051 // Given the following function prototype:
3052 //
3053 // template <class T>
3054 // typename add_rvalue_reference<T>::type create();
3055 //
3056 // the predicate condition for a template specialization
3057 // is_convertible<From, To> shall be satisfied if and only if
3058 // the return expression in the following code would be
3059 // well-formed, including any implicit conversions to the return
3060 // type of the function:
3061 //
3062 // To test() {
3063 // return create<From>();
3064 // }
3065 //
3066 // Access checking is performed as if in a context unrelated to To and
3067 // From. Only the validity of the immediate context of the expression
3068 // of the return-statement (including conversions to the return type)
3069 // is considered.
3070 //
3071 // We model the initialization as a copy-initialization of a temporary
3072 // of the appropriate type, which for this expression is identical to the
3073 // return statement (since NRVO doesn't apply).
3074 if (LhsT->isObjectType() || LhsT->isFunctionType())
3075 LhsT = Self.Context.getRValueReferenceType(LhsT);
3076
3077 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorb608b982011-01-28 02:26:04 +00003078 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor9f361132011-01-27 20:28:01 +00003079 Expr::getValueKindForType(LhsT));
3080 Expr *FromPtr = &From;
3081 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3082 SourceLocation()));
3083
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003084 // Perform the initialization within a SFINAE trap at translation unit
3085 // scope.
3086 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3087 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor9f361132011-01-27 20:28:01 +00003088 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003089 if (Init.Failed())
Douglas Gregor9f361132011-01-27 20:28:01 +00003090 return false;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003091
Douglas Gregor9f361132011-01-27 20:28:01 +00003092 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
3093 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3094 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003095 }
3096 llvm_unreachable("Unknown type trait or not implemented");
3097}
3098
3099ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3100 SourceLocation KWLoc,
3101 TypeSourceInfo *LhsTSInfo,
3102 TypeSourceInfo *RhsTSInfo,
3103 SourceLocation RParen) {
3104 QualType LhsT = LhsTSInfo->getType();
3105 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003106
John McCalld89d30f2011-01-28 22:02:36 +00003107 if (BTT == BTT_TypeCompatible) {
Francois Pichetf1872372010-12-08 22:35:30 +00003108 if (getLangOptions().CPlusPlus) {
3109 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3110 << SourceRange(KWLoc, RParen);
3111 return ExprError();
3112 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003113 }
3114
3115 bool Value = false;
3116 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3117 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3118
Francois Pichetf1872372010-12-08 22:35:30 +00003119 // Select trait result type.
3120 QualType ResultType;
3121 switch (BTT) {
Francois Pichetf1872372010-12-08 22:35:30 +00003122 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
John Wiegley20c0da72011-04-27 23:09:49 +00003123 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3124 case BTT_IsSame: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003125 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor9f361132011-01-27 20:28:01 +00003126 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003127 }
3128
Francois Pichet6ad6f282010-12-07 00:08:36 +00003129 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3130 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00003131 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00003132}
3133
John Wiegley21ff2e52011-04-28 00:16:57 +00003134ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3135 SourceLocation KWLoc,
3136 ParsedType Ty,
3137 Expr* DimExpr,
3138 SourceLocation RParen) {
3139 TypeSourceInfo *TSInfo;
3140 QualType T = GetTypeFromParser(Ty, &TSInfo);
3141 if (!TSInfo)
3142 TSInfo = Context.getTrivialTypeSourceInfo(T);
3143
3144 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3145}
3146
3147static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3148 QualType T, Expr *DimExpr,
3149 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003150 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley21ff2e52011-04-28 00:16:57 +00003151
3152 switch(ATT) {
3153 case ATT_ArrayRank:
3154 if (T->isArrayType()) {
3155 unsigned Dim = 0;
3156 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3157 ++Dim;
3158 T = AT->getElementType();
3159 }
3160 return Dim;
John Wiegley21ff2e52011-04-28 00:16:57 +00003161 }
John Wiegleycf566412011-04-28 02:06:46 +00003162 return 0;
3163
John Wiegley21ff2e52011-04-28 00:16:57 +00003164 case ATT_ArrayExtent: {
3165 llvm::APSInt Value;
3166 uint64_t Dim;
John Wiegleycf566412011-04-28 02:06:46 +00003167 if (DimExpr->isIntegerConstantExpr(Value, Self.Context, 0, false)) {
3168 if (Value < llvm::APSInt(Value.getBitWidth(), Value.isUnsigned())) {
3169 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3170 DimExpr->getSourceRange();
3171 return false;
3172 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003173 Dim = Value.getLimitedValue();
John Wiegleycf566412011-04-28 02:06:46 +00003174 } else {
3175 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3176 DimExpr->getSourceRange();
3177 return false;
3178 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003179
3180 if (T->isArrayType()) {
3181 unsigned D = 0;
3182 bool Matched = false;
3183 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3184 if (Dim == D) {
3185 Matched = true;
3186 break;
3187 }
3188 ++D;
3189 T = AT->getElementType();
3190 }
3191
John Wiegleycf566412011-04-28 02:06:46 +00003192 if (Matched && T->isArrayType()) {
3193 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3194 return CAT->getSize().getLimitedValue();
3195 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003196 }
John Wiegleycf566412011-04-28 02:06:46 +00003197 return 0;
John Wiegley21ff2e52011-04-28 00:16:57 +00003198 }
3199 }
3200 llvm_unreachable("Unknown type trait or not implemented");
3201}
3202
3203ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3204 SourceLocation KWLoc,
3205 TypeSourceInfo *TSInfo,
3206 Expr* DimExpr,
3207 SourceLocation RParen) {
3208 QualType T = TSInfo->getType();
John Wiegley21ff2e52011-04-28 00:16:57 +00003209
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003210 // FIXME: This should likely be tracked as an APInt to remove any host
3211 // assumptions about the width of size_t on the target.
Chandler Carruthd064c702011-05-01 08:41:10 +00003212 uint64_t Value = 0;
3213 if (!T->isDependentType())
3214 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3215
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003216 // While the specification for these traits from the Embarcadero C++
3217 // compiler's documentation says the return type is 'unsigned int', Clang
3218 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3219 // compiler, there is no difference. On several other platforms this is an
3220 // important distinction.
John Wiegley21ff2e52011-04-28 00:16:57 +00003221 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
Chandler Carruth06207f62011-05-01 07:49:26 +00003222 DimExpr, RParen,
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003223 Context.getSizeType()));
John Wiegley21ff2e52011-04-28 00:16:57 +00003224}
3225
John Wiegley55262202011-04-25 06:54:41 +00003226ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003227 SourceLocation KWLoc,
3228 Expr *Queried,
3229 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003230 // If error parsing the expression, ignore.
3231 if (!Queried)
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003232 return ExprError();
John Wiegley55262202011-04-25 06:54:41 +00003233
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003234 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegley55262202011-04-25 06:54:41 +00003235
3236 return move(Result);
3237}
3238
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003239static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3240 switch (ET) {
3241 case ET_IsLValueExpr: return E->isLValue();
3242 case ET_IsRValueExpr: return E->isRValue();
3243 }
3244 llvm_unreachable("Expression trait not covered by switch");
3245}
3246
John Wiegley55262202011-04-25 06:54:41 +00003247ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003248 SourceLocation KWLoc,
3249 Expr *Queried,
3250 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003251 if (Queried->isTypeDependent()) {
3252 // Delay type-checking for type-dependent expressions.
3253 } else if (Queried->getType()->isPlaceholderType()) {
3254 ExprResult PE = CheckPlaceholderExpr(Queried);
3255 if (PE.isInvalid()) return ExprError();
3256 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3257 }
3258
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003259 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf7ef0002011-05-01 08:48:19 +00003260
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003261 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3262 RParen, Context.BoolTy));
John Wiegley55262202011-04-25 06:54:41 +00003263}
3264
Richard Trieudd225092011-09-15 21:56:47 +00003265QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCallf89e55a2010-11-18 06:31:45 +00003266 ExprValueKind &VK,
3267 SourceLocation Loc,
3268 bool isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003269 assert(!LHS.get()->getType()->isPlaceholderType() &&
3270 !RHS.get()->getType()->isPlaceholderType() &&
John McCallea4aba02011-06-30 17:15:34 +00003271 "placeholders should have been weeded out by now");
3272
3273 // The LHS undergoes lvalue conversions if this is ->*.
3274 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003275 LHS = DefaultLvalueConversion(LHS.take());
3276 if (LHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003277 }
3278
3279 // The RHS always undergoes lvalue conversions.
Richard Trieudd225092011-09-15 21:56:47 +00003280 RHS = DefaultLvalueConversion(RHS.take());
3281 if (RHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003282
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003283 const char *OpSpelling = isIndirect ? "->*" : ".*";
3284 // C++ 5.5p2
3285 // The binary operator .* [p3: ->*] binds its second operand, which shall
3286 // be of type "pointer to member of T" (where T is a completely-defined
3287 // class type) [...]
Richard Trieudd225092011-09-15 21:56:47 +00003288 QualType RHSType = RHS.get()->getType();
3289 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00003290 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003291 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieudd225092011-09-15 21:56:47 +00003292 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003293 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00003294 }
Douglas Gregore7450f52009-03-24 19:52:54 +00003295
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003296 QualType Class(MemPtr->getClass(), 0);
3297
Douglas Gregor7d520ba2010-10-13 20:41:14 +00003298 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3299 // member pointer points must be completely-defined. However, there is no
3300 // reason for this semantic distinction, and the rule is not enforced by
3301 // other compilers. Therefore, we do not check this property, as it is
3302 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00003303
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003304 // C++ 5.5p2
3305 // [...] to its first operand, which shall be of class T or of a class of
3306 // which T is an unambiguous and accessible base class. [p3: a pointer to
3307 // such a class]
Richard Trieudd225092011-09-15 21:56:47 +00003308 QualType LHSType = LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003309 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003310 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
3311 LHSType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003312 else {
3313 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieudd225092011-09-15 21:56:47 +00003314 << OpSpelling << 1 << LHSType
Douglas Gregor849b2432010-03-31 17:46:05 +00003315 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003316 return QualType();
3317 }
3318 }
3319
Richard Trieudd225092011-09-15 21:56:47 +00003320 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00003321 // If we want to check the hierarchy, we need a complete type.
Richard Trieudd225092011-09-15 21:56:47 +00003322 if (RequireCompleteType(Loc, LHSType, PDiag(diag::err_bad_memptr_lhs)
Sebastian Redl17e1d352010-04-23 17:18:26 +00003323 << OpSpelling << (int)isIndirect)) {
3324 return QualType();
3325 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003326 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00003327 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00003328 // FIXME: Would it be useful to print full ambiguity paths, or is that
3329 // overkill?
Richard Trieudd225092011-09-15 21:56:47 +00003330 if (!IsDerivedFrom(LHSType, Class, Paths) ||
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003331 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3332 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieudd225092011-09-15 21:56:47 +00003333 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003334 return QualType();
3335 }
Eli Friedman3005efe2010-01-16 00:00:48 +00003336 // Cast LHS to type of use.
3337 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00003338 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00003339
John McCallf871d0c2010-08-07 06:22:56 +00003340 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003341 BuildBasePathArray(Paths, BasePath);
Richard Trieudd225092011-09-15 21:56:47 +00003342 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
3343 &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003344 }
3345
Richard Trieudd225092011-09-15 21:56:47 +00003346 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00003347 // Diagnose use of pointer-to-member type which when used as
3348 // the functional cast in a pointer-to-member expression.
3349 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3350 return QualType();
3351 }
John McCallf89e55a2010-11-18 06:31:45 +00003352
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003353 // C++ 5.5p2
3354 // The result is an object or a function of the type specified by the
3355 // second operand.
3356 // The cv qualifiers are the union of those in the pointer and the left side,
3357 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003358 QualType Result = MemPtr->getPointeeType();
Richard Trieudd225092011-09-15 21:56:47 +00003359 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00003360
Douglas Gregor6b4df912011-01-26 16:40:18 +00003361 // C++0x [expr.mptr.oper]p6:
3362 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003363 // ill-formed if the second operand is a pointer to member function with
3364 // ref-qualifier &. In a ->* expression or in a .* expression whose object
3365 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor6b4df912011-01-26 16:40:18 +00003366 // is a pointer to member function with ref-qualifier &&.
3367 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3368 switch (Proto->getRefQualifier()) {
3369 case RQ_None:
3370 // Do nothing
3371 break;
3372
3373 case RQ_LValue:
Richard Trieudd225092011-09-15 21:56:47 +00003374 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003375 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003376 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003377 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003378
Douglas Gregor6b4df912011-01-26 16:40:18 +00003379 case RQ_RValue:
Richard Trieudd225092011-09-15 21:56:47 +00003380 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003381 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003382 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003383 break;
3384 }
3385 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003386
John McCallf89e55a2010-11-18 06:31:45 +00003387 // C++ [expr.mptr.oper]p6:
3388 // The result of a .* expression whose second operand is a pointer
3389 // to a data member is of the same value category as its
3390 // first operand. The result of a .* expression whose second
3391 // operand is a pointer to a member function is a prvalue. The
3392 // result of an ->* expression is an lvalue if its second operand
3393 // is a pointer to data member and a prvalue otherwise.
John McCall864c0412011-04-26 20:42:42 +00003394 if (Result->isFunctionType()) {
John McCallf89e55a2010-11-18 06:31:45 +00003395 VK = VK_RValue;
John McCall864c0412011-04-26 20:42:42 +00003396 return Context.BoundMemberTy;
3397 } else if (isIndirect) {
John McCallf89e55a2010-11-18 06:31:45 +00003398 VK = VK_LValue;
John McCall864c0412011-04-26 20:42:42 +00003399 } else {
Richard Trieudd225092011-09-15 21:56:47 +00003400 VK = LHS.get()->getValueKind();
John McCall864c0412011-04-26 20:42:42 +00003401 }
John McCallf89e55a2010-11-18 06:31:45 +00003402
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003403 return Result;
3404}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003405
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003406/// \brief Try to convert a type to another according to C++0x 5.16p3.
3407///
3408/// This is part of the parameter validation for the ? operator. If either
3409/// value operand is a class type, the two operands are attempted to be
3410/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003411/// It returns true if the program is ill-formed and has already been diagnosed
3412/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003413static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3414 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00003415 bool &HaveConversion,
3416 QualType &ToType) {
3417 HaveConversion = false;
3418 ToType = To->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003419
3420 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003421 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003422 // C++0x 5.16p3
3423 // The process for determining whether an operand expression E1 of type T1
3424 // can be converted to match an operand expression E2 of type T2 is defined
3425 // as follows:
3426 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00003427 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003428 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003429 // E1 can be converted to match E2 if E1 can be implicitly converted to
3430 // type "lvalue reference to T2", subject to the constraint that in the
3431 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003432 QualType T = Self.Context.getLValueReferenceType(ToType);
3433 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003434
Douglas Gregorb70cf442010-03-26 20:14:36 +00003435 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3436 if (InitSeq.isDirectReferenceBinding()) {
3437 ToType = T;
3438 HaveConversion = true;
3439 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003440 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003441
Douglas Gregorb70cf442010-03-26 20:14:36 +00003442 if (InitSeq.isAmbiguous())
3443 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003444 }
John McCallb1bdc622010-02-25 01:37:24 +00003445
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003446 // -- If E2 is an rvalue, or if the conversion above cannot be done:
3447 // -- if E1 and E2 have class type, and the underlying class types are
3448 // the same or one is a base class of the other:
3449 QualType FTy = From->getType();
3450 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003451 const RecordType *FRec = FTy->getAs<RecordType>();
3452 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003453 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003454 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003455 if (FRec && TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003456 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003457 // E1 can be converted to match E2 if the class of T2 is the
3458 // same type as, or a base class of, the class of T1, and
3459 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00003460 if (FRec == TRec || FDerivedFromT) {
3461 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003462 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3463 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003464 if (InitSeq) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003465 HaveConversion = true;
3466 return false;
3467 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003468
Douglas Gregorb70cf442010-03-26 20:14:36 +00003469 if (InitSeq.isAmbiguous())
3470 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003471 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003472 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003473
Douglas Gregorb70cf442010-03-26 20:14:36 +00003474 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003475 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003476
Douglas Gregorb70cf442010-03-26 20:14:36 +00003477 // -- Otherwise: E1 can be converted to match E2 if E1 can be
3478 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003479 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003480 // an rvalue).
3481 //
3482 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3483 // to the array-to-pointer or function-to-pointer conversions.
3484 if (!TTy->getAs<TagType>())
3485 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003486
Douglas Gregorb70cf442010-03-26 20:14:36 +00003487 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3488 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003489 HaveConversion = !InitSeq.Failed();
Douglas Gregorb70cf442010-03-26 20:14:36 +00003490 ToType = TTy;
3491 if (InitSeq.isAmbiguous())
3492 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3493
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003494 return false;
3495}
3496
3497/// \brief Try to find a common type for two according to C++0x 5.16p5.
3498///
3499/// This is part of the parameter validation for the ? operator. If either
3500/// value operand is a class type, overload resolution is used to find a
3501/// conversion to a common type.
John Wiegley429bb272011-04-08 18:41:53 +00003502static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth82214a82011-02-18 23:54:50 +00003503 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00003504 Expr *Args[2] = { LHS.get(), RHS.get() };
Chandler Carruth82214a82011-02-18 23:54:50 +00003505 OverloadCandidateSet CandidateSet(QuestionLoc);
3506 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3507 CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003508
3509 OverloadCandidateSet::iterator Best;
Chandler Carruth82214a82011-02-18 23:54:50 +00003510 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley429bb272011-04-08 18:41:53 +00003511 case OR_Success: {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003512 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley429bb272011-04-08 18:41:53 +00003513 ExprResult LHSRes =
3514 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3515 Best->Conversions[0], Sema::AA_Converting);
3516 if (LHSRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003517 break;
John Wiegley429bb272011-04-08 18:41:53 +00003518 LHS = move(LHSRes);
3519
3520 ExprResult RHSRes =
3521 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3522 Best->Conversions[1], Sema::AA_Converting);
3523 if (RHSRes.isInvalid())
3524 break;
3525 RHS = move(RHSRes);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003526 if (Best->Function)
3527 Self.MarkDeclarationReferenced(QuestionLoc, Best->Function);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003528 return false;
John Wiegley429bb272011-04-08 18:41:53 +00003529 }
3530
Douglas Gregor20093b42009-12-09 23:02:17 +00003531 case OR_No_Viable_Function:
Chandler Carruth82214a82011-02-18 23:54:50 +00003532
3533 // Emit a better diagnostic if one of the expressions is a null pointer
3534 // constant and the other is a pointer type. In this case, the user most
3535 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00003536 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00003537 return true;
3538
3539 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003540 << LHS.get()->getType() << RHS.get()->getType()
3541 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003542 return true;
3543
Douglas Gregor20093b42009-12-09 23:02:17 +00003544 case OR_Ambiguous:
Chandler Carruth82214a82011-02-18 23:54:50 +00003545 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley429bb272011-04-08 18:41:53 +00003546 << LHS.get()->getType() << RHS.get()->getType()
3547 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00003548 // FIXME: Print the possible common types by printing the return types of
3549 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003550 break;
3551
Douglas Gregor20093b42009-12-09 23:02:17 +00003552 case OR_Deleted:
David Blaikieb219cfc2011-09-23 05:06:16 +00003553 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003554 }
3555 return true;
3556}
3557
Sebastian Redl76458502009-04-17 16:30:52 +00003558/// \brief Perform an "extended" implicit conversion as returned by
3559/// TryClassUnification.
John Wiegley429bb272011-04-08 18:41:53 +00003560static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003561 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley429bb272011-04-08 18:41:53 +00003562 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003563 SourceLocation());
John Wiegley429bb272011-04-08 18:41:53 +00003564 Expr *Arg = E.take();
3565 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
3566 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00003567 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00003568 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003569
John Wiegley429bb272011-04-08 18:41:53 +00003570 E = Result;
Sebastian Redl76458502009-04-17 16:30:52 +00003571 return false;
3572}
3573
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003574/// \brief Check the operands of ?: under C++ semantics.
3575///
3576/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
3577/// extension. In this case, LHS == Cond. (But they're not aliases.)
John Wiegley429bb272011-04-08 18:41:53 +00003578QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCall56ca35d2011-02-17 10:25:35 +00003579 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003580 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00003581 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
3582 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003583
3584 // C++0x 5.16p1
3585 // The first expression is contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00003586 if (!Cond.get()->isTypeDependent()) {
3587 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
3588 if (CondRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003589 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003590 Cond = move(CondRes);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003591 }
3592
John McCallf89e55a2010-11-18 06:31:45 +00003593 // Assume r-value.
3594 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00003595 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00003596
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003597 // Either of the arguments dependent?
John Wiegley429bb272011-04-08 18:41:53 +00003598 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003599 return Context.DependentTy;
3600
3601 // C++0x 5.16p2
3602 // If either the second or the third operand has type (cv) void, ...
John Wiegley429bb272011-04-08 18:41:53 +00003603 QualType LTy = LHS.get()->getType();
3604 QualType RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003605 bool LVoid = LTy->isVoidType();
3606 bool RVoid = RTy->isVoidType();
3607 if (LVoid || RVoid) {
3608 // ... then the [l2r] conversions are performed on the second and third
3609 // operands ...
John Wiegley429bb272011-04-08 18:41:53 +00003610 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3611 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3612 if (LHS.isInvalid() || RHS.isInvalid())
3613 return QualType();
3614 LTy = LHS.get()->getType();
3615 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003616
3617 // ... and one of the following shall hold:
3618 // -- The second or the third operand (but not both) is a throw-
3619 // expression; the result is of the type of the other and is an rvalue.
John Wiegley429bb272011-04-08 18:41:53 +00003620 bool LThrow = isa<CXXThrowExpr>(LHS.get());
3621 bool RThrow = isa<CXXThrowExpr>(RHS.get());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003622 if (LThrow && !RThrow)
3623 return RTy;
3624 if (RThrow && !LThrow)
3625 return LTy;
3626
3627 // -- Both the second and third operands have type void; the result is of
3628 // type void and is an rvalue.
3629 if (LVoid && RVoid)
3630 return Context.VoidTy;
3631
3632 // Neither holds, error.
3633 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3634 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley429bb272011-04-08 18:41:53 +00003635 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003636 return QualType();
3637 }
3638
3639 // Neither is void.
3640
3641 // C++0x 5.16p3
3642 // Otherwise, if the second and third operand have different types, and
3643 // either has (cv) class type, and attempt is made to convert each of those
3644 // operands to the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003645 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003646 (LTy->isRecordType() || RTy->isRecordType())) {
3647 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3648 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003649 QualType L2RType, R2LType;
3650 bool HaveL2R, HaveR2L;
John Wiegley429bb272011-04-08 18:41:53 +00003651 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003652 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003653 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003654 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003655
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003656 // If both can be converted, [...] the program is ill-formed.
3657 if (HaveL2R && HaveR2L) {
3658 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley429bb272011-04-08 18:41:53 +00003659 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003660 return QualType();
3661 }
3662
3663 // If exactly one conversion is possible, that conversion is applied to
3664 // the chosen operand and the converted operands are used in place of the
3665 // original operands for the remainder of this section.
3666 if (HaveL2R) {
John Wiegley429bb272011-04-08 18:41:53 +00003667 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003668 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003669 LTy = LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003670 } else if (HaveR2L) {
John Wiegley429bb272011-04-08 18:41:53 +00003671 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003672 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003673 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003674 }
3675 }
3676
3677 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00003678 // If the second and third operands are glvalues of the same value
3679 // category and have the same type, the result is of that type and
3680 // value category and it is a bit-field if the second or the third
3681 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00003682 // We only extend this to bitfields, not to the crazy other kinds of
3683 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003684 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00003685 if (Same &&
John Wiegley429bb272011-04-08 18:41:53 +00003686 LHS.get()->isGLValue() &&
3687 LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
3688 LHS.get()->isOrdinaryOrBitFieldObject() &&
3689 RHS.get()->isOrdinaryOrBitFieldObject()) {
3690 VK = LHS.get()->getValueKind();
3691 if (LHS.get()->getObjectKind() == OK_BitField ||
3692 RHS.get()->getObjectKind() == OK_BitField)
John McCall09431682010-11-18 19:01:18 +00003693 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00003694 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00003695 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003696
3697 // C++0x 5.16p5
3698 // Otherwise, the result is an rvalue. If the second and third operands
3699 // do not have the same type, and either has (cv) class type, ...
3700 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3701 // ... overload resolution is used to determine the conversions (if any)
3702 // to be applied to the operands. If the overload resolution fails, the
3703 // program is ill-formed.
3704 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3705 return QualType();
3706 }
3707
3708 // C++0x 5.16p6
3709 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3710 // conversions are performed on the second and third operands.
John Wiegley429bb272011-04-08 18:41:53 +00003711 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3712 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3713 if (LHS.isInvalid() || RHS.isInvalid())
3714 return QualType();
3715 LTy = LHS.get()->getType();
3716 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003717
3718 // After those conversions, one of the following shall hold:
3719 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00003720 // is of that type. If the operands have class type, the result
3721 // is a prvalue temporary of the result type, which is
3722 // copy-initialized from either the second operand or the third
3723 // operand depending on the value of the first operand.
3724 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3725 if (LTy->isRecordType()) {
3726 // The operands have class type. Make a temporary copy.
3727 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003728 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3729 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00003730 LHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00003731 if (LHSCopy.isInvalid())
3732 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003733
3734 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3735 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00003736 RHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00003737 if (RHSCopy.isInvalid())
3738 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003739
John Wiegley429bb272011-04-08 18:41:53 +00003740 LHS = LHSCopy;
3741 RHS = RHSCopy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003742 }
3743
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003744 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003745 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003746
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003747 // Extension: conditional operator involving vector types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003748 if (LTy->isVectorType() || RTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00003749 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003750
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003751 // -- The second and third operands have arithmetic or enumeration type;
3752 // the usual arithmetic conversions are performed to bring them to a
3753 // common type, and the result is of that type.
3754 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3755 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00003756 if (LHS.isInvalid() || RHS.isInvalid())
3757 return QualType();
3758 return LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003759 }
3760
3761 // -- The second and third operands have pointer type, or one has pointer
3762 // type and the other is a null pointer constant; pointer conversions
3763 // and qualification conversions are performed to bring them to their
3764 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00003765 // -- The second and third operands have pointer to member type, or one has
3766 // pointer to member type and the other is a null pointer constant;
3767 // pointer to member conversions and qualification conversions are
3768 // performed to bring them to a common type, whose cv-qualification
3769 // shall match the cv-qualification of either the second or the third
3770 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003771 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003772 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003773 isSFINAEContext()? 0 : &NonStandardCompositeType);
3774 if (!Composite.isNull()) {
3775 if (NonStandardCompositeType)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003776 Diag(QuestionLoc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003777 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3778 << LTy << RTy << Composite
John Wiegley429bb272011-04-08 18:41:53 +00003779 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003780
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003781 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003782 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003783
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003784 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00003785 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3786 if (!Composite.isNull())
3787 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003788
Chandler Carruth7ef93242011-02-19 00:13:59 +00003789 // Check if we are using a null with a non-pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00003790 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth7ef93242011-02-19 00:13:59 +00003791 return QualType();
3792
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003793 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003794 << LHS.get()->getType() << RHS.get()->getType()
3795 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003796 return QualType();
3797}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003798
3799/// \brief Find a merged pointer type and convert the two expressions to it.
3800///
Douglas Gregor20b3e992009-08-24 17:42:35 +00003801/// This finds the composite pointer type (or member pointer type) for @p E1
3802/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3803/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003804/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003805///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003806/// \param Loc The location of the operator requiring these two expressions to
3807/// be converted to the composite pointer type.
3808///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003809/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3810/// a non-standard (but still sane) composite type to which both expressions
3811/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3812/// will be set true.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003813QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003814 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003815 bool *NonStandardCompositeType) {
3816 if (NonStandardCompositeType)
3817 *NonStandardCompositeType = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003818
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003819 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3820 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003821
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00003822 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3823 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00003824 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003825
3826 // C++0x 5.9p2
3827 // Pointer conversions and qualification conversions are performed on
3828 // pointer operands to bring them to their composite pointer type. If
3829 // one operand is a null pointer constant, the composite pointer type is
3830 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00003831 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003832 if (T2->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00003833 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003834 else
John Wiegley429bb272011-04-08 18:41:53 +00003835 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003836 return T2;
3837 }
Douglas Gregorce940492009-09-25 04:25:58 +00003838 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003839 if (T1->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00003840 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003841 else
John Wiegley429bb272011-04-08 18:41:53 +00003842 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003843 return T1;
3844 }
Mike Stump1eb44332009-09-09 15:08:12 +00003845
Douglas Gregor20b3e992009-08-24 17:42:35 +00003846 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003847 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3848 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003849 return QualType();
3850
3851 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3852 // the other has type "pointer to cv2 T" and the composite pointer type is
3853 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3854 // Otherwise, the composite pointer type is a pointer type similar to the
3855 // type of one of the operands, with a cv-qualification signature that is
3856 // the union of the cv-qualification signatures of the operand types.
3857 // In practice, the first part here is redundant; it's subsumed by the second.
3858 // What we do here is, we build the two possible composite types, and try the
3859 // conversions in both directions. If only one works, or if the two composite
3860 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00003861 // FIXME: extended qualifiers?
Chris Lattner5f9e2722011-07-23 10:55:15 +00003862 typedef SmallVector<unsigned, 4> QualifierVector;
Sebastian Redla439e6f2009-11-16 21:03:45 +00003863 QualifierVector QualifierUnion;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003864 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
Sebastian Redla439e6f2009-11-16 21:03:45 +00003865 ContainingClassVector;
3866 ContainingClassVector MemberOfClass;
3867 QualType Composite1 = Context.getCanonicalType(T1),
3868 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003869 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00003870 do {
3871 const PointerType *Ptr1, *Ptr2;
3872 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3873 (Ptr2 = Composite2->getAs<PointerType>())) {
3874 Composite1 = Ptr1->getPointeeType();
3875 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003876
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003877 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003878 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003879 if (NonStandardCompositeType &&
3880 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3881 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003882
Douglas Gregor20b3e992009-08-24 17:42:35 +00003883 QualifierUnion.push_back(
3884 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3885 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3886 continue;
3887 }
Mike Stump1eb44332009-09-09 15:08:12 +00003888
Douglas Gregor20b3e992009-08-24 17:42:35 +00003889 const MemberPointerType *MemPtr1, *MemPtr2;
3890 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3891 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3892 Composite1 = MemPtr1->getPointeeType();
3893 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003894
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003895 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003896 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003897 if (NonStandardCompositeType &&
3898 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3899 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003900
Douglas Gregor20b3e992009-08-24 17:42:35 +00003901 QualifierUnion.push_back(
3902 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3903 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3904 MemPtr2->getClass()));
3905 continue;
3906 }
Mike Stump1eb44332009-09-09 15:08:12 +00003907
Douglas Gregor20b3e992009-08-24 17:42:35 +00003908 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00003909
Douglas Gregor20b3e992009-08-24 17:42:35 +00003910 // Cannot unwrap any more types.
3911 break;
3912 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00003913
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003914 if (NeedConstBefore && NonStandardCompositeType) {
3915 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003916 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003917 // requirements of C++ [conv.qual]p4 bullet 3.
3918 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3919 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3920 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3921 *NonStandardCompositeType = true;
3922 }
3923 }
3924 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003925
Douglas Gregor20b3e992009-08-24 17:42:35 +00003926 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003927 ContainingClassVector::reverse_iterator MOC
3928 = MemberOfClass.rbegin();
3929 for (QualifierVector::reverse_iterator
3930 I = QualifierUnion.rbegin(),
3931 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00003932 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00003933 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003934 if (MOC->first && MOC->second) {
3935 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00003936 Composite1 = Context.getMemberPointerType(
3937 Context.getQualifiedType(Composite1, Quals),
3938 MOC->first);
3939 Composite2 = Context.getMemberPointerType(
3940 Context.getQualifiedType(Composite2, Quals),
3941 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003942 } else {
3943 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00003944 Composite1
3945 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3946 Composite2
3947 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00003948 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003949 }
3950
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003951 // Try to convert to the first composite pointer type.
3952 InitializedEntity Entity1
3953 = InitializedEntity::InitializeTemporary(Composite1);
3954 InitializationKind Kind
3955 = InitializationKind::CreateCopy(Loc, SourceLocation());
3956 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3957 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00003958
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003959 if (E1ToC1 && E2ToC1) {
3960 // Conversion to Composite1 is viable.
3961 if (!Context.hasSameType(Composite1, Composite2)) {
3962 // Composite2 is a different type from Composite1. Check whether
3963 // Composite2 is also viable.
3964 InitializedEntity Entity2
3965 = InitializedEntity::InitializeTemporary(Composite2);
3966 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3967 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3968 if (E1ToC2 && E2ToC2) {
3969 // Both Composite1 and Composite2 are viable and are different;
3970 // this is an ambiguity.
3971 return QualType();
3972 }
3973 }
3974
3975 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003976 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00003977 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003978 if (E1Result.isInvalid())
3979 return QualType();
3980 E1 = E1Result.takeAs<Expr>();
3981
3982 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003983 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00003984 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003985 if (E2Result.isInvalid())
3986 return QualType();
3987 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003988
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003989 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003990 }
3991
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003992 // Check whether Composite2 is viable.
3993 InitializedEntity Entity2
3994 = InitializedEntity::InitializeTemporary(Composite2);
3995 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3996 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3997 if (!E1ToC2 || !E2ToC2)
3998 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003999
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004000 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004001 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004002 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004003 if (E1Result.isInvalid())
4004 return QualType();
4005 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004006
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004007 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004008 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004009 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004010 if (E2Result.isInvalid())
4011 return QualType();
4012 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004013
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004014 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004015}
Anders Carlsson165a0a02009-05-17 18:41:29 +00004016
John McCall60d7b3a2010-08-24 06:29:42 +00004017ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00004018 if (!E)
4019 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004020
John McCallf85e1932011-06-15 23:02:42 +00004021 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4022
4023 // If the result is a glvalue, we shouldn't bind it.
4024 if (!E->isRValue())
Anders Carlsson089c2602009-08-15 23:41:35 +00004025 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004026
John McCallf85e1932011-06-15 23:02:42 +00004027 // In ARC, calls that return a retainable type can return retained,
4028 // in which case we have to insert a consuming cast.
4029 if (getLangOptions().ObjCAutoRefCount &&
4030 E->getType()->isObjCRetainableType()) {
4031
4032 bool ReturnsRetained;
4033
4034 // For actual calls, we compute this by examining the type of the
4035 // called value.
4036 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4037 Expr *Callee = Call->getCallee()->IgnoreParens();
4038 QualType T = Callee->getType();
4039
4040 if (T == Context.BoundMemberTy) {
4041 // Handle pointer-to-members.
4042 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4043 T = BinOp->getRHS()->getType();
4044 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4045 T = Mem->getMemberDecl()->getType();
4046 }
4047
4048 if (const PointerType *Ptr = T->getAs<PointerType>())
4049 T = Ptr->getPointeeType();
4050 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4051 T = Ptr->getPointeeType();
4052 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4053 T = MemPtr->getPointeeType();
4054
4055 const FunctionType *FTy = T->getAs<FunctionType>();
4056 assert(FTy && "call to value not of function type?");
4057 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4058
4059 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4060 // type always produce a +1 object.
4061 } else if (isa<StmtExpr>(E)) {
4062 ReturnsRetained = true;
4063
4064 // For message sends and property references, we try to find an
4065 // actual method. FIXME: we should infer retention by selector in
4066 // cases where we don't have an actual method.
4067 } else {
John McCallfc4b1912011-08-03 07:02:44 +00004068 ObjCMethodDecl *D = 0;
John McCallf85e1932011-06-15 23:02:42 +00004069 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4070 D = Send->getMethodDecl();
4071 } else {
4072 CastExpr *CE = cast<CastExpr>(E);
John McCallf85e1932011-06-15 23:02:42 +00004073 assert(CE->getCastKind() == CK_GetObjCProperty);
4074 const ObjCPropertyRefExpr *PRE = CE->getSubExpr()->getObjCProperty();
4075 D = (PRE->isImplicitProperty() ? PRE->getImplicitPropertyGetter() : 0);
4076 }
4077
4078 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCallfc4b1912011-08-03 07:02:44 +00004079
4080 // Don't do reclaims on performSelector calls; despite their
4081 // return type, the invoked method doesn't necessarily actually
4082 // return an object.
4083 if (!ReturnsRetained &&
4084 D && D->getMethodFamily() == OMF_performSelector)
4085 return Owned(E);
John McCallf85e1932011-06-15 23:02:42 +00004086 }
4087
John McCall7e5e5f42011-07-07 06:58:02 +00004088 ExprNeedsCleanups = true;
4089
John McCall33e56f32011-09-10 06:18:15 +00004090 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4091 : CK_ARCReclaimReturnedObject);
John McCall7e5e5f42011-07-07 06:58:02 +00004092 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4093 VK_RValue));
John McCallf85e1932011-06-15 23:02:42 +00004094 }
4095
4096 if (!getLangOptions().CPlusPlus)
4097 return Owned(E);
Douglas Gregor51326552009-12-24 18:51:59 +00004098
Ted Kremenek6217b802009-07-29 21:53:49 +00004099 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00004100 if (!RT)
4101 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004102
John McCall86ff3082010-02-04 22:26:26 +00004103 // That should be enough to guarantee that this type is complete.
4104 // If it has a trivial destructor, we can avoid the extra copy.
Jeffrey Yasskinb7ee2e52011-01-27 19:17:54 +00004105 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall507384f2010-08-12 02:40:37 +00004106 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00004107 return Owned(E);
4108
John McCallf85e1932011-06-15 23:02:42 +00004109 CXXDestructorDecl *Destructor = LookupDestructor(RD);
4110
4111 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
4112 if (Destructor) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00004113 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00004114 CheckDestructorAccess(E->getExprLoc(), Destructor,
4115 PDiag(diag::err_access_dtor_temp)
4116 << E->getType());
John McCallf85e1932011-06-15 23:02:42 +00004117
4118 ExprTemporaries.push_back(Temp);
4119 ExprNeedsCleanups = true;
John McCallc91cc662010-04-07 00:41:46 +00004120 }
Anders Carlssondef11992009-05-30 20:36:53 +00004121 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
4122}
4123
John McCall4765fa02010-12-06 08:20:24 +00004124Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00004125 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00004126
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00004127 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
4128 assert(ExprTemporaries.size() >= FirstTemporary);
John McCallf85e1932011-06-15 23:02:42 +00004129 assert(ExprNeedsCleanups || ExprTemporaries.size() == FirstTemporary);
4130 if (!ExprNeedsCleanups)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00004131 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00004132
John McCall4765fa02010-12-06 08:20:24 +00004133 Expr *E = ExprWithCleanups::Create(Context, SubExpr,
John McCallf85e1932011-06-15 23:02:42 +00004134 ExprTemporaries.begin() + FirstTemporary,
John McCall4765fa02010-12-06 08:20:24 +00004135 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00004136 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
4137 ExprTemporaries.end());
John McCallf85e1932011-06-15 23:02:42 +00004138 ExprNeedsCleanups = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004139
Anders Carlsson99ba36d2009-06-05 15:38:08 +00004140 return E;
4141}
4142
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004143ExprResult
John McCall4765fa02010-12-06 08:20:24 +00004144Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004145 if (SubExpr.isInvalid())
4146 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004147
John McCall4765fa02010-12-06 08:20:24 +00004148 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00004149}
4150
John McCall4765fa02010-12-06 08:20:24 +00004151Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004152 assert(SubStmt && "sub statement can't be null!");
4153
John McCallf85e1932011-06-15 23:02:42 +00004154 if (!ExprNeedsCleanups)
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004155 return SubStmt;
4156
4157 // FIXME: In order to attach the temporaries, wrap the statement into
4158 // a StmtExpr; currently this is only used for asm statements.
4159 // This is hacky, either create a new CXXStmtWithTemporaries statement or
4160 // a new AsmStmtWithTemporaries.
4161 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
4162 SourceLocation(),
4163 SourceLocation());
4164 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
4165 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00004166 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004167}
4168
John McCall60d7b3a2010-08-24 06:29:42 +00004169ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004170Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00004171 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00004172 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004173 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004174 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004175 if (Result.isInvalid()) return ExprError();
4176 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004177
John McCall9ae2f072010-08-23 23:25:46 +00004178 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004179 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004180 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00004181 // If we have a pointer to a dependent type and are using the -> operator,
4182 // the object type is the type that the pointer points to. We might still
4183 // have enough information about that type to do something useful.
4184 if (OpKind == tok::arrow)
4185 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4186 BaseType = Ptr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004187
John McCallb3d87482010-08-24 05:47:05 +00004188 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00004189 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004190 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004191 }
Mike Stump1eb44332009-09-09 15:08:12 +00004192
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004193 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00004194 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004195 // returned, with the original second operand.
4196 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00004197 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00004198 llvm::SmallPtrSet<CanQualType,8> CTypes;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004199 SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00004200 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004201
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004202 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00004203 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
4204 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004205 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00004206 Base = Result.get();
4207 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00004208 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00004209 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00004210 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00004211 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004212 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00004213 for (unsigned i = 0; i < Locations.size(); i++)
4214 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004215 return ExprError();
4216 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004217 }
Mike Stump1eb44332009-09-09 15:08:12 +00004218
Douglas Gregor31658df2009-11-20 19:58:21 +00004219 if (BaseType->isPointerType())
4220 BaseType = BaseType->getPointeeType();
4221 }
Mike Stump1eb44332009-09-09 15:08:12 +00004222
4223 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004224 // vector types or Objective-C interfaces. Just return early and let
4225 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00004226 if (!BaseType->isRecordType()) {
4227 // C++ [basic.lookup.classref]p2:
4228 // [...] If the type of the object expression is of pointer to scalar
4229 // type, the unqualified-id is looked up in the context of the complete
4230 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00004231 //
4232 // This also indicates that we should be parsing a
4233 // pseudo-destructor-name.
John McCallb3d87482010-08-24 05:47:05 +00004234 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004235 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004236 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00004237 }
Mike Stump1eb44332009-09-09 15:08:12 +00004238
Douglas Gregor03c57052009-11-17 05:17:33 +00004239 // The object type must be complete (or dependent).
4240 if (!BaseType->isDependentType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004241 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor03c57052009-11-17 05:17:33 +00004242 PDiag(diag::err_incomplete_member_access)))
4243 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004244
Douglas Gregorc68afe22009-09-03 21:38:09 +00004245 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004246 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00004247 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00004248 // type C (or of pointer to a class type C), the unqualified-id is looked
4249 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00004250 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00004251 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004252}
4253
John McCall60d7b3a2010-08-24 06:29:42 +00004254ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00004255 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00004256 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00004257 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
4258 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00004259 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004260
Douglas Gregor77549082010-02-24 21:29:12 +00004261 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00004262 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00004263 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00004264 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00004265 /*RPLoc*/ ExpectedLParenLoc);
4266}
Douglas Gregord4dca082010-02-24 18:44:31 +00004267
John McCall60d7b3a2010-08-24 06:29:42 +00004268ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004269 SourceLocation OpLoc,
4270 tok::TokenKind OpKind,
4271 const CXXScopeSpec &SS,
4272 TypeSourceInfo *ScopeTypeInfo,
4273 SourceLocation CCLoc,
4274 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004275 PseudoDestructorTypeStorage Destructed,
John McCall2d9f5fa2011-02-25 05:21:17 +00004276 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004277 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004278
Douglas Gregorb57fb492010-02-24 22:38:50 +00004279 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004280 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregorb57fb492010-02-24 22:38:50 +00004281 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004282 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00004283 QualType ObjectType = Base->getType();
Douglas Gregorb57fb492010-02-24 22:38:50 +00004284 if (OpKind == tok::arrow) {
4285 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4286 ObjectType = Ptr->getPointeeType();
John McCall9ae2f072010-08-23 23:25:46 +00004287 } else if (!Base->isTypeDependent()) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004288 // The user wrote "p->" when she probably meant "p."; fix it.
4289 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4290 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00004291 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00004292 if (isSFINAEContext())
4293 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004294
Douglas Gregorb57fb492010-02-24 22:38:50 +00004295 OpKind = tok::period;
4296 }
4297 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004298
Douglas Gregorb57fb492010-02-24 22:38:50 +00004299 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
4300 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCall9ae2f072010-08-23 23:25:46 +00004301 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00004302 return ExprError();
4303 }
4304
4305 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004306 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb57fb492010-02-24 22:38:50 +00004307 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004308 if (DestructedTypeInfo) {
4309 QualType DestructedType = DestructedTypeInfo->getType();
4310 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004311 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCallf85e1932011-06-15 23:02:42 +00004312 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
4313 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
4314 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
4315 << ObjectType << DestructedType << Base->getSourceRange()
4316 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004317
John McCallf85e1932011-06-15 23:02:42 +00004318 // Recover by setting the destructed type to the object type.
4319 DestructedType = ObjectType;
4320 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004321 DestructedTypeStart);
John McCallf85e1932011-06-15 23:02:42 +00004322 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4323 } else if (DestructedType.getObjCLifetime() !=
4324 ObjectType.getObjCLifetime()) {
4325
4326 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
4327 // Okay: just pretend that the user provided the correctly-qualified
4328 // type.
4329 } else {
4330 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
4331 << ObjectType << DestructedType << Base->getSourceRange()
4332 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4333 }
4334
4335 // Recover by setting the destructed type to the object type.
4336 DestructedType = ObjectType;
4337 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4338 DestructedTypeStart);
4339 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4340 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004341 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00004342 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004343
Douglas Gregorb57fb492010-02-24 22:38:50 +00004344 // C++ [expr.pseudo]p2:
4345 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4346 // form
4347 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004348 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb57fb492010-02-24 22:38:50 +00004349 //
4350 // shall designate the same scalar type.
4351 if (ScopeTypeInfo) {
4352 QualType ScopeType = ScopeTypeInfo->getType();
4353 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00004354 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004355
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004356 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00004357 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00004358 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004359 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004360
Douglas Gregorb57fb492010-02-24 22:38:50 +00004361 ScopeType = QualType();
4362 ScopeTypeInfo = 0;
4363 }
4364 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004365
John McCall9ae2f072010-08-23 23:25:46 +00004366 Expr *Result
4367 = new (Context) CXXPseudoDestructorExpr(Context, Base,
4368 OpKind == tok::arrow, OpLoc,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004369 SS.getWithLocInContext(Context),
John McCall9ae2f072010-08-23 23:25:46 +00004370 ScopeTypeInfo,
4371 CCLoc,
4372 TildeLoc,
4373 Destructed);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004374
Douglas Gregorb57fb492010-02-24 22:38:50 +00004375 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00004376 return Owned(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004377
John McCall9ae2f072010-08-23 23:25:46 +00004378 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00004379}
4380
John McCall60d7b3a2010-08-24 06:29:42 +00004381ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004382 SourceLocation OpLoc,
4383 tok::TokenKind OpKind,
4384 CXXScopeSpec &SS,
4385 UnqualifiedId &FirstTypeName,
4386 SourceLocation CCLoc,
4387 SourceLocation TildeLoc,
4388 UnqualifiedId &SecondTypeName,
4389 bool HasTrailingLParen) {
Douglas Gregor77549082010-02-24 21:29:12 +00004390 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4391 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4392 "Invalid first type name in pseudo-destructor");
4393 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4394 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4395 "Invalid second type name in pseudo-destructor");
4396
Douglas Gregor77549082010-02-24 21:29:12 +00004397 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004398 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregor77549082010-02-24 21:29:12 +00004399 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004400 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00004401 QualType ObjectType = Base->getType();
Douglas Gregor77549082010-02-24 21:29:12 +00004402 if (OpKind == tok::arrow) {
4403 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4404 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004405 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00004406 // The user wrote "p->" when she probably meant "p."; fix it.
4407 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004408 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00004409 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00004410 if (isSFINAEContext())
4411 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004412
Douglas Gregor77549082010-02-24 21:29:12 +00004413 OpKind = tok::period;
4414 }
4415 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004416
4417 // Compute the object type that we should use for name lookup purposes. Only
4418 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00004419 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004420 if (!SS.isSet()) {
John McCall2d9f5fa2011-02-25 05:21:17 +00004421 if (ObjectType->isRecordType())
4422 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallb3d87482010-08-24 05:47:05 +00004423 else if (ObjectType->isDependentType())
4424 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004425 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004426
4427 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb57fb492010-02-24 22:38:50 +00004428 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00004429 QualType DestructedType;
4430 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004431 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00004432 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004433 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00004434 SecondTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00004435 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004436 if (!T &&
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004437 ((SS.isSet() && !computeDeclContext(SS, false)) ||
4438 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004439 // The name of the type being destroyed is a dependent name, and we
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004440 // couldn't find anything useful in scope. Just store the identifier and
4441 // it's location, and we'll perform (qualified) name lookup again at
4442 // template instantiation time.
4443 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
4444 SecondTypeName.StartLocation);
4445 } else if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004446 Diag(SecondTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00004447 diag::err_pseudo_dtor_destructor_non_type)
4448 << SecondTypeName.Identifier << ObjectType;
4449 if (isSFINAEContext())
4450 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004451
Douglas Gregor77549082010-02-24 21:29:12 +00004452 // Recover by assuming we had the right type all along.
4453 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004454 } else
Douglas Gregor77549082010-02-24 21:29:12 +00004455 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004456 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004457 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00004458 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004459 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4460 TemplateId->getTemplateArgs(),
4461 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00004462 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4463 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004464 TemplateId->TemplateNameLoc,
4465 TemplateId->LAngleLoc,
4466 TemplateArgsPtr,
4467 TemplateId->RAngleLoc);
4468 if (T.isInvalid() || !T.get()) {
4469 // Recover by assuming we had the right type all along.
4470 DestructedType = ObjectType;
4471 } else
4472 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004473 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004474
4475 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb57fb492010-02-24 22:38:50 +00004476 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004477 if (!DestructedType.isNull()) {
4478 if (!DestructedTypeInfo)
4479 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004480 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004481 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4482 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004483
Douglas Gregorb57fb492010-02-24 22:38:50 +00004484 // Convert the name of the scope type (the type prior to '::') into a type.
4485 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00004486 QualType ScopeType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004487 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor77549082010-02-24 21:29:12 +00004488 FirstTypeName.Identifier) {
4489 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004490 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00004491 FirstTypeName.StartLocation,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004492 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00004493 if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004494 Diag(FirstTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00004495 diag::err_pseudo_dtor_destructor_non_type)
4496 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004497
Douglas Gregorb57fb492010-02-24 22:38:50 +00004498 if (isSFINAEContext())
4499 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004500
Douglas Gregorb57fb492010-02-24 22:38:50 +00004501 // Just drop this type. It's unnecessary anyway.
4502 ScopeType = QualType();
4503 } else
4504 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004505 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004506 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00004507 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004508 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4509 TemplateId->getTemplateArgs(),
4510 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00004511 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4512 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004513 TemplateId->TemplateNameLoc,
4514 TemplateId->LAngleLoc,
4515 TemplateArgsPtr,
4516 TemplateId->RAngleLoc);
4517 if (T.isInvalid() || !T.get()) {
4518 // Recover by dropping this type.
4519 ScopeType = QualType();
4520 } else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004521 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004522 }
4523 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004524
Douglas Gregorb4a418f2010-02-24 23:02:30 +00004525 if (!ScopeType.isNull() && !ScopeTypeInfo)
4526 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
4527 FirstTypeName.StartLocation);
4528
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004529
John McCall9ae2f072010-08-23 23:25:46 +00004530 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00004531 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004532 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00004533}
4534
John Wiegley429bb272011-04-08 18:41:53 +00004535ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004536 CXXMethodDecl *Method,
4537 bool HadMultipleCandidates) {
John Wiegley429bb272011-04-08 18:41:53 +00004538 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
4539 FoundDecl, Method);
4540 if (Exp.isInvalid())
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004541 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00004542
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004543 MemberExpr *ME =
John Wiegley429bb272011-04-08 18:41:53 +00004544 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
John McCallf89e55a2010-11-18 06:31:45 +00004545 SourceLocation(), Method->getType(),
4546 VK_RValue, OK_Ordinary);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004547 if (HadMultipleCandidates)
4548 ME->setHadMultipleCandidates(true);
4549
John McCallf89e55a2010-11-18 06:31:45 +00004550 QualType ResultType = Method->getResultType();
4551 ExprValueKind VK = Expr::getValueKindForType(ResultType);
4552 ResultType = ResultType.getNonLValueExprType(Context);
4553
John Wiegley429bb272011-04-08 18:41:53 +00004554 MarkDeclarationReferenced(Exp.get()->getLocStart(), Method);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004555 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00004556 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
John Wiegley429bb272011-04-08 18:41:53 +00004557 Exp.get()->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00004558 return CE;
4559}
4560
Sebastian Redl2e156222010-09-10 20:55:43 +00004561ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4562 SourceLocation RParen) {
Sebastian Redl2e156222010-09-10 20:55:43 +00004563 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
4564 Operand->CanThrow(Context),
4565 KeyLoc, RParen));
4566}
4567
4568ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
4569 Expr *Operand, SourceLocation RParen) {
4570 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00004571}
4572
John McCallf6a16482010-12-04 03:47:34 +00004573/// Perform the conversions required for an expression used in a
4574/// context that ignores the result.
John Wiegley429bb272011-04-08 18:41:53 +00004575ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCalla878cda2010-12-02 02:07:15 +00004576 // C99 6.3.2.1:
4577 // [Except in specific positions,] an lvalue that does not have
4578 // array type is converted to the value stored in the
4579 // designated object (and is no longer an lvalue).
John McCalle6d134b2011-06-27 21:24:11 +00004580 if (E->isRValue()) {
4581 // In C, function designators (i.e. expressions of function type)
4582 // are r-values, but we still want to do function-to-pointer decay
4583 // on them. This is both technically correct and convenient for
4584 // some clients.
4585 if (!getLangOptions().CPlusPlus && E->getType()->isFunctionType())
4586 return DefaultFunctionArrayConversion(E);
4587
4588 return Owned(E);
4589 }
John McCalla878cda2010-12-02 02:07:15 +00004590
John McCallf6a16482010-12-04 03:47:34 +00004591 // We always want to do this on ObjC property references.
4592 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley429bb272011-04-08 18:41:53 +00004593 ExprResult Res = ConvertPropertyForRValue(E);
4594 if (Res.isInvalid()) return Owned(E);
4595 E = Res.take();
4596 if (E->isRValue()) return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004597 }
4598
4599 // Otherwise, this rule does not apply in C++, at least not for the moment.
John Wiegley429bb272011-04-08 18:41:53 +00004600 if (getLangOptions().CPlusPlus) return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004601
4602 // GCC seems to also exclude expressions of incomplete enum type.
4603 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
4604 if (!T->getDecl()->isComplete()) {
4605 // FIXME: stupid workaround for a codegen bug!
John Wiegley429bb272011-04-08 18:41:53 +00004606 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
4607 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004608 }
4609 }
4610
John Wiegley429bb272011-04-08 18:41:53 +00004611 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
4612 if (Res.isInvalid())
4613 return Owned(E);
4614 E = Res.take();
4615
John McCall85515d62010-12-04 12:29:11 +00004616 if (!E->getType()->isVoidType())
4617 RequireCompleteType(E->getExprLoc(), E->getType(),
4618 diag::err_incomplete_type);
John Wiegley429bb272011-04-08 18:41:53 +00004619 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004620}
4621
John Wiegley429bb272011-04-08 18:41:53 +00004622ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
4623 ExprResult FullExpr = Owned(FE);
4624
4625 if (!FullExpr.get())
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00004626 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00004627
John Wiegley429bb272011-04-08 18:41:53 +00004628 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregord0937222010-12-13 22:49:22 +00004629 return ExprError();
4630
John McCallfb8721c2011-04-10 19:13:55 +00004631 FullExpr = CheckPlaceholderExpr(FullExpr.take());
4632 if (FullExpr.isInvalid())
4633 return ExprError();
Douglas Gregor353ee242011-03-07 02:05:23 +00004634
John Wiegley429bb272011-04-08 18:41:53 +00004635 FullExpr = IgnoredValueConversions(FullExpr.take());
4636 if (FullExpr.isInvalid())
4637 return ExprError();
4638
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004639 CheckImplicitConversions(FullExpr.get(), FullExpr.get()->getExprLoc());
John McCall4765fa02010-12-06 08:20:24 +00004640 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00004641}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004642
4643StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
4644 if (!FullStmt) return StmtError();
4645
John McCall4765fa02010-12-06 08:20:24 +00004646 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004647}
Francois Pichet1e862692011-05-06 20:48:22 +00004648
4649bool Sema::CheckMicrosoftIfExistsSymbol(CXXScopeSpec &SS,
4650 UnqualifiedId &Name) {
4651 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
4652 DeclarationName TargetName = TargetNameInfo.getName();
4653 if (!TargetName)
4654 return false;
4655
4656 // Do the redeclaration lookup in the current scope.
4657 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
4658 Sema::NotForRedeclaration);
4659 R.suppressDiagnostics();
4660 LookupParsedName(R, getCurScope(), &SS);
4661 return !R.empty();
4662}