blob: 867bd3515b6d24e7fa80bc9b3d3dfad0bc85addd [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall2a7fb272010-08-25 05:32:35 +000015#include "clang/Sema/DeclSpec.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/ParsedTemplate.h"
John McCall469a1eb2011-02-02 13:00:07 +000019#include "clang/Sema/ScopeInfo.h"
John McCall2a7fb272010-08-25 05:32:35 +000020#include "clang/Sema/TemplateDeduction.h"
Steve Naroff210679c2007-08-25 14:02:58 +000021#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000024#include "clang/AST/ExprCXX.h"
Fariborz Jahaniand4266622010-06-16 18:56:04 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregorb57fb492010-02-24 22:38:50 +000026#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000027#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000028#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000029#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000030#include "llvm/ADT/STLExtras.h"
Chandler Carruth73e0a912011-05-01 07:23:17 +000031#include "llvm/Support/ErrorHandling.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000033using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000034
John McCallb3d87482010-08-24 05:47:05 +000035ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000036 IdentifierInfo &II,
John McCallb3d87482010-08-24 05:47:05 +000037 SourceLocation NameLoc,
38 Scope *S, CXXScopeSpec &SS,
39 ParsedType ObjectTypePtr,
40 bool EnteringContext) {
Douglas Gregor124b8782010-02-16 19:09:40 +000041 // Determine where to perform name lookup.
42
43 // FIXME: This area of the standard is very messy, and the current
44 // wording is rather unclear about which scopes we search for the
45 // destructor name; see core issues 399 and 555. Issue 399 in
46 // particular shows where the current description of destructor name
47 // lookup is completely out of line with existing practice, e.g.,
48 // this appears to be ill-formed:
49 //
50 // namespace N {
51 // template <typename T> struct S {
52 // ~S();
53 // };
54 // }
55 //
56 // void f(N::S<int>* s) {
57 // s->N::S<int>::~S();
58 // }
59 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000060 // See also PR6358 and PR6359.
Sebastian Redlc0fee502010-07-07 23:17:38 +000061 // For this reason, we're currently only doing the C++03 version of this
62 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregor124b8782010-02-16 19:09:40 +000063 QualType SearchType;
64 DeclContext *LookupCtx = 0;
65 bool isDependent = false;
66 bool LookInScope = false;
67
68 // If we have an object type, it's because we are in a
69 // pseudo-destructor-expression or a member access expression, and
70 // we know what type we're looking for.
71 if (ObjectTypePtr)
72 SearchType = GetTypeFromParser(ObjectTypePtr);
73
74 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000075 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000076
Douglas Gregor93649fd2010-02-23 00:15:22 +000077 bool AlreadySearched = false;
78 bool LookAtPrefix = true;
Sebastian Redlc0fee502010-07-07 23:17:38 +000079 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000080 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redlc0fee502010-07-07 23:17:38 +000081 // the type-names are looked up as types in the scope designated by the
82 // nested-name-specifier. In a qualified-id of the form:
NAKAMURA Takumi00995302011-01-27 07:09:49 +000083 //
84 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redlc0fee502010-07-07 23:17:38 +000085 //
86 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth5e895a82010-02-21 10:19:54 +000087 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +000088 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +000089 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregor124b8782010-02-16 19:09:40 +000090 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000091 // the class-names are looked up as types in the scope designated by
Sebastian Redlc0fee502010-07-07 23:17:38 +000092 // the nested-name-specifier.
Douglas Gregor124b8782010-02-16 19:09:40 +000093 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000094 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000095 // code below is permitted to look at the prefix of the
Sebastian Redlc0fee502010-07-07 23:17:38 +000096 // nested-name-specifier.
97 DeclContext *DC = computeDeclContext(SS, EnteringContext);
98 if (DC && DC->isFileContext()) {
99 AlreadySearched = true;
100 LookupCtx = DC;
101 isDependent = false;
102 } else if (DC && isa<CXXRecordDecl>(DC))
103 LookAtPrefix = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000104
Sebastian Redlc0fee502010-07-07 23:17:38 +0000105 // The second case from the C++03 rules quoted further above.
Douglas Gregor93649fd2010-02-23 00:15:22 +0000106 NestedNameSpecifier *Prefix = 0;
107 if (AlreadySearched) {
108 // Nothing left to do.
109 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
110 CXXScopeSpec PrefixSS;
Douglas Gregor7e384942011-02-25 16:07:42 +0000111 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor93649fd2010-02-23 00:15:22 +0000112 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
113 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000114 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000115 LookupCtx = computeDeclContext(SearchType);
116 isDependent = SearchType->isDependentType();
117 } else {
118 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000119 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000120 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000121
Douglas Gregoredc90502010-02-25 04:46:04 +0000122 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000123 } else if (ObjectTypePtr) {
124 // C++ [basic.lookup.classref]p3:
125 // If the unqualified-id is ~type-name, the type-name is looked up
126 // in the context of the entire postfix-expression. If the type T
127 // of the object expression is of a class type C, the type-name is
128 // also looked up in the scope of class C. At least one of the
129 // lookups shall find a name that refers to (possibly
130 // cv-qualified) T.
131 LookupCtx = computeDeclContext(SearchType);
132 isDependent = SearchType->isDependentType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000133 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregor124b8782010-02-16 19:09:40 +0000134 "Caller should have completed object type");
135
136 LookInScope = true;
137 } else {
138 // Perform lookup into the current scope (only).
139 LookInScope = true;
140 }
141
Douglas Gregor7ec18732011-03-04 22:32:08 +0000142 TypeDecl *NonMatchingTypeDecl = 0;
Douglas Gregor124b8782010-02-16 19:09:40 +0000143 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
144 for (unsigned Step = 0; Step != 2; ++Step) {
145 // Look for the name first in the computed lookup context (if we
Douglas Gregor7ec18732011-03-04 22:32:08 +0000146 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregor124b8782010-02-16 19:09:40 +0000147 // we're allowed to look there).
148 Found.clear();
149 if (Step == 0 && LookupCtx)
150 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000151 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000152 LookupName(Found, S);
153 else
154 continue;
155
156 // FIXME: Should we be suppressing ambiguities here?
157 if (Found.isAmbiguous())
John McCallb3d87482010-08-24 05:47:05 +0000158 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000159
160 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
161 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000162
163 if (SearchType.isNull() || SearchType->isDependentType() ||
164 Context.hasSameUnqualifiedType(T, SearchType)) {
165 // We found our type!
166
John McCallb3d87482010-08-24 05:47:05 +0000167 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000168 }
John Wiegley36784e72011-03-08 08:13:22 +0000169
Douglas Gregor7ec18732011-03-04 22:32:08 +0000170 if (!SearchType.isNull())
171 NonMatchingTypeDecl = Type;
Douglas Gregor124b8782010-02-16 19:09:40 +0000172 }
173
174 // If the name that we found is a class template name, and it is
175 // the same name as the template name in the last part of the
176 // nested-name-specifier (if present) or the object type, then
177 // this is the destructor for that class.
178 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000179 // issue 399, for which there isn't even an obvious direction.
Douglas Gregor124b8782010-02-16 19:09:40 +0000180 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
181 QualType MemberOfType;
182 if (SS.isSet()) {
183 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
184 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000185 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
186 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000187 }
188 }
189 if (MemberOfType.isNull())
190 MemberOfType = SearchType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000191
Douglas Gregor124b8782010-02-16 19:09:40 +0000192 if (MemberOfType.isNull())
193 continue;
194
195 // We're referring into a class template specialization. If the
196 // class template we found is the same as the template being
197 // specialized, we found what we are looking for.
198 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
199 if (ClassTemplateSpecializationDecl *Spec
200 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
201 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
202 Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000203 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000204 }
205
206 continue;
207 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000208
Douglas Gregor124b8782010-02-16 19:09:40 +0000209 // We're referring to an unresolved class template
210 // specialization. Determine whether we class template we found
211 // is the same as the template being specialized or, if we don't
212 // know which template is being specialized, that it at least
213 // has the same name.
214 if (const TemplateSpecializationType *SpecType
215 = MemberOfType->getAs<TemplateSpecializationType>()) {
216 TemplateName SpecName = SpecType->getTemplateName();
217
218 // The class template we found is the same template being
219 // specialized.
220 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
221 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000222 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000223
224 continue;
225 }
226
227 // The class template we found has the same name as the
228 // (dependent) template name being specialized.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000229 if (DependentTemplateName *DepTemplate
Douglas Gregor124b8782010-02-16 19:09:40 +0000230 = SpecName.getAsDependentTemplateName()) {
231 if (DepTemplate->isIdentifier() &&
232 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallb3d87482010-08-24 05:47:05 +0000233 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000234
235 continue;
236 }
237 }
238 }
239 }
240
241 if (isDependent) {
242 // We didn't find our type, but that's okay: it's dependent
243 // anyway.
Douglas Gregore29425b2011-02-28 22:42:13 +0000244
245 // FIXME: What if we have no nested-name-specifier?
246 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
247 SS.getWithLocInContext(Context),
248 II, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000249 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000250 }
251
Douglas Gregor7ec18732011-03-04 22:32:08 +0000252 if (NonMatchingTypeDecl) {
253 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
254 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
255 << T << SearchType;
256 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
257 << T;
258 } else if (ObjectTypePtr)
259 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000260 << &II;
Douglas Gregor124b8782010-02-16 19:09:40 +0000261 else
262 Diag(NameLoc, diag::err_destructor_class_name);
263
John McCallb3d87482010-08-24 05:47:05 +0000264 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000265}
266
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000267/// \brief Build a C++ typeid expression with a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000268ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000269 SourceLocation TypeidLoc,
270 TypeSourceInfo *Operand,
271 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000272 // C++ [expr.typeid]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000273 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000274 // that is the operand of typeid are always ignored.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000275 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000276 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000277 Qualifiers Quals;
278 QualType T
279 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
280 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000281 if (T->getAs<RecordType>() &&
282 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
283 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000284
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000285 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
286 Operand,
287 SourceRange(TypeidLoc, RParenLoc)));
288}
289
290/// \brief Build a C++ typeid expression with an expression operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000291ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000292 SourceLocation TypeidLoc,
293 Expr *E,
294 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000295 bool isUnevaluatedOperand = true;
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000296 if (E && !E->isTypeDependent()) {
297 QualType T = E->getType();
298 if (const RecordType *RecordT = T->getAs<RecordType>()) {
299 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
300 // C++ [expr.typeid]p3:
301 // [...] If the type of the expression is a class type, the class
302 // shall be completely-defined.
303 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
304 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000305
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000306 // C++ [expr.typeid]p3:
Sebastian Redl906082e2010-07-20 04:20:21 +0000307 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000308 // polymorphic class type [...] [the] expression is an unevaluated
309 // operand. [...]
Sebastian Redl906082e2010-07-20 04:20:21 +0000310 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000311 isUnevaluatedOperand = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000312
313 // We require a vtable to query the type at run time.
314 MarkVTableUsed(TypeidLoc, RecordD);
315 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000316 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000317
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000318 // C++ [expr.typeid]p4:
319 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000320 // cv-qualified type, the result of the typeid expression refers to a
321 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000322 // type.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000323 Qualifiers Quals;
324 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
325 if (!Context.hasSameType(T, UnqualT)) {
326 T = UnqualT;
John Wiegley429bb272011-04-08 18:41:53 +0000327 E = ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E)).take();
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000328 }
329 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000330
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000331 // If this is an unevaluated operand, clear out the set of
332 // declaration references we have been computing and eliminate any
333 // temporaries introduced in its computation.
334 if (isUnevaluatedOperand)
335 ExprEvalContexts.back().Context = Unevaluated;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000336
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000337 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCall9ae2f072010-08-23 23:25:46 +0000338 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000339 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000340}
341
342/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCall60d7b3a2010-08-24 06:29:42 +0000343ExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000344Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
345 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000346 // Find the std::type_info type.
Sebastian Redlce0682f2011-03-31 19:29:24 +0000347 if (!getStdNamespace())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000348 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000349
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000350 if (!CXXTypeInfoDecl) {
351 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
352 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
353 LookupQualifiedName(R, getStdNamespace());
354 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
355 if (!CXXTypeInfoDecl)
356 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
357 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000358
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000359 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000360
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000361 if (isType) {
362 // The operand is a type; handle it as such.
363 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +0000364 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
365 &TInfo);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000366 if (T.isNull())
367 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000368
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000369 if (!TInfo)
370 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000371
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000372 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000373 }
Mike Stump1eb44332009-09-09 15:08:12 +0000374
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000375 // The operand is an expression.
John McCall9ae2f072010-08-23 23:25:46 +0000376 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000377}
378
Francois Pichet6915c522010-12-27 01:32:00 +0000379/// Retrieve the UuidAttr associated with QT.
380static UuidAttr *GetUuidAttrOfType(QualType QT) {
381 // Optionally remove one level of pointer, reference or array indirection.
John McCallf4c73712011-01-19 06:33:43 +0000382 const Type *Ty = QT.getTypePtr();;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000383 if (QT->isPointerType() || QT->isReferenceType())
384 Ty = QT->getPointeeType().getTypePtr();
385 else if (QT->isArrayType())
386 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
387
Francois Pichet8db75a22011-05-08 10:02:20 +0000388 // Loop all record redeclaration looking for an uuid attribute.
Francois Pichet6915c522010-12-27 01:32:00 +0000389 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Francois Pichet8db75a22011-05-08 10:02:20 +0000390 for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(),
391 E = RD->redecls_end(); I != E; ++I) {
392 if (UuidAttr *Uuid = I->getAttr<UuidAttr>())
Francois Pichet6915c522010-12-27 01:32:00 +0000393 return Uuid;
Francois Pichet6915c522010-12-27 01:32:00 +0000394 }
Francois Pichet8db75a22011-05-08 10:02:20 +0000395
Francois Pichet6915c522010-12-27 01:32:00 +0000396 return 0;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000397}
398
Francois Pichet01b7c302010-09-08 12:20:18 +0000399/// \brief Build a Microsoft __uuidof expression with a type operand.
400ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
401 SourceLocation TypeidLoc,
402 TypeSourceInfo *Operand,
403 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000404 if (!Operand->getType()->isDependentType()) {
405 if (!GetUuidAttrOfType(Operand->getType()))
406 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
407 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000408
Francois Pichet01b7c302010-09-08 12:20:18 +0000409 // FIXME: add __uuidof semantic analysis for type operand.
410 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
411 Operand,
412 SourceRange(TypeidLoc, RParenLoc)));
413}
414
415/// \brief Build a Microsoft __uuidof expression with an expression operand.
416ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
417 SourceLocation TypeidLoc,
418 Expr *E,
419 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000420 if (!E->getType()->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000421 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichet6915c522010-12-27 01:32:00 +0000422 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
423 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
424 }
425 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet01b7c302010-09-08 12:20:18 +0000426 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
427 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000428 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet01b7c302010-09-08 12:20:18 +0000429}
430
431/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
432ExprResult
433Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
434 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000435 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet01b7c302010-09-08 12:20:18 +0000436 if (!MSVCGuidDecl) {
437 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
438 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
439 LookupQualifiedName(R, Context.getTranslationUnitDecl());
440 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
441 if (!MSVCGuidDecl)
442 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000443 }
444
Francois Pichet01b7c302010-09-08 12:20:18 +0000445 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000446
Francois Pichet01b7c302010-09-08 12:20:18 +0000447 if (isType) {
448 // The operand is a type; handle it as such.
449 TypeSourceInfo *TInfo = 0;
450 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
451 &TInfo);
452 if (T.isNull())
453 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000454
Francois Pichet01b7c302010-09-08 12:20:18 +0000455 if (!TInfo)
456 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
457
458 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
459 }
460
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000461 // The operand is an expression.
Francois Pichet01b7c302010-09-08 12:20:18 +0000462 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
463}
464
Steve Naroff1b273c42007-09-16 14:56:35 +0000465/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCall60d7b3a2010-08-24 06:29:42 +0000466ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000467Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000468 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000469 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000470 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
471 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000472}
Chris Lattner50dd2892008-02-26 00:51:44 +0000473
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000474/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCall60d7b3a2010-08-24 06:29:42 +0000475ExprResult
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000476Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
477 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
478}
479
Chris Lattner50dd2892008-02-26 00:51:44 +0000480/// ActOnCXXThrow - Parse throw expressions.
John McCall60d7b3a2010-08-24 06:29:42 +0000481ExprResult
John McCall9ae2f072010-08-23 23:25:46 +0000482Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
Anders Carlsson729b8532011-02-23 03:46:46 +0000483 // Don't report an error if 'throw' is used in system headers.
Anders Carlsson15348ae2011-02-28 02:27:16 +0000484 if (!getLangOptions().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +0000485 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb1fba312011-02-19 21:53:09 +0000486 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Anders Carlsson7f11d9c2011-02-19 19:26:44 +0000487
John Wiegley429bb272011-04-08 18:41:53 +0000488 if (Ex && !Ex->isTypeDependent()) {
489 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex);
490 if (ExRes.isInvalid())
491 return ExprError();
492 Ex = ExRes.take();
493 }
Sebastian Redl972041f2009-04-27 20:27:31 +0000494 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
495}
496
497/// CheckCXXThrowOperand - Validate the operand of a throw.
John Wiegley429bb272011-04-08 18:41:53 +0000498ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000499 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000500 // A throw-expression initializes a temporary object, called the exception
501 // object, the type of which is determined by removing any top-level
502 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000503 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor154fe982009-12-23 22:04:40 +0000504 // or "pointer to function returning T", [...]
505 if (E->getType().hasQualifiers())
John Wiegley429bb272011-04-08 18:41:53 +0000506 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
507 CastCategory(E)).take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000508
John Wiegley429bb272011-04-08 18:41:53 +0000509 ExprResult Res = DefaultFunctionArrayConversion(E);
510 if (Res.isInvalid())
511 return ExprError();
512 E = Res.take();
Sebastian Redl972041f2009-04-27 20:27:31 +0000513
514 // If the type of the exception would be an incomplete type or a pointer
515 // to an incomplete type other than (cv) void the program is ill-formed.
516 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000517 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000518 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000519 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000520 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000521 }
522 if (!isPointer || !Ty->isVoidType()) {
523 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000524 PDiag(isPointer ? diag::err_throw_incomplete_ptr
525 : diag::err_throw_incomplete)
526 << E->getSourceRange()))
John Wiegley429bb272011-04-08 18:41:53 +0000527 return ExprError();
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000528
Douglas Gregorbf422f92010-04-15 18:05:39 +0000529 if (RequireNonAbstractType(ThrowLoc, E->getType(),
530 PDiag(diag::err_throw_abstract_type)
531 << E->getSourceRange()))
John Wiegley429bb272011-04-08 18:41:53 +0000532 return ExprError();
Sebastian Redl972041f2009-04-27 20:27:31 +0000533 }
534
John McCallac418162010-04-22 01:10:34 +0000535 // Initialize the exception result. This implicitly weeds out
536 // abstract types or types with inaccessible copy constructors.
Douglas Gregor72dfa272011-01-21 22:46:35 +0000537 const VarDecl *NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
538
Douglas Gregorf5d8f462011-01-21 18:05:27 +0000539 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p32.
John McCallac418162010-04-22 01:10:34 +0000540 InitializedEntity Entity =
Douglas Gregor72dfa272011-01-21 22:46:35 +0000541 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
542 /*NRVO=*/false);
John Wiegley429bb272011-04-08 18:41:53 +0000543 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
544 QualType(), E);
John McCallac418162010-04-22 01:10:34 +0000545 if (Res.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000546 return ExprError();
547 E = Res.take();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000548
Eli Friedman5ed9b932010-06-03 20:39:03 +0000549 // If the exception has class type, we need additional handling.
550 const RecordType *RecordTy = Ty->getAs<RecordType>();
551 if (!RecordTy)
John Wiegley429bb272011-04-08 18:41:53 +0000552 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000553 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
554
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000555 // If we are throwing a polymorphic class type or pointer thereof,
556 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000557 MarkVTableUsed(ThrowLoc, RD);
558
Eli Friedman98efb9f2010-10-12 20:32:36 +0000559 // If a pointer is thrown, the referenced object will not be destroyed.
560 if (isPointer)
John Wiegley429bb272011-04-08 18:41:53 +0000561 return Owned(E);
Eli Friedman98efb9f2010-10-12 20:32:36 +0000562
Eli Friedman5ed9b932010-06-03 20:39:03 +0000563 // If the class has a non-trivial destructor, we must be able to call it.
564 if (RD->hasTrivialDestructor())
John Wiegley429bb272011-04-08 18:41:53 +0000565 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000566
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000567 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +0000568 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman5ed9b932010-06-03 20:39:03 +0000569 if (!Destructor)
John Wiegley429bb272011-04-08 18:41:53 +0000570 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000571
572 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
573 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000574 PDiag(diag::err_access_dtor_exception) << Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000575 return Owned(E);
Chris Lattner50dd2892008-02-26 00:51:44 +0000576}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000577
John McCall5808ce42011-02-03 08:15:49 +0000578CXXMethodDecl *Sema::tryCaptureCXXThis() {
579 // Ignore block scopes: we can capture through them.
580 // Ignore nested enum scopes: we'll diagnose non-constant expressions
581 // where they're invalid, and other uses are legitimate.
582 // Don't ignore nested class scopes: you can't use 'this' in a local class.
John McCall469a1eb2011-02-02 13:00:07 +0000583 DeclContext *DC = CurContext;
John McCall5808ce42011-02-03 08:15:49 +0000584 while (true) {
585 if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
586 else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
587 else break;
588 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000589
John McCall5808ce42011-02-03 08:15:49 +0000590 // If we're not in an instance method, error out.
John McCall469a1eb2011-02-02 13:00:07 +0000591 CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC);
592 if (!method || !method->isInstance())
John McCall5808ce42011-02-03 08:15:49 +0000593 return 0;
John McCall469a1eb2011-02-02 13:00:07 +0000594
595 // Mark that we're closing on 'this' in all the block scopes, if applicable.
596 for (unsigned idx = FunctionScopes.size() - 1;
597 isa<BlockScopeInfo>(FunctionScopes[idx]);
598 --idx)
599 cast<BlockScopeInfo>(FunctionScopes[idx])->CapturesCXXThis = true;
600
John McCall5808ce42011-02-03 08:15:49 +0000601 return method;
602}
603
604ExprResult Sema::ActOnCXXThis(SourceLocation loc) {
605 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
606 /// is a non-lvalue expression whose value is the address of the object for
607 /// which the function is called.
608
609 CXXMethodDecl *method = tryCaptureCXXThis();
610 if (!method) return Diag(loc, diag::err_invalid_this_use);
611
612 return Owned(new (Context) CXXThisExpr(loc, method->getThisType(Context),
John McCall469a1eb2011-02-02 13:00:07 +0000613 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000614}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000615
John McCall60d7b3a2010-08-24 06:29:42 +0000616ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000617Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000618 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000619 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000620 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000621 if (!TypeRep)
622 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000623
John McCall9d125032010-01-15 18:39:57 +0000624 TypeSourceInfo *TInfo;
625 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
626 if (!TInfo)
627 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000628
629 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
630}
631
632/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
633/// Can be interpreted either as function-style casting ("int(x)")
634/// or class type construction ("ClassType(x,y,z)")
635/// or creation of a value-initialized type ("int()").
636ExprResult
637Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
638 SourceLocation LParenLoc,
639 MultiExprArg exprs,
640 SourceLocation RParenLoc) {
641 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000642 unsigned NumExprs = exprs.size();
643 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000644 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000645 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
646
Sebastian Redlf53597f2009-03-15 17:47:39 +0000647 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000648 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000649 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000650
Douglas Gregorab6677e2010-09-08 00:15:04 +0000651 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000652 LParenLoc,
653 Exprs, NumExprs,
654 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000655 }
656
Anders Carlssonbb60a502009-08-27 03:53:50 +0000657 if (Ty->isArrayType())
658 return ExprError(Diag(TyBeginLoc,
659 diag::err_value_init_for_array_type) << FullRange);
660 if (!Ty->isVoidType() &&
661 RequireCompleteType(TyBeginLoc, Ty,
662 PDiag(diag::err_invalid_incomplete_type_use)
663 << FullRange))
664 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000665
Anders Carlssonbb60a502009-08-27 03:53:50 +0000666 if (RequireNonAbstractType(TyBeginLoc, Ty,
667 diag::err_allocation_of_abstract_type))
668 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000669
670
Douglas Gregor506ae412009-01-16 18:33:17 +0000671 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000672 // If the expression list is a single expression, the type conversion
673 // expression is equivalent (in definedness, and if defined in meaning) to the
674 // corresponding cast expression.
675 //
676 if (NumExprs == 1) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000677 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +0000678 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +0000679 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +0000680 ExprResult CastExpr =
681 CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
682 Kind, VK, BasePath,
683 /*FunctionalStyle=*/true);
684 if (CastExpr.isInvalid())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000685 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +0000686 Exprs[0] = CastExpr.take();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000687
688 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000689
John McCallf871d0c2010-08-07 06:22:56 +0000690 return Owned(CXXFunctionalCastExpr::Create(Context,
Douglas Gregorab6677e2010-09-08 00:15:04 +0000691 Ty.getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +0000692 VK, TInfo, TyBeginLoc, Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000693 Exprs[0], &BasePath,
694 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000695 }
696
Douglas Gregor19311e72010-09-08 21:40:08 +0000697 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
698 InitializationKind Kind
699 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
700 LParenLoc, RParenLoc)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000701 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor19311e72010-09-08 21:40:08 +0000702 LParenLoc, RParenLoc);
703 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
704 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000705
Douglas Gregor19311e72010-09-08 21:40:08 +0000706 // FIXME: Improve AST representation?
707 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000708}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000709
John McCall6ec278d2011-01-27 09:37:56 +0000710/// doesUsualArrayDeleteWantSize - Answers whether the usual
711/// operator delete[] for the given type has a size_t parameter.
712static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
713 QualType allocType) {
714 const RecordType *record =
715 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
716 if (!record) return false;
717
718 // Try to find an operator delete[] in class scope.
719
720 DeclarationName deleteName =
721 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
722 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
723 S.LookupQualifiedName(ops, record->getDecl());
724
725 // We're just doing this for information.
726 ops.suppressDiagnostics();
727
728 // Very likely: there's no operator delete[].
729 if (ops.empty()) return false;
730
731 // If it's ambiguous, it should be illegal to call operator delete[]
732 // on this thing, so it doesn't matter if we allocate extra space or not.
733 if (ops.isAmbiguous()) return false;
734
735 LookupResult::Filter filter = ops.makeFilter();
736 while (filter.hasNext()) {
737 NamedDecl *del = filter.next()->getUnderlyingDecl();
738
739 // C++0x [basic.stc.dynamic.deallocation]p2:
740 // A template instance is never a usual deallocation function,
741 // regardless of its signature.
742 if (isa<FunctionTemplateDecl>(del)) {
743 filter.erase();
744 continue;
745 }
746
747 // C++0x [basic.stc.dynamic.deallocation]p2:
748 // If class T does not declare [an operator delete[] with one
749 // parameter] but does declare a member deallocation function
750 // named operator delete[] with exactly two parameters, the
751 // second of which has type std::size_t, then this function
752 // is a usual deallocation function.
753 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
754 filter.erase();
755 continue;
756 }
757 }
758 filter.done();
759
760 if (!ops.isSingleResult()) return false;
761
762 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
763 return (del->getNumParams() == 2);
764}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000765
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000766/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
767/// @code new (memory) int[size][4] @endcode
768/// or
769/// @code ::new Foo(23, "hello") @endcode
770/// For the interpretation of this heap of arguments, consult the base version.
John McCall60d7b3a2010-08-24 06:29:42 +0000771ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000772Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000773 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000774 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000775 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000776 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000777 SourceLocation ConstructorRParen) {
Richard Smith34b41d92011-02-20 03:19:35 +0000778 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
779
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000780 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000781 // If the specified type is an array, unwrap it and save the expression.
782 if (D.getNumTypeObjects() > 0 &&
783 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
784 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith34b41d92011-02-20 03:19:35 +0000785 if (TypeContainsAuto)
786 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
787 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000788 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000789 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
790 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000791 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000792 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
793 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000794
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000795 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000796 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000797 }
798
Douglas Gregor043cad22009-09-11 00:18:58 +0000799 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000800 if (ArraySize) {
801 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000802 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
803 break;
804
805 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
806 if (Expr *NumElts = (Expr *)Array.NumElts) {
807 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
808 !NumElts->isIntegerConstantExpr(Context)) {
809 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
810 << NumElts->getSourceRange();
811 return ExprError();
812 }
813 }
814 }
815 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000816
Richard Smith34b41d92011-02-20 03:19:35 +0000817 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0, /*OwnedDecl=*/0,
818 /*AllowAuto=*/true);
John McCallbf1a0282010-06-04 23:28:52 +0000819 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000820 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000821 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000822
Mike Stump1eb44332009-09-09 15:08:12 +0000823 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000824 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000825 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000826 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000827 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000828 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000829 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000830 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000831 ConstructorLParen,
832 move(ConstructorArgs),
Richard Smith34b41d92011-02-20 03:19:35 +0000833 ConstructorRParen,
834 TypeContainsAuto);
Douglas Gregor3433cf72009-05-21 00:00:09 +0000835}
836
John McCall60d7b3a2010-08-24 06:29:42 +0000837ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000838Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
839 SourceLocation PlacementLParen,
840 MultiExprArg PlacementArgs,
841 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000842 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000843 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000844 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000845 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000846 SourceLocation ConstructorLParen,
847 MultiExprArg ConstructorArgs,
Richard Smith34b41d92011-02-20 03:19:35 +0000848 SourceLocation ConstructorRParen,
849 bool TypeMayContainAuto) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000850 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000851
Richard Smith34b41d92011-02-20 03:19:35 +0000852 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
853 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
854 if (ConstructorArgs.size() == 0)
855 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
856 << AllocType << TypeRange);
857 if (ConstructorArgs.size() != 1) {
858 Expr *FirstBad = ConstructorArgs.get()[1];
859 return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
860 diag::err_auto_new_ctor_multiple_expressions)
861 << AllocType << TypeRange);
862 }
Richard Smitha085da82011-03-17 16:11:59 +0000863 TypeSourceInfo *DeducedType = 0;
864 if (!DeduceAutoType(AllocTypeInfo, ConstructorArgs.get()[0], DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +0000865 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
866 << AllocType
867 << ConstructorArgs.get()[0]->getType()
868 << TypeRange
869 << ConstructorArgs.get()[0]->getSourceRange());
Richard Smitha085da82011-03-17 16:11:59 +0000870 if (!DeducedType)
871 return ExprError();
Richard Smith34b41d92011-02-20 03:19:35 +0000872
Richard Smitha085da82011-03-17 16:11:59 +0000873 AllocTypeInfo = DeducedType;
874 AllocType = AllocTypeInfo->getType();
Richard Smith34b41d92011-02-20 03:19:35 +0000875 }
876
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000877 // Per C++0x [expr.new]p5, the type being constructed may be a
878 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +0000879 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000880 if (const ConstantArrayType *Array
881 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000882 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
883 Context.getSizeType(),
884 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000885 AllocType = Array->getElementType();
886 }
887 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000888
Douglas Gregora0750762010-10-06 16:00:31 +0000889 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
890 return ExprError();
891
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000892 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000893
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000894 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
895 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000896 if (ArraySize && !ArraySize->isTypeDependent()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000897
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000898 QualType SizeType = ArraySize->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000899
John McCall60d7b3a2010-08-24 06:29:42 +0000900 ExprResult ConvertedSize
John McCall9ae2f072010-08-23 23:25:46 +0000901 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000902 PDiag(diag::err_array_size_not_integral),
903 PDiag(diag::err_array_size_incomplete_type)
904 << ArraySize->getSourceRange(),
905 PDiag(diag::err_array_size_explicit_conversion),
906 PDiag(diag::note_array_size_conversion),
907 PDiag(diag::err_array_size_ambiguous_conversion),
908 PDiag(diag::note_array_size_conversion),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000909 PDiag(getLangOptions().CPlusPlus0x? 0
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000910 : diag::ext_array_size_conversion));
911 if (ConvertedSize.isInvalid())
912 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000913
John McCall9ae2f072010-08-23 23:25:46 +0000914 ArraySize = ConvertedSize.take();
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000915 SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000916 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000917 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000918
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000919 // Let's see if this is a constant < 0. If so, we reject it out of hand.
920 // We don't care about special rules, so we tell the machinery it's not
921 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000922 if (!ArraySize->isValueDependent()) {
923 llvm::APSInt Value;
924 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
925 if (Value < llvm::APSInt(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000926 llvm::APInt::getNullValue(Value.getBitWidth()),
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000927 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000928 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000929 diag::err_typecheck_negative_array_size)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000930 << ArraySize->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000931
Douglas Gregor2767ce22010-08-18 00:39:00 +0000932 if (!AllocType->isDependentType()) {
933 unsigned ActiveSizeBits
934 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
935 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000936 Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregor2767ce22010-08-18 00:39:00 +0000937 diag::err_array_too_large)
938 << Value.toString(10)
939 << ArraySize->getSourceRange();
940 return ExprError();
941 }
942 }
Douglas Gregor4bd40312010-07-13 15:54:32 +0000943 } else if (TypeIdParens.isValid()) {
944 // Can't have dynamic array size when the type-id is in parentheses.
945 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
946 << ArraySize->getSourceRange()
947 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
948 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000949
Douglas Gregor4bd40312010-07-13 15:54:32 +0000950 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +0000951 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000952 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000953
John Wiegley429bb272011-04-08 18:41:53 +0000954 ArraySize = ImpCastExprToType(ArraySize, Context.getSizeType(),
955 CK_IntegralCast).take();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000956 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000957
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000958 FunctionDecl *OperatorNew = 0;
959 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000960 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
961 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000962
Sebastian Redl28507842009-02-26 14:39:58 +0000963 if (!AllocType->isDependentType() &&
964 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
965 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000966 SourceRange(PlacementLParen, PlacementRParen),
967 UseGlobal, AllocType, ArraySize, PlaceArgs,
968 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000969 return ExprError();
John McCall6ec278d2011-01-27 09:37:56 +0000970
971 // If this is an array allocation, compute whether the usual array
972 // deallocation function for the type has a size_t parameter.
973 bool UsualArrayDeleteWantsSize = false;
974 if (ArraySize && !AllocType->isDependentType())
975 UsualArrayDeleteWantsSize
976 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
977
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000978 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000979 if (OperatorNew) {
980 // Add default arguments, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000981 const FunctionProtoType *Proto =
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000982 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000983 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000984 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000985
Anders Carlsson28e94832010-05-03 02:07:56 +0000986 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000987 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlsson28e94832010-05-03 02:07:56 +0000988 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000989 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000990
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000991 NumPlaceArgs = AllPlaceArgs.size();
992 if (NumPlaceArgs > 0)
993 PlaceArgs = &AllPlaceArgs[0];
994 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000995
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000996 bool Init = ConstructorLParen.isValid();
997 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000998 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000999 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
1000 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +00001001 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +00001002
Anders Carlsson48c95012010-05-03 15:45:23 +00001003 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +00001004 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +00001005 SourceRange InitRange(ConsArgs[0]->getLocStart(),
1006 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001007
Anders Carlsson48c95012010-05-03 15:45:23 +00001008 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1009 return ExprError();
1010 }
1011
Douglas Gregor99a2e602009-12-16 01:38:02 +00001012 if (!AllocType->isDependentType() &&
1013 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
1014 // C++0x [expr.new]p15:
1015 // A new-expression that creates an object of type T initializes that
1016 // object as follows:
1017 InitializationKind Kind
1018 // - If the new-initializer is omitted, the object is default-
1019 // initialized (8.5); if no initialization is performed,
1020 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001021 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001022 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor99a2e602009-12-16 01:38:02 +00001023 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001024 : InitializationKind::CreateDirect(TypeRange.getBegin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001025 ConstructorLParen,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001026 ConstructorRParen);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001027
Douglas Gregor99a2e602009-12-16 01:38:02 +00001028 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00001029 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001030 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001031 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001032 move(ConstructorArgs));
1033 if (FullInit.isInvalid())
1034 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001035
1036 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor99a2e602009-12-16 01:38:02 +00001037 // constructor call, which CXXNewExpr handles directly.
1038 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1039 if (CXXBindTemporaryExpr *Binder
1040 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1041 FullInitExpr = Binder->getSubExpr();
1042 if (CXXConstructExpr *Construct
1043 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1044 Constructor = Construct->getConstructor();
1045 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1046 AEnd = Construct->arg_end();
1047 A != AEnd; ++A)
John McCall3fa5cae2010-10-26 07:05:15 +00001048 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001049 } else {
1050 // Take the converted initializer.
1051 ConvertedConstructorArgs.push_back(FullInit.release());
1052 }
1053 } else {
1054 // No initialization required.
1055 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001056
Douglas Gregor99a2e602009-12-16 01:38:02 +00001057 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001058 NumConsArgs = ConvertedConstructorArgs.size();
1059 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001060 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001061
Douglas Gregor6d908702010-02-26 05:06:18 +00001062 // Mark the new and delete operators as referenced.
1063 if (OperatorNew)
1064 MarkDeclarationReferenced(StartLoc, OperatorNew);
1065 if (OperatorDelete)
1066 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1067
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001068 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001069
Sebastian Redlf53597f2009-03-15 17:47:39 +00001070 PlacementArgs.release();
1071 ConstructorArgs.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001072
Ted Kremenekad7fe862010-02-11 22:51:03 +00001073 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001074 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001075 ArraySize, Constructor, Init,
1076 ConsArgs, NumConsArgs, OperatorDelete,
John McCall6ec278d2011-01-27 09:37:56 +00001077 UsualArrayDeleteWantsSize,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001078 ResultType, AllocTypeInfo,
1079 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001080 Init ? ConstructorRParen :
Chandler Carruth428edaf2010-10-25 08:47:36 +00001081 TypeRange.getEnd(),
1082 ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001083}
1084
1085/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1086/// in a new-expression.
1087/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +00001088bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00001089 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001090 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1091 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +00001092 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001093 return Diag(Loc, diag::err_bad_new_type)
1094 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001095 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001096 return Diag(Loc, diag::err_bad_new_type)
1097 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001098 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +00001099 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001100 PDiag(diag::err_new_incomplete_type)
1101 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001102 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +00001103 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +00001104 diag::err_allocation_of_abstract_type))
1105 return true;
Douglas Gregora0750762010-10-06 16:00:31 +00001106 else if (AllocType->isVariablyModifiedType())
1107 return Diag(Loc, diag::err_variably_modified_new_type)
1108 << AllocType;
Douglas Gregor5666d362011-04-15 19:46:20 +00001109 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1110 return Diag(Loc, diag::err_address_space_qualified_new)
1111 << AllocType.getUnqualifiedType() << AddressSpace;
1112
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001113 return false;
1114}
1115
Douglas Gregor6d908702010-02-26 05:06:18 +00001116/// \brief Determine whether the given function is a non-placement
1117/// deallocation function.
1118static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1119 if (FD->isInvalidDecl())
1120 return false;
1121
1122 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1123 return Method->isUsualDeallocationFunction();
1124
1125 return ((FD->getOverloadedOperator() == OO_Delete ||
1126 FD->getOverloadedOperator() == OO_Array_Delete) &&
1127 FD->getNumParams() == 1);
1128}
1129
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001130/// FindAllocationFunctions - Finds the overloads of operator new and delete
1131/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001132bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1133 bool UseGlobal, QualType AllocType,
1134 bool IsArray, Expr **PlaceArgs,
1135 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001136 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +00001137 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001138 // --- Choosing an allocation function ---
1139 // C++ 5.3.4p8 - 14 & 18
1140 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1141 // in the scope of the allocated class.
1142 // 2) If an array size is given, look for operator new[], else look for
1143 // operator new.
1144 // 3) The first argument is always size_t. Append the arguments from the
1145 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001146
1147 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
1148 // We don't care about the actual value of this argument.
1149 // FIXME: Should the Sema create the expression and embed it in the syntax
1150 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001151 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Anders Carlssond67c4c32009-08-16 20:29:29 +00001152 Context.Target.getPointerWidth(0)),
1153 Context.getSizeType(),
1154 SourceLocation());
1155 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001156 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1157
Douglas Gregor6d908702010-02-26 05:06:18 +00001158 // C++ [expr.new]p8:
1159 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001160 // function's name is operator new and the deallocation function's
Douglas Gregor6d908702010-02-26 05:06:18 +00001161 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001162 // type, the allocation function's name is operator new[] and the
1163 // deallocation function's name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001164 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1165 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001166 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1167 IsArray ? OO_Array_Delete : OO_Delete);
1168
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001169 QualType AllocElemType = Context.getBaseElementType(AllocType);
1170
1171 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001172 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001173 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001174 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001175 AllocArgs.size(), Record, /*AllowMissing=*/true,
1176 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001177 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001178 }
1179 if (!OperatorNew) {
1180 // Didn't find a member overload. Look for a global one.
1181 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001182 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001183 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001184 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1185 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001186 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001187 }
1188
John McCall9c82afc2010-04-20 02:18:25 +00001189 // We don't need an operator delete if we're running under
1190 // -fno-exceptions.
1191 if (!getLangOptions().Exceptions) {
1192 OperatorDelete = 0;
1193 return false;
1194 }
1195
Anders Carlssond9583892009-05-31 20:26:12 +00001196 // FindAllocationOverload can change the passed in arguments, so we need to
1197 // copy them back.
1198 if (NumPlaceArgs > 0)
1199 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Douglas Gregor6d908702010-02-26 05:06:18 +00001201 // C++ [expr.new]p19:
1202 //
1203 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001204 // deallocation function's name is looked up in the global
Douglas Gregor6d908702010-02-26 05:06:18 +00001205 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001206 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6d908702010-02-26 05:06:18 +00001207 // the scope of T. If this lookup fails to find the name, or if
1208 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001209 // deallocation function's name is looked up in the global scope.
Douglas Gregor6d908702010-02-26 05:06:18 +00001210 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001211 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001212 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001213 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001214 LookupQualifiedName(FoundDelete, RD);
1215 }
John McCall90c8c572010-03-18 08:19:33 +00001216 if (FoundDelete.isAmbiguous())
1217 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001218
1219 if (FoundDelete.empty()) {
1220 DeclareGlobalNewDelete();
1221 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1222 }
1223
1224 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001225
1226 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1227
John McCalledeb6c92010-09-14 21:34:24 +00001228 // Whether we're looking for a placement operator delete is dictated
1229 // by whether we selected a placement operator new, not by whether
1230 // we had explicit placement arguments. This matters for things like
1231 // struct A { void *operator new(size_t, int = 0); ... };
1232 // A *a = new A()
1233 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1234
1235 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001236 // C++ [expr.new]p20:
1237 // A declaration of a placement deallocation function matches the
1238 // declaration of a placement allocation function if it has the
1239 // same number of parameters and, after parameter transformations
1240 // (8.3.5), all parameter types except the first are
1241 // identical. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001242 //
Douglas Gregor6d908702010-02-26 05:06:18 +00001243 // To perform this comparison, we compute the function type that
1244 // the deallocation function should have, and use that type both
1245 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001246 //
1247 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001248 QualType ExpectedFunctionType;
1249 {
1250 const FunctionProtoType *Proto
1251 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001252
Douglas Gregor6d908702010-02-26 05:06:18 +00001253 llvm::SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001254 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6d908702010-02-26 05:06:18 +00001255 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1256 ArgTypes.push_back(Proto->getArgType(I));
1257
John McCalle23cf432010-12-14 08:05:40 +00001258 FunctionProtoType::ExtProtoInfo EPI;
1259 EPI.Variadic = Proto->isVariadic();
1260
Douglas Gregor6d908702010-02-26 05:06:18 +00001261 ExpectedFunctionType
1262 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalle23cf432010-12-14 08:05:40 +00001263 ArgTypes.size(), EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001264 }
1265
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001266 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001267 DEnd = FoundDelete.end();
1268 D != DEnd; ++D) {
1269 FunctionDecl *Fn = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001270 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6d908702010-02-26 05:06:18 +00001271 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1272 // Perform template argument deduction to try to match the
1273 // expected function type.
1274 TemplateDeductionInfo Info(Context, StartLoc);
1275 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1276 continue;
1277 } else
1278 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1279
1280 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001281 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001282 }
1283 } else {
1284 // C++ [expr.new]p20:
1285 // [...] Any non-placement deallocation function matches a
1286 // non-placement allocation function. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001287 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001288 DEnd = FoundDelete.end();
1289 D != DEnd; ++D) {
1290 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1291 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001292 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001293 }
1294 }
1295
1296 // C++ [expr.new]p20:
1297 // [...] If the lookup finds a single matching deallocation
1298 // function, that function will be called; otherwise, no
1299 // deallocation function will be called.
1300 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001301 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001302
1303 // C++0x [expr.new]p20:
1304 // If the lookup finds the two-parameter form of a usual
1305 // deallocation function (3.7.4.2) and that function, considered
1306 // as a placement deallocation function, would have been
1307 // selected as a match for the allocation function, the program
1308 // is ill-formed.
1309 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1310 isNonPlacementDeallocationFunction(OperatorDelete)) {
1311 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001312 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001313 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1314 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1315 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001316 } else {
1317 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001318 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001319 }
1320 }
1321
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001322 return false;
1323}
1324
Sebastian Redl7f662392008-12-04 22:20:51 +00001325/// FindAllocationOverload - Find an fitting overload for the allocation
1326/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001327bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1328 DeclarationName Name, Expr** Args,
1329 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001330 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001331 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1332 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001333 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001334 if (AllowMissing)
1335 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001336 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001337 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001338 }
1339
John McCall90c8c572010-03-18 08:19:33 +00001340 if (R.isAmbiguous())
1341 return true;
1342
1343 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001344
John McCall5769d612010-02-08 23:07:23 +00001345 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001346 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001347 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001348 // Even member operator new/delete are implicitly treated as
1349 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001350 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001351
John McCall9aa472c2010-03-19 07:35:19 +00001352 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1353 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001354 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1355 Candidates,
1356 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001357 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001358 }
1359
John McCall9aa472c2010-03-19 07:35:19 +00001360 FunctionDecl *Fn = cast<FunctionDecl>(D);
1361 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001362 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001363 }
1364
1365 // Do the resolution.
1366 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001367 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001368 case OR_Success: {
1369 // Got one!
1370 FunctionDecl *FnDecl = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00001371 MarkDeclarationReferenced(StartLoc, FnDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001372 // The first argument is size_t, and the first parameter must be size_t,
1373 // too. This is checked on declaration and can be assumed. (It can't be
1374 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001375 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001376 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1377 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
John McCall60d7b3a2010-08-24 06:29:42 +00001378 ExprResult Result
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001379 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001380 Context,
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001381 FnDecl->getParamDecl(i)),
1382 SourceLocation(),
John McCall3fa5cae2010-10-26 07:05:15 +00001383 Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001384 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001385 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001386
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001387 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001388 }
1389 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001390 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001391 return false;
1392 }
1393
1394 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001395 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001396 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001397 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001398 return true;
1399
1400 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001401 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001402 << Name << Range;
John McCall120d63c2010-08-24 20:38:10 +00001403 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001404 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001405
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001406 case OR_Deleted: {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001407 Diag(StartLoc, diag::err_ovl_deleted_call)
1408 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00001409 << Name
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001410 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00001411 << Range;
John McCall120d63c2010-08-24 20:38:10 +00001412 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001413 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001414 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001415 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001416 assert(false && "Unreachable, bad result from BestViableFunction");
1417 return true;
1418}
1419
1420
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001421/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1422/// delete. These are:
1423/// @code
Sebastian Redl8999fe12011-03-14 18:08:30 +00001424/// // C++03:
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001425/// void* operator new(std::size_t) throw(std::bad_alloc);
1426/// void* operator new[](std::size_t) throw(std::bad_alloc);
1427/// void operator delete(void *) throw();
1428/// void operator delete[](void *) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001429/// // C++0x:
1430/// void* operator new(std::size_t);
1431/// void* operator new[](std::size_t);
1432/// void operator delete(void *);
1433/// void operator delete[](void *);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001434/// @endcode
Sebastian Redl8999fe12011-03-14 18:08:30 +00001435/// C++0x operator delete is implicitly noexcept.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001436/// Note that the placement and nothrow forms of new are *not* implicitly
1437/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001438void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001439 if (GlobalNewDeleteDeclared)
1440 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001441
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001442 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001443 // [...] The following allocation and deallocation functions (18.4) are
1444 // implicitly declared in global scope in each translation unit of a
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001445 // program
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001446 //
Sebastian Redl8999fe12011-03-14 18:08:30 +00001447 // C++03:
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001448 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001449 // void* operator new[](std::size_t) throw(std::bad_alloc);
1450 // void operator delete(void*) throw();
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001451 // void operator delete[](void*) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001452 // C++0x:
1453 // void* operator new(std::size_t);
1454 // void* operator new[](std::size_t);
1455 // void operator delete(void*);
1456 // void operator delete[](void*);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001457 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001458 // These implicit declarations introduce only the function names operator
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001459 // new, operator new[], operator delete, operator delete[].
1460 //
1461 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1462 // "std" or "bad_alloc" as necessary to form the exception specification.
1463 // However, we do not make these implicit declarations visible to name
1464 // lookup.
Sebastian Redl8999fe12011-03-14 18:08:30 +00001465 // Note that the C++0x versions of operator delete are deallocation functions,
1466 // and thus are implicitly noexcept.
1467 if (!StdBadAlloc && !getLangOptions().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001468 // The "std::bad_alloc" class has not yet been declared, so build it
1469 // implicitly.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001470 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1471 getOrCreateStdNamespace(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001472 SourceLocation(), SourceLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001473 &PP.getIdentifierTable().get("bad_alloc"),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001474 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001475 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001476 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001477
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001478 GlobalNewDeleteDeclared = true;
1479
1480 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1481 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001482 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001483
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001484 DeclareGlobalAllocationFunction(
1485 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001486 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001487 DeclareGlobalAllocationFunction(
1488 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001489 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001490 DeclareGlobalAllocationFunction(
1491 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1492 Context.VoidTy, VoidPtr);
1493 DeclareGlobalAllocationFunction(
1494 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1495 Context.VoidTy, VoidPtr);
1496}
1497
1498/// DeclareGlobalAllocationFunction - Declares a single implicit global
1499/// allocation function if it doesn't already exist.
1500void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001501 QualType Return, QualType Argument,
1502 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001503 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1504
1505 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001506 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001507 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001508 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001509 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001510 // Only look at non-template functions, as it is the predefined,
1511 // non-templated allocation function we are trying to declare here.
1512 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1513 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001514 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001515 Func->getParamDecl(0)->getType().getUnqualifiedType());
1516 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001517 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1518 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001519 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001520 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001521 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001522 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001523 }
1524 }
1525
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001526 QualType BadAllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001527 bool HasBadAllocExceptionSpec
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001528 = (Name.getCXXOverloadedOperator() == OO_New ||
1529 Name.getCXXOverloadedOperator() == OO_Array_New);
Sebastian Redl8999fe12011-03-14 18:08:30 +00001530 if (HasBadAllocExceptionSpec && !getLangOptions().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001531 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001532 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001533 }
John McCalle23cf432010-12-14 08:05:40 +00001534
1535 FunctionProtoType::ExtProtoInfo EPI;
John McCalle23cf432010-12-14 08:05:40 +00001536 if (HasBadAllocExceptionSpec) {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001537 if (!getLangOptions().CPlusPlus0x) {
1538 EPI.ExceptionSpecType = EST_Dynamic;
1539 EPI.NumExceptions = 1;
1540 EPI.Exceptions = &BadAllocType;
1541 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00001542 } else {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001543 EPI.ExceptionSpecType = getLangOptions().CPlusPlus0x ?
1544 EST_BasicNoexcept : EST_DynamicNone;
John McCalle23cf432010-12-14 08:05:40 +00001545 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001546
John McCalle23cf432010-12-14 08:05:40 +00001547 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001548 FunctionDecl *Alloc =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001549 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1550 SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001551 FnType, /*TInfo=*/0, SC_None,
1552 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001553 Alloc->setImplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001554
Nuno Lopesfc284482009-12-16 16:59:22 +00001555 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001556 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001557
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001558 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001559 SourceLocation(), 0,
1560 Argument, /*TInfo=*/0,
1561 SC_None, SC_None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001562 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001563
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001564 // FIXME: Also add this declaration to the IdentifierResolver, but
1565 // make sure it is at the end of the chain to coincide with the
1566 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001567 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001568}
1569
Anders Carlsson78f74552009-11-15 18:45:20 +00001570bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1571 DeclarationName Name,
Sean Huntcb45a0f2011-05-12 22:46:25 +00001572 FunctionDecl* &Operator, bool AllowMissing) {
John McCalla24dc2e2009-11-17 02:14:36 +00001573 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001574 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001575 LookupQualifiedName(Found, RD);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001576
John McCalla24dc2e2009-11-17 02:14:36 +00001577 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001578 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001579
Chandler Carruth23893242010-06-28 00:30:51 +00001580 Found.suppressDiagnostics();
1581
John McCall046a7462010-08-04 00:31:26 +00001582 llvm::SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001583 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1584 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001585 NamedDecl *ND = (*F)->getUnderlyingDecl();
1586
1587 // Ignore template operator delete members from the check for a usual
1588 // deallocation function.
1589 if (isa<FunctionTemplateDecl>(ND))
1590 continue;
1591
1592 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001593 Matches.push_back(F.getPair());
1594 }
1595
1596 // There's exactly one suitable operator; pick it.
1597 if (Matches.size() == 1) {
1598 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1599 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Sean Huntcb45a0f2011-05-12 22:46:25 +00001600 Matches[0], !AllowMissing);
John McCall046a7462010-08-04 00:31:26 +00001601 return false;
1602
1603 // We found multiple suitable operators; complain about the ambiguity.
1604 } else if (!Matches.empty()) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001605 if (!AllowMissing) {
1606 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1607 << Name << RD;
John McCall046a7462010-08-04 00:31:26 +00001608
Sean Huntcb45a0f2011-05-12 22:46:25 +00001609 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1610 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1611 Diag((*F)->getUnderlyingDecl()->getLocation(),
1612 diag::note_member_declared_here) << Name;
1613 }
John McCall046a7462010-08-04 00:31:26 +00001614 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001615 }
1616
1617 // We did find operator delete/operator delete[] declarations, but
1618 // none of them were suitable.
1619 if (!Found.empty()) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001620 if (!AllowMissing) {
1621 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1622 << Name << RD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001623
Sean Huntcb45a0f2011-05-12 22:46:25 +00001624 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1625 F != FEnd; ++F)
1626 Diag((*F)->getUnderlyingDecl()->getLocation(),
1627 diag::note_member_declared_here) << Name;
1628 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001629 return true;
1630 }
1631
1632 // Look for a global declaration.
1633 DeclareGlobalNewDelete();
1634 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001635
Anders Carlsson78f74552009-11-15 18:45:20 +00001636 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1637 Expr* DeallocArgs[1];
1638 DeallocArgs[0] = &Null;
1639 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
Sean Huntcb45a0f2011-05-12 22:46:25 +00001640 DeallocArgs, 1, TUDecl, AllowMissing,
Anders Carlsson78f74552009-11-15 18:45:20 +00001641 Operator))
1642 return true;
1643
1644 assert(Operator && "Did not find a deallocation function!");
1645 return false;
1646}
1647
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001648/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1649/// @code ::delete ptr; @endcode
1650/// or
1651/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001652ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001653Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley429bb272011-04-08 18:41:53 +00001654 bool ArrayForm, Expr *ExE) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001655 // C++ [expr.delete]p1:
1656 // The operand shall have a pointer type, or a class type having a single
1657 // conversion function to a pointer type. The result has type void.
1658 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001659 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1660
John Wiegley429bb272011-04-08 18:41:53 +00001661 ExprResult Ex = Owned(ExE);
Anders Carlssond67c4c32009-08-16 20:29:29 +00001662 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001663 bool ArrayFormAsWritten = ArrayForm;
John McCall6ec278d2011-01-27 09:37:56 +00001664 bool UsualArrayDeleteWantsSize = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001665
John Wiegley429bb272011-04-08 18:41:53 +00001666 if (!Ex.get()->isTypeDependent()) {
1667 QualType Type = Ex.get()->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001668
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001669 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001670 if (RequireCompleteType(StartLoc, Type,
Douglas Gregor254a9422010-07-29 14:44:35 +00001671 PDiag(diag::err_delete_incomplete_class_type)))
1672 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001673
John McCall32daa422010-03-31 01:36:47 +00001674 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1675
Fariborz Jahanian53462782009-09-11 21:44:33 +00001676 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001677 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001678 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001679 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001680 NamedDecl *D = I.getDecl();
1681 if (isa<UsingShadowDecl>(D))
1682 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1683
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001684 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001685 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001686 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001687
John McCall32daa422010-03-31 01:36:47 +00001688 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001689
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001690 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1691 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001692 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001693 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001694 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001695 if (ObjectPtrConversions.size() == 1) {
1696 // We have a single conversion to a pointer-to-object type. Perform
1697 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001698 // TODO: don't redo the conversion calculation.
John Wiegley429bb272011-04-08 18:41:53 +00001699 ExprResult Res =
1700 PerformImplicitConversion(Ex.get(),
John McCall32daa422010-03-31 01:36:47 +00001701 ObjectPtrConversions.front()->getConversionType(),
John Wiegley429bb272011-04-08 18:41:53 +00001702 AA_Converting);
1703 if (Res.isUsable()) {
1704 Ex = move(Res);
1705 Type = Ex.get()->getType();
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001706 }
1707 }
1708 else if (ObjectPtrConversions.size() > 1) {
1709 Diag(StartLoc, diag::err_ambiguous_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001710 << Type << Ex.get()->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001711 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1712 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001713 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001714 }
Sebastian Redl28507842009-02-26 14:39:58 +00001715 }
1716
Sebastian Redlf53597f2009-03-15 17:47:39 +00001717 if (!Type->isPointerType())
1718 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001719 << Type << Ex.get()->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001720
Ted Kremenek6217b802009-07-29 21:53:49 +00001721 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor94a61572010-05-24 17:01:56 +00001722 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001723 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregor94a61572010-05-24 17:01:56 +00001724 // effectively bans deletion of "void*". However, most compilers support
1725 // this, so we treat it as a warning unless we're in a SFINAE context.
1726 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001727 << Type << Ex.get()->getSourceRange();
Douglas Gregor94a61572010-05-24 17:01:56 +00001728 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001729 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001730 << Type << Ex.get()->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001731 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001732 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001733 PDiag(diag::warn_delete_incomplete)
John Wiegley429bb272011-04-08 18:41:53 +00001734 << Ex.get()->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001735 return ExprError();
Douglas Gregor5666d362011-04-15 19:46:20 +00001736 else if (unsigned AddressSpace = Pointee.getAddressSpace())
1737 return Diag(Ex.get()->getLocStart(),
1738 diag::err_address_space_qualified_delete)
1739 << Pointee.getUnqualifiedType() << AddressSpace;
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001740 // C++ [expr.delete]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001741 // [Note: a pointer to a const type can be the operand of a
1742 // delete-expression; it is not necessary to cast away the constness
1743 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001744 // of the delete-expression. ]
John Wiegley429bb272011-04-08 18:41:53 +00001745 Ex = ImpCastExprToType(Ex.take(), Context.getPointerType(Context.VoidTy),
John McCall2de56d12010-08-25 11:45:40 +00001746 CK_NoOp);
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001747
1748 if (Pointee->isArrayType() && !ArrayForm) {
1749 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley429bb272011-04-08 18:41:53 +00001750 << Type << Ex.get()->getSourceRange()
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001751 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1752 ArrayForm = true;
1753 }
1754
Anders Carlssond67c4c32009-08-16 20:29:29 +00001755 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1756 ArrayForm ? OO_Array_Delete : OO_Delete);
1757
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001758 QualType PointeeElem = Context.getBaseElementType(Pointee);
1759 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001760 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1761
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001762 if (!UseGlobal &&
Anders Carlsson78f74552009-11-15 18:45:20 +00001763 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001764 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001765
John McCall6ec278d2011-01-27 09:37:56 +00001766 // If we're allocating an array of records, check whether the
1767 // usual operator delete[] has a size_t parameter.
1768 if (ArrayForm) {
1769 // If the user specifically asked to use the global allocator,
1770 // we'll need to do the lookup into the class.
1771 if (UseGlobal)
1772 UsualArrayDeleteWantsSize =
1773 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1774
1775 // Otherwise, the usual operator delete[] should be the
1776 // function we just found.
1777 else if (isa<CXXMethodDecl>(OperatorDelete))
1778 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1779 }
1780
Anders Carlsson78f74552009-11-15 18:45:20 +00001781 if (!RD->hasTrivialDestructor())
Douglas Gregor9b623632010-10-12 23:32:35 +00001782 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001783 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001784 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00001785 DiagnoseUseOfDecl(Dtor, StartLoc);
1786 }
Anders Carlssond67c4c32009-08-16 20:29:29 +00001787 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001788
Anders Carlssond67c4c32009-08-16 20:29:29 +00001789 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001790 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001791 DeclareGlobalNewDelete();
1792 DeclContext *TUDecl = Context.getTranslationUnitDecl();
John Wiegley429bb272011-04-08 18:41:53 +00001793 Expr *Arg = Ex.get();
Mike Stump1eb44332009-09-09 15:08:12 +00001794 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
John Wiegley429bb272011-04-08 18:41:53 +00001795 &Arg, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001796 OperatorDelete))
1797 return ExprError();
1798 }
Mike Stump1eb44332009-09-09 15:08:12 +00001799
John McCall9c82afc2010-04-20 02:18:25 +00001800 MarkDeclarationReferenced(StartLoc, OperatorDelete);
John McCall6ec278d2011-01-27 09:37:56 +00001801
Douglas Gregord880f522011-02-01 15:50:11 +00001802 // Check access and ambiguity of operator delete and destructor.
1803 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1804 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1805 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
John Wiegley429bb272011-04-08 18:41:53 +00001806 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregord880f522011-02-01 15:50:11 +00001807 PDiag(diag::err_access_dtor) << PointeeElem);
1808 }
1809 }
1810
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001811 }
1812
Sebastian Redlf53597f2009-03-15 17:47:39 +00001813 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall6ec278d2011-01-27 09:37:56 +00001814 ArrayFormAsWritten,
1815 UsualArrayDeleteWantsSize,
John Wiegley429bb272011-04-08 18:41:53 +00001816 OperatorDelete, Ex.take(), StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001817}
1818
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001819/// \brief Check the use of the given variable as a C++ condition in an if,
1820/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00001821ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00001822 SourceLocation StmtLoc,
1823 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001824 QualType T = ConditionVar->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001825
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001826 // C++ [stmt.select]p2:
1827 // The declarator shall not specify a function or an array.
1828 if (T->isFunctionType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001829 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001830 diag::err_invalid_use_of_function_type)
1831 << ConditionVar->getSourceRange());
1832 else if (T->isArrayType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001833 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001834 diag::err_invalid_use_of_array_type)
1835 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001836
John Wiegley429bb272011-04-08 18:41:53 +00001837 ExprResult Condition =
1838 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
Douglas Gregor40d96a62011-02-28 21:54:11 +00001839 ConditionVar,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001840 ConditionVar->getLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00001841 ConditionVar->getType().getNonReferenceType(),
John Wiegley429bb272011-04-08 18:41:53 +00001842 VK_LValue));
1843 if (ConvertToBoolean) {
1844 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
1845 if (Condition.isInvalid())
1846 return ExprError();
1847 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001848
John Wiegley429bb272011-04-08 18:41:53 +00001849 return move(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001850}
1851
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001852/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley429bb272011-04-08 18:41:53 +00001853ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001854 // C++ 6.4p4:
1855 // The value of a condition that is an initialized declaration in a statement
1856 // other than a switch statement is the value of the declared variable
1857 // implicitly converted to type bool. If that conversion is ill-formed, the
1858 // program is ill-formed.
1859 // The value of a condition that is an expression is the value of the
1860 // expression, implicitly converted to bool.
1861 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001862 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001863}
Douglas Gregor77a52232008-09-12 00:47:35 +00001864
1865/// Helper function to determine whether this is the (deprecated) C++
1866/// conversion from a string literal to a pointer to non-const char or
1867/// non-const wchar_t (for narrow and wide string literals,
1868/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001869bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001870Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1871 // Look inside the implicit cast, if it exists.
1872 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1873 From = Cast->getSubExpr();
1874
1875 // A string literal (2.13.4) that is not a wide string literal can
1876 // be converted to an rvalue of type "pointer to char"; a wide
1877 // string literal can be converted to an rvalue of type "pointer
1878 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00001879 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00001880 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001881 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001882 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001883 // This conversion is considered only when there is an
1884 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001885 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001886 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1887 (!StrLit->isWide() &&
1888 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1889 ToPointeeType->getKind() == BuiltinType::Char_S))))
1890 return true;
1891 }
1892
1893 return false;
1894}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001895
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001896static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00001897 SourceLocation CastLoc,
1898 QualType Ty,
1899 CastKind Kind,
1900 CXXMethodDecl *Method,
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001901 NamedDecl *FoundDecl,
John McCall2de56d12010-08-25 11:45:40 +00001902 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001903 switch (Kind) {
1904 default: assert(0 && "Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00001905 case CK_ConstructorConversion: {
John McCallca0408f2010-08-23 06:44:23 +00001906 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001907
Douglas Gregorba70ab62010-04-16 22:17:36 +00001908 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
John McCallf312b1e2010-08-26 23:41:50 +00001909 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00001910 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00001911 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001912
1913 ExprResult Result =
1914 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
John McCall7a1fad32010-08-24 07:32:53 +00001915 move_arg(ConstructorArgs),
Chandler Carruth428edaf2010-10-25 08:47:36 +00001916 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete,
1917 SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00001918 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00001919 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001920
Douglas Gregorba70ab62010-04-16 22:17:36 +00001921 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1922 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001923
John McCall2de56d12010-08-25 11:45:40 +00001924 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00001925 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001926
Douglas Gregorba70ab62010-04-16 22:17:36 +00001927 // Create an implicit call expr that calls it.
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001928 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00001929 if (Result.isInvalid())
1930 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001931
Douglas Gregorf2ae5262011-01-20 00:18:04 +00001932 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00001933 }
1934 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001935}
Douglas Gregorba70ab62010-04-16 22:17:36 +00001936
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001937/// PerformImplicitConversion - Perform an implicit conversion of the
1938/// expression From to the type ToType using the pre-computed implicit
John Wiegley429bb272011-04-08 18:41:53 +00001939/// conversion sequence ICS. Returns the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001940/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001941/// used in the error message.
John Wiegley429bb272011-04-08 18:41:53 +00001942ExprResult
1943Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001944 const ImplicitConversionSequence &ICS,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001945 AssignmentAction Action, bool CStyle) {
John McCall1d318332010-01-12 00:44:57 +00001946 switch (ICS.getKind()) {
John Wiegley429bb272011-04-08 18:41:53 +00001947 case ImplicitConversionSequence::StandardConversion: {
1948 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
1949 Action, CStyle);
1950 if (Res.isInvalid())
1951 return ExprError();
1952 From = Res.take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001953 break;
John Wiegley429bb272011-04-08 18:41:53 +00001954 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001955
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001956 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001957
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001958 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00001959 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001960 QualType BeforeToType;
1961 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00001962 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001963
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001964 // If the user-defined conversion is specified by a conversion function,
1965 // the initial standard conversion sequence converts the source type to
1966 // the implicit object parameter of the conversion function.
1967 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00001968 } else {
1969 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00001970 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001971 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001972 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001973 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001974 // initial standard conversion sequence converts the source type to the
1975 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001976 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1977 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001978 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00001979 // Watch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001980 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley429bb272011-04-08 18:41:53 +00001981 ExprResult Res =
1982 PerformImplicitConversion(From, BeforeToType,
1983 ICS.UserDefined.Before, AA_Converting,
1984 CStyle);
1985 if (Res.isInvalid())
1986 return ExprError();
1987 From = Res.take();
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001988 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001989
1990 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00001991 = BuildCXXCastArgument(*this,
1992 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00001993 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00001994 CastKind, cast<CXXMethodDecl>(FD),
1995 ICS.UserDefined.FoundConversionFunction,
John McCall9ae2f072010-08-23 23:25:46 +00001996 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00001997
1998 if (CastArg.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001999 return ExprError();
Eli Friedmand8889622009-11-27 04:41:50 +00002000
John Wiegley429bb272011-04-08 18:41:53 +00002001 From = CastArg.take();
Eli Friedmand8889622009-11-27 04:41:50 +00002002
Eli Friedmand8889622009-11-27 04:41:50 +00002003 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002004 AA_Converting, CStyle);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00002005 }
John McCall1d318332010-01-12 00:44:57 +00002006
2007 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00002008 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00002009 PDiag(diag::err_typecheck_ambiguous_condition)
2010 << From->getSourceRange());
John Wiegley429bb272011-04-08 18:41:53 +00002011 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002012
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002013 case ImplicitConversionSequence::EllipsisConversion:
2014 assert(false && "Cannot perform an ellipsis conversion");
John Wiegley429bb272011-04-08 18:41:53 +00002015 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002016
2017 case ImplicitConversionSequence::BadConversion:
John Wiegley429bb272011-04-08 18:41:53 +00002018 return ExprError();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002019 }
2020
2021 // Everything went well.
John Wiegley429bb272011-04-08 18:41:53 +00002022 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002023}
2024
2025/// PerformImplicitConversion - Perform an implicit conversion of the
2026/// expression From to the type ToType by following the standard
John Wiegley429bb272011-04-08 18:41:53 +00002027/// conversion sequence SCS. Returns the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00002028/// expression. Flavor is the context in which we're performing this
2029/// conversion, for use in error messages.
John Wiegley429bb272011-04-08 18:41:53 +00002030ExprResult
2031Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00002032 const StandardConversionSequence& SCS,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002033 AssignmentAction Action, bool CStyle) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002034 // Overall FIXME: we are recomputing too many types here and doing far too
2035 // much extra work. What this means is that we need to keep track of more
2036 // information that is computed when we try the implicit conversion initially,
2037 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002038 QualType FromType = From->getType();
2039
Douglas Gregor225c41e2008-11-03 19:09:14 +00002040 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00002041 // FIXME: When can ToType be a reference type?
2042 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002043 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00002044 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002045 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00002046 MultiExprArg(*this, &From, 1),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002047 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002048 ConstructorArgs))
John Wiegley429bb272011-04-08 18:41:53 +00002049 return ExprError();
2050 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2051 ToType, SCS.CopyConstructor,
2052 move_arg(ConstructorArgs),
2053 /*ZeroInit*/ false,
2054 CXXConstructExpr::CK_Complete,
2055 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002056 }
John Wiegley429bb272011-04-08 18:41:53 +00002057 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2058 ToType, SCS.CopyConstructor,
2059 MultiExprArg(*this, &From, 1),
2060 /*ZeroInit*/ false,
2061 CXXConstructExpr::CK_Complete,
2062 SourceRange());
Douglas Gregor225c41e2008-11-03 19:09:14 +00002063 }
2064
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002065 // Resolve overloaded function references.
2066 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2067 DeclAccessPair Found;
2068 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2069 true, Found);
2070 if (!Fn)
John Wiegley429bb272011-04-08 18:41:53 +00002071 return ExprError();
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002072
2073 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
John Wiegley429bb272011-04-08 18:41:53 +00002074 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002075
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002076 From = FixOverloadedFunctionReference(From, Found, Fn);
2077 FromType = From->getType();
2078 }
2079
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002080 // Perform the first implicit conversion.
2081 switch (SCS.First) {
2082 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002083 // Nothing to do.
2084 break;
2085
John McCallf6a16482010-12-04 03:47:34 +00002086 case ICK_Lvalue_To_Rvalue:
2087 // Should this get its own ICK?
2088 if (From->getObjectKind() == OK_ObjCProperty) {
John Wiegley429bb272011-04-08 18:41:53 +00002089 ExprResult FromRes = ConvertPropertyForRValue(From);
2090 if (FromRes.isInvalid())
2091 return ExprError();
2092 From = FromRes.take();
John McCall241d5582010-12-07 22:54:16 +00002093 if (!From->isGLValue()) break;
John McCallf6a16482010-12-04 03:47:34 +00002094 }
2095
Chandler Carruth35001ca2011-02-17 21:10:52 +00002096 // Check for trivial buffer overflows.
Ted Kremenek3aea4da2011-03-01 18:41:00 +00002097 CheckArrayAccess(From);
Chandler Carruth35001ca2011-02-17 21:10:52 +00002098
John McCallf6a16482010-12-04 03:47:34 +00002099 FromType = FromType.getUnqualifiedType();
2100 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2101 From, 0, VK_RValue);
2102 break;
2103
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002104 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002105 FromType = Context.getArrayDecayedType(FromType);
John Wiegley429bb272011-04-08 18:41:53 +00002106 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay).take();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002107 break;
2108
2109 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002110 FromType = Context.getPointerType(FromType);
John Wiegley429bb272011-04-08 18:41:53 +00002111 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002112 break;
2113
2114 default:
2115 assert(false && "Improper first standard conversion");
2116 break;
2117 }
2118
2119 // Perform the second implicit conversion
2120 switch (SCS.Second) {
2121 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002122 // If both sides are functions (or pointers/references to them), there could
2123 // be incompatible exception declarations.
2124 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002125 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002126 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002127 break;
2128
Douglas Gregor43c79c22009-12-09 00:47:37 +00002129 case ICK_NoReturn_Adjustment:
2130 // If both sides are functions (or pointers/references to them), there could
2131 // be incompatible exception declarations.
2132 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002133 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002134
John Wiegley429bb272011-04-08 18:41:53 +00002135 From = ImpCastExprToType(From, ToType, CK_NoOp).take();
Douglas Gregor43c79c22009-12-09 00:47:37 +00002136 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002137
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002138 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002139 case ICK_Integral_Conversion:
John Wiegley429bb272011-04-08 18:41:53 +00002140 From = ImpCastExprToType(From, ToType, CK_IntegralCast).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002141 break;
2142
2143 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002144 case ICK_Floating_Conversion:
John Wiegley429bb272011-04-08 18:41:53 +00002145 From = ImpCastExprToType(From, ToType, CK_FloatingCast).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002146 break;
2147
2148 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00002149 case ICK_Complex_Conversion: {
2150 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2151 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2152 CastKind CK;
2153 if (FromEl->isRealFloatingType()) {
2154 if (ToEl->isRealFloatingType())
2155 CK = CK_FloatingComplexCast;
2156 else
2157 CK = CK_FloatingComplexToIntegralComplex;
2158 } else if (ToEl->isRealFloatingType()) {
2159 CK = CK_IntegralComplexToFloatingComplex;
2160 } else {
2161 CK = CK_IntegralComplexCast;
2162 }
John Wiegley429bb272011-04-08 18:41:53 +00002163 From = ImpCastExprToType(From, ToType, CK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002164 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00002165 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002166
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002167 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002168 if (ToType->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00002169 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002170 else
John Wiegley429bb272011-04-08 18:41:53 +00002171 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002172 break;
2173
Douglas Gregorf9201e02009-02-11 23:02:49 +00002174 case ICK_Compatible_Conversion:
John Wiegley429bb272011-04-08 18:41:53 +00002175 From = ImpCastExprToType(From, ToType, CK_NoOp).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002176 break;
2177
Anders Carlsson61faec12009-09-12 04:46:44 +00002178 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00002179 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002180 // Diagnose incompatible Objective-C conversions
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002181 if (Action == AA_Initializing)
2182 Diag(From->getSourceRange().getBegin(),
2183 diag::ext_typecheck_convert_incompatible_pointer)
2184 << ToType << From->getType() << Action
2185 << From->getSourceRange();
2186 else
2187 Diag(From->getSourceRange().getBegin(),
2188 diag::ext_typecheck_convert_incompatible_pointer)
2189 << From->getType() << ToType << Action
2190 << From->getSourceRange();
Douglas Gregor45920e82008-12-19 17:40:08 +00002191 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002192
John McCalldaa8e4e2010-11-15 09:13:47 +00002193 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002194 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002195 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002196 return ExprError();
2197 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002198 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00002199 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002200
Anders Carlsson61faec12009-09-12 04:46:44 +00002201 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002202 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002203 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002204 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002205 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002206 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002207 return ExprError();
2208 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath).take();
Anders Carlsson61faec12009-09-12 04:46:44 +00002209 break;
2210 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002211
Abramo Bagnara737d5442011-04-07 09:26:19 +00002212 case ICK_Boolean_Conversion:
John Wiegley429bb272011-04-08 18:41:53 +00002213 From = ImpCastExprToType(From, Context.BoolTy,
2214 ScalarTypeToBooleanCastKind(FromType)).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002215 break;
2216
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002217 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002218 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002219 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002220 ToType.getNonReferenceType(),
2221 From->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002222 From->getSourceRange(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002223 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002224 CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002225 return ExprError();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002226
John Wiegley429bb272011-04-08 18:41:53 +00002227 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
John McCall2de56d12010-08-25 11:45:40 +00002228 CK_DerivedToBase, CastCategory(From),
John Wiegley429bb272011-04-08 18:41:53 +00002229 &BasePath).take();
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002230 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002231 }
2232
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002233 case ICK_Vector_Conversion:
John Wiegley429bb272011-04-08 18:41:53 +00002234 From = ImpCastExprToType(From, ToType, CK_BitCast).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002235 break;
2236
2237 case ICK_Vector_Splat:
John Wiegley429bb272011-04-08 18:41:53 +00002238 From = ImpCastExprToType(From, ToType, CK_VectorSplat).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002239 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002240
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002241 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002242 // Case 1. x -> _Complex y
2243 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2244 QualType ElType = ToComplex->getElementType();
2245 bool isFloatingComplex = ElType->isRealFloatingType();
2246
2247 // x -> y
2248 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2249 // do nothing
2250 } else if (From->getType()->isRealFloatingType()) {
John Wiegley429bb272011-04-08 18:41:53 +00002251 From = ImpCastExprToType(From, ElType,
2252 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002253 } else {
2254 assert(From->getType()->isIntegerType());
John Wiegley429bb272011-04-08 18:41:53 +00002255 From = ImpCastExprToType(From, ElType,
2256 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002257 }
2258 // y -> _Complex y
John Wiegley429bb272011-04-08 18:41:53 +00002259 From = ImpCastExprToType(From, ToType,
John McCalldaa8e4e2010-11-15 09:13:47 +00002260 isFloatingComplex ? CK_FloatingRealToComplex
John Wiegley429bb272011-04-08 18:41:53 +00002261 : CK_IntegralRealToComplex).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002262
2263 // Case 2. _Complex x -> y
2264 } else {
2265 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2266 assert(FromComplex);
2267
2268 QualType ElType = FromComplex->getElementType();
2269 bool isFloatingComplex = ElType->isRealFloatingType();
2270
2271 // _Complex x -> x
John Wiegley429bb272011-04-08 18:41:53 +00002272 From = ImpCastExprToType(From, ElType,
John McCalldaa8e4e2010-11-15 09:13:47 +00002273 isFloatingComplex ? CK_FloatingComplexToReal
John Wiegley429bb272011-04-08 18:41:53 +00002274 : CK_IntegralComplexToReal).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002275
2276 // x -> y
2277 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2278 // do nothing
2279 } else if (ToType->isRealFloatingType()) {
John Wiegley429bb272011-04-08 18:41:53 +00002280 From = ImpCastExprToType(From, ToType,
2281 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002282 } else {
2283 assert(ToType->isIntegerType());
John Wiegley429bb272011-04-08 18:41:53 +00002284 From = ImpCastExprToType(From, ToType,
2285 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002286 }
2287 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002288 break;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002289
2290 case ICK_Block_Pointer_Conversion: {
John Wiegley429bb272011-04-08 18:41:53 +00002291 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2292 VK_RValue).take();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002293 break;
2294 }
2295
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002296 case ICK_TransparentUnionConversion: {
John Wiegley429bb272011-04-08 18:41:53 +00002297 ExprResult FromRes = Owned(From);
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002298 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002299 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2300 if (FromRes.isInvalid())
2301 return ExprError();
2302 From = FromRes.take();
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002303 assert ((ConvTy == Sema::Compatible) &&
2304 "Improper transparent union conversion");
2305 (void)ConvTy;
2306 break;
2307 }
2308
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002309 case ICK_Lvalue_To_Rvalue:
2310 case ICK_Array_To_Pointer:
2311 case ICK_Function_To_Pointer:
2312 case ICK_Qualification:
2313 case ICK_Num_Conversion_Kinds:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002314 assert(false && "Improper second standard conversion");
2315 break;
2316 }
2317
2318 switch (SCS.Third) {
2319 case ICK_Identity:
2320 // Nothing to do.
2321 break;
2322
Sebastian Redl906082e2010-07-20 04:20:21 +00002323 case ICK_Qualification: {
2324 // The qualification keeps the category of the inner expression, unless the
2325 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002326 ExprValueKind VK = ToType->isReferenceType() ?
2327 CastCategory(From) : VK_RValue;
John Wiegley429bb272011-04-08 18:41:53 +00002328 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2329 CK_NoOp, VK).take();
Douglas Gregora9bff302010-02-28 18:30:25 +00002330
Douglas Gregor069a6da2011-03-14 16:13:32 +00002331 if (SCS.DeprecatedStringLiteralToCharPtr &&
2332 !getLangOptions().WritableStrings)
Douglas Gregora9bff302010-02-28 18:30:25 +00002333 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2334 << ToType.getNonReferenceType();
2335
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002336 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002337 }
2338
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002339 default:
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002340 assert(false && "Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002341 break;
2342 }
2343
John Wiegley429bb272011-04-08 18:41:53 +00002344 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002345}
2346
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002347ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002348 SourceLocation KWLoc,
2349 ParsedType Ty,
2350 SourceLocation RParen) {
2351 TypeSourceInfo *TSInfo;
2352 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002353
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002354 if (!TSInfo)
2355 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002356 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002357}
2358
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002359/// \brief Check the completeness of a type in a unary type trait.
2360///
2361/// If the particular type trait requires a complete type, tries to complete
2362/// it. If completing the type fails, a diagnostic is emitted and false
2363/// returned. If completing the type succeeds or no completion was required,
2364/// returns true.
2365static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2366 UnaryTypeTrait UTT,
2367 SourceLocation Loc,
2368 QualType ArgTy) {
2369 // C++0x [meta.unary.prop]p3:
2370 // For all of the class templates X declared in this Clause, instantiating
2371 // that template with a template argument that is a class template
2372 // specialization may result in the implicit instantiation of the template
2373 // argument if and only if the semantics of X require that the argument
2374 // must be a complete type.
2375 // We apply this rule to all the type trait expressions used to implement
2376 // these class templates. We also try to follow any GCC documented behavior
2377 // in these expressions to ensure portability of standard libraries.
2378 switch (UTT) {
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002379 // is_complete_type somewhat obviously cannot require a complete type.
2380 case UTT_IsCompleteType:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002381 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002382
2383 // These traits are modeled on the type predicates in C++0x
2384 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2385 // requiring a complete type, as whether or not they return true cannot be
2386 // impacted by the completeness of the type.
2387 case UTT_IsVoid:
2388 case UTT_IsIntegral:
2389 case UTT_IsFloatingPoint:
2390 case UTT_IsArray:
2391 case UTT_IsPointer:
2392 case UTT_IsLvalueReference:
2393 case UTT_IsRvalueReference:
2394 case UTT_IsMemberFunctionPointer:
2395 case UTT_IsMemberObjectPointer:
2396 case UTT_IsEnum:
2397 case UTT_IsUnion:
2398 case UTT_IsClass:
2399 case UTT_IsFunction:
2400 case UTT_IsReference:
2401 case UTT_IsArithmetic:
2402 case UTT_IsFundamental:
2403 case UTT_IsObject:
2404 case UTT_IsScalar:
2405 case UTT_IsCompound:
2406 case UTT_IsMemberPointer:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002407 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002408
2409 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2410 // which requires some of its traits to have the complete type. However,
2411 // the completeness of the type cannot impact these traits' semantics, and
2412 // so they don't require it. This matches the comments on these traits in
2413 // Table 49.
2414 case UTT_IsConst:
2415 case UTT_IsVolatile:
2416 case UTT_IsSigned:
2417 case UTT_IsUnsigned:
2418 return true;
2419
2420 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002421 // applied to a complete type.
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002422 case UTT_IsTrivial:
2423 case UTT_IsStandardLayout:
2424 case UTT_IsPOD:
2425 case UTT_IsLiteral:
2426 case UTT_IsEmpty:
2427 case UTT_IsPolymorphic:
2428 case UTT_IsAbstract:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002429 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002430
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002431 // These trait expressions are designed to help implement predicates in
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002432 // [meta.unary.prop] despite not being named the same. They are specified
2433 // by both GCC and the Embarcadero C++ compiler, and require the complete
2434 // type due to the overarching C++0x type predicates being implemented
2435 // requiring the complete type.
2436 case UTT_HasNothrowAssign:
2437 case UTT_HasNothrowConstructor:
2438 case UTT_HasNothrowCopy:
2439 case UTT_HasTrivialAssign:
Sean Hunt023df372011-05-09 18:22:59 +00002440 case UTT_HasTrivialDefaultConstructor:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002441 case UTT_HasTrivialCopy:
2442 case UTT_HasTrivialDestructor:
2443 case UTT_HasVirtualDestructor:
2444 // Arrays of unknown bound are expressly allowed.
2445 QualType ElTy = ArgTy;
2446 if (ArgTy->isIncompleteArrayType())
2447 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2448
2449 // The void type is expressly allowed.
2450 if (ElTy->isVoidType())
2451 return true;
2452
2453 return !S.RequireCompleteType(
2454 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleycf566412011-04-28 02:06:46 +00002455 }
Chandler Carruth73e0a912011-05-01 07:23:17 +00002456 llvm_unreachable("Type trait not handled by switch");
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002457}
2458
2459static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2460 SourceLocation KeyLoc, QualType T) {
Chandler Carruthd064c702011-05-01 08:41:10 +00002461 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleycf566412011-04-28 02:06:46 +00002462
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002463 ASTContext &C = Self.Context;
2464 switch(UTT) {
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002465 // Type trait expressions corresponding to the primary type category
2466 // predicates in C++0x [meta.unary.cat].
2467 case UTT_IsVoid:
2468 return T->isVoidType();
2469 case UTT_IsIntegral:
2470 return T->isIntegralType(C);
2471 case UTT_IsFloatingPoint:
2472 return T->isFloatingType();
2473 case UTT_IsArray:
2474 return T->isArrayType();
2475 case UTT_IsPointer:
2476 return T->isPointerType();
2477 case UTT_IsLvalueReference:
2478 return T->isLValueReferenceType();
2479 case UTT_IsRvalueReference:
2480 return T->isRValueReferenceType();
2481 case UTT_IsMemberFunctionPointer:
2482 return T->isMemberFunctionPointerType();
2483 case UTT_IsMemberObjectPointer:
2484 return T->isMemberDataPointerType();
2485 case UTT_IsEnum:
2486 return T->isEnumeralType();
Chandler Carruth28eeb382011-05-01 06:11:03 +00002487 case UTT_IsUnion:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002488 return T->isUnionType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002489 case UTT_IsClass:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002490 return T->isClassType() || T->isStructureType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002491 case UTT_IsFunction:
2492 return T->isFunctionType();
2493
2494 // Type trait expressions which correspond to the convenient composition
2495 // predicates in C++0x [meta.unary.comp].
2496 case UTT_IsReference:
2497 return T->isReferenceType();
2498 case UTT_IsArithmetic:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002499 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002500 case UTT_IsFundamental:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002501 return T->isFundamentalType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002502 case UTT_IsObject:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002503 return T->isObjectType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002504 case UTT_IsScalar:
Chandler Carruthcec0ced2011-05-01 09:29:55 +00002505 return T->isScalarType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002506 case UTT_IsCompound:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002507 return T->isCompoundType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002508 case UTT_IsMemberPointer:
2509 return T->isMemberPointerType();
2510
2511 // Type trait expressions which correspond to the type property predicates
2512 // in C++0x [meta.unary.prop].
2513 case UTT_IsConst:
2514 return T.isConstQualified();
2515 case UTT_IsVolatile:
2516 return T.isVolatileQualified();
2517 case UTT_IsTrivial:
2518 return T->isTrivialType();
2519 case UTT_IsStandardLayout:
2520 return T->isStandardLayoutType();
2521 case UTT_IsPOD:
2522 return T->isPODType();
2523 case UTT_IsLiteral:
2524 return T->isLiteralType();
2525 case UTT_IsEmpty:
2526 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2527 return !RD->isUnion() && RD->isEmpty();
2528 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002529 case UTT_IsPolymorphic:
Chandler Carruth28eeb382011-05-01 06:11:03 +00002530 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2531 return RD->isPolymorphic();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002532 return false;
2533 case UTT_IsAbstract:
Chandler Carruth28eeb382011-05-01 06:11:03 +00002534 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2535 return RD->isAbstract();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002536 return false;
John Wiegley20c0da72011-04-27 23:09:49 +00002537 case UTT_IsSigned:
2538 return T->isSignedIntegerType();
John Wiegley20c0da72011-04-27 23:09:49 +00002539 case UTT_IsUnsigned:
2540 return T->isUnsignedIntegerType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002541
2542 // Type trait expressions which query classes regarding their construction,
2543 // destruction, and copying. Rather than being based directly on the
2544 // related type predicates in the standard, they are specified by both
2545 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
2546 // specifications.
2547 //
2548 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
2549 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Sean Hunt023df372011-05-09 18:22:59 +00002550 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002551 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2552 // If __is_pod (type) is true then the trait is true, else if type is
2553 // a cv class or union type (or array thereof) with a trivial default
2554 // constructor ([class.ctor]) then the trait is true, else it is false.
2555 if (T->isPODType())
2556 return true;
2557 if (const RecordType *RT =
2558 C.getBaseElementType(T)->getAs<RecordType>())
Sean Hunt023df372011-05-09 18:22:59 +00002559 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002560 return false;
2561 case UTT_HasTrivialCopy:
2562 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2563 // If __is_pod (type) is true or type is a reference type then
2564 // the trait is true, else if type is a cv class or union type
2565 // with a trivial copy constructor ([class.copy]) then the trait
2566 // is true, else it is false.
2567 if (T->isPODType() || T->isReferenceType())
2568 return true;
2569 if (const RecordType *RT = T->getAs<RecordType>())
2570 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2571 return false;
2572 case UTT_HasTrivialAssign:
2573 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2574 // If type is const qualified or is a reference type then the
2575 // trait is false. Otherwise if __is_pod (type) is true then the
2576 // trait is true, else if type is a cv class or union type with
2577 // a trivial copy assignment ([class.copy]) then the trait is
2578 // true, else it is false.
2579 // Note: the const and reference restrictions are interesting,
2580 // given that const and reference members don't prevent a class
2581 // from having a trivial copy assignment operator (but do cause
2582 // errors if the copy assignment operator is actually used, q.v.
2583 // [class.copy]p12).
2584
2585 if (C.getBaseElementType(T).isConstQualified())
2586 return false;
2587 if (T->isPODType())
2588 return true;
2589 if (const RecordType *RT = T->getAs<RecordType>())
2590 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2591 return false;
2592 case UTT_HasTrivialDestructor:
2593 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2594 // If __is_pod (type) is true or type is a reference type
2595 // then the trait is true, else if type is a cv class or union
2596 // type (or array thereof) with a trivial destructor
2597 // ([class.dtor]) then the trait is true, else it is
2598 // false.
2599 if (T->isPODType() || T->isReferenceType())
2600 return true;
2601 if (const RecordType *RT =
2602 C.getBaseElementType(T)->getAs<RecordType>())
2603 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2604 return false;
2605 // TODO: Propagate nothrowness for implicitly declared special members.
2606 case UTT_HasNothrowAssign:
2607 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2608 // If type is const qualified or is a reference type then the
2609 // trait is false. Otherwise if __has_trivial_assign (type)
2610 // is true then the trait is true, else if type is a cv class
2611 // or union type with copy assignment operators that are known
2612 // not to throw an exception then the trait is true, else it is
2613 // false.
2614 if (C.getBaseElementType(T).isConstQualified())
2615 return false;
2616 if (T->isReferenceType())
2617 return false;
2618 if (T->isPODType())
2619 return true;
2620 if (const RecordType *RT = T->getAs<RecordType>()) {
2621 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2622 if (RD->hasTrivialCopyAssignment())
2623 return true;
2624
2625 bool FoundAssign = false;
2626 bool AllNoThrow = true;
2627 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00002628 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2629 Sema::LookupOrdinaryName);
2630 if (Self.LookupQualifiedName(Res, RD)) {
2631 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2632 Op != OpEnd; ++Op) {
2633 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2634 if (Operator->isCopyAssignmentOperator()) {
2635 FoundAssign = true;
2636 const FunctionProtoType *CPT
2637 = Operator->getType()->getAs<FunctionProtoType>();
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002638 if (!CPT->isNothrow(Self.Context)) {
Sebastian Redlf8aca862010-09-14 23:40:14 +00002639 AllNoThrow = false;
2640 break;
2641 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002642 }
2643 }
2644 }
2645
2646 return FoundAssign && AllNoThrow;
2647 }
2648 return false;
2649 case UTT_HasNothrowCopy:
2650 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2651 // If __has_trivial_copy (type) is true then the trait is true, else
2652 // if type is a cv class or union type with copy constructors that are
2653 // known not to throw an exception then the trait is true, else it is
2654 // false.
2655 if (T->isPODType() || T->isReferenceType())
2656 return true;
2657 if (const RecordType *RT = T->getAs<RecordType>()) {
2658 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2659 if (RD->hasTrivialCopyConstructor())
2660 return true;
2661
2662 bool FoundConstructor = false;
2663 bool AllNoThrow = true;
2664 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002665 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00002666 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002667 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002668 // A template constructor is never a copy constructor.
2669 // FIXME: However, it may actually be selected at the actual overload
2670 // resolution point.
2671 if (isa<FunctionTemplateDecl>(*Con))
2672 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002673 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2674 if (Constructor->isCopyConstructor(FoundTQs)) {
2675 FoundConstructor = true;
2676 const FunctionProtoType *CPT
2677 = Constructor->getType()->getAs<FunctionProtoType>();
Sebastian Redl60618fa2011-03-12 11:50:43 +00002678 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redl751025d2010-09-13 22:02:47 +00002679 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002680 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002681 AllNoThrow = false;
2682 break;
2683 }
2684 }
2685 }
2686
2687 return FoundConstructor && AllNoThrow;
2688 }
2689 return false;
2690 case UTT_HasNothrowConstructor:
2691 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2692 // If __has_trivial_constructor (type) is true then the trait is
2693 // true, else if type is a cv class or union type (or array
2694 // thereof) with a default constructor that is known not to
2695 // throw an exception then the trait is true, else it is false.
2696 if (T->isPODType())
2697 return true;
2698 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2699 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Hunt023df372011-05-09 18:22:59 +00002700 if (RD->hasTrivialDefaultConstructor())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002701 return true;
2702
Sebastian Redl751025d2010-09-13 22:02:47 +00002703 DeclContext::lookup_const_iterator Con, ConEnd;
2704 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2705 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00002706 // FIXME: In C++0x, a constructor template can be a default constructor.
2707 if (isa<FunctionTemplateDecl>(*Con))
2708 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00002709 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2710 if (Constructor->isDefaultConstructor()) {
2711 const FunctionProtoType *CPT
2712 = Constructor->getType()->getAs<FunctionProtoType>();
2713 // TODO: check whether evaluating default arguments can throw.
2714 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002715 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
Sebastian Redl751025d2010-09-13 22:02:47 +00002716 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002717 }
2718 }
2719 return false;
2720 case UTT_HasVirtualDestructor:
2721 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2722 // If type is a class type with a virtual destructor ([class.dtor])
2723 // then the trait is true, else it is false.
2724 if (const RecordType *Record = T->getAs<RecordType>()) {
2725 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00002726 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002727 return Destructor->isVirtual();
2728 }
2729 return false;
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002730
2731 // These type trait expressions are modeled on the specifications for the
2732 // Embarcadero C++0x type trait functions:
2733 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
2734 case UTT_IsCompleteType:
2735 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
2736 // Returns True if and only if T is a complete type at the point of the
2737 // function call.
2738 return !T->isIncompleteType();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002739 }
Chandler Carruth83f563c2011-05-01 07:44:17 +00002740 llvm_unreachable("Type trait not covered by switch");
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002741}
2742
2743ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002744 SourceLocation KWLoc,
2745 TypeSourceInfo *TSInfo,
2746 SourceLocation RParen) {
2747 QualType T = TSInfo->getType();
Chandler Carrutheb65a102011-04-30 10:07:32 +00002748 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
2749 return ExprError();
Sebastian Redl64b45f72009-01-05 20:52:13 +00002750
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002751 bool Value = false;
2752 if (!T->isDependentType())
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002753 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002754
2755 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00002756 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00002757}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00002758
Francois Pichet6ad6f282010-12-07 00:08:36 +00002759ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
2760 SourceLocation KWLoc,
2761 ParsedType LhsTy,
2762 ParsedType RhsTy,
2763 SourceLocation RParen) {
2764 TypeSourceInfo *LhsTSInfo;
2765 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
2766 if (!LhsTSInfo)
2767 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
2768
2769 TypeSourceInfo *RhsTSInfo;
2770 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
2771 if (!RhsTSInfo)
2772 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
2773
2774 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
2775}
2776
2777static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
2778 QualType LhsT, QualType RhsT,
2779 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00002780 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
2781 "Cannot evaluate traits of dependent types");
Francois Pichet6ad6f282010-12-07 00:08:36 +00002782
2783 switch(BTT) {
John McCalld89d30f2011-01-28 22:02:36 +00002784 case BTT_IsBaseOf: {
Francois Pichet6ad6f282010-12-07 00:08:36 +00002785 // C++0x [meta.rel]p2
John McCalld89d30f2011-01-28 22:02:36 +00002786 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet6ad6f282010-12-07 00:08:36 +00002787 // Base and Derived are not unions and name the same class type without
2788 // regard to cv-qualifiers.
Francois Pichet6ad6f282010-12-07 00:08:36 +00002789
John McCalld89d30f2011-01-28 22:02:36 +00002790 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
2791 if (!lhsRecord) return false;
2792
2793 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
2794 if (!rhsRecord) return false;
2795
2796 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
2797 == (lhsRecord == rhsRecord));
2798
2799 if (lhsRecord == rhsRecord)
2800 return !lhsRecord->getDecl()->isUnion();
2801
2802 // C++0x [meta.rel]p2:
2803 // If Base and Derived are class types and are different types
2804 // (ignoring possible cv-qualifiers) then Derived shall be a
2805 // complete type.
2806 if (Self.RequireCompleteType(KeyLoc, RhsT,
2807 diag::err_incomplete_type_used_in_type_trait_expr))
2808 return false;
2809
2810 return cast<CXXRecordDecl>(rhsRecord->getDecl())
2811 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
2812 }
John Wiegley20c0da72011-04-27 23:09:49 +00002813 case BTT_IsSame:
2814 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichetf1872372010-12-08 22:35:30 +00002815 case BTT_TypeCompatible:
2816 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
2817 RhsT.getUnqualifiedType());
John Wiegley20c0da72011-04-27 23:09:49 +00002818 case BTT_IsConvertible:
Douglas Gregor9f361132011-01-27 20:28:01 +00002819 case BTT_IsConvertibleTo: {
2820 // C++0x [meta.rel]p4:
2821 // Given the following function prototype:
2822 //
2823 // template <class T>
2824 // typename add_rvalue_reference<T>::type create();
2825 //
2826 // the predicate condition for a template specialization
2827 // is_convertible<From, To> shall be satisfied if and only if
2828 // the return expression in the following code would be
2829 // well-formed, including any implicit conversions to the return
2830 // type of the function:
2831 //
2832 // To test() {
2833 // return create<From>();
2834 // }
2835 //
2836 // Access checking is performed as if in a context unrelated to To and
2837 // From. Only the validity of the immediate context of the expression
2838 // of the return-statement (including conversions to the return type)
2839 // is considered.
2840 //
2841 // We model the initialization as a copy-initialization of a temporary
2842 // of the appropriate type, which for this expression is identical to the
2843 // return statement (since NRVO doesn't apply).
2844 if (LhsT->isObjectType() || LhsT->isFunctionType())
2845 LhsT = Self.Context.getRValueReferenceType(LhsT);
2846
2847 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorb608b982011-01-28 02:26:04 +00002848 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor9f361132011-01-27 20:28:01 +00002849 Expr::getValueKindForType(LhsT));
2850 Expr *FromPtr = &From;
2851 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
2852 SourceLocation()));
2853
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00002854 // Perform the initialization within a SFINAE trap at translation unit
2855 // scope.
2856 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
2857 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor9f361132011-01-27 20:28:01 +00002858 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
2859 if (Init.getKind() == InitializationSequence::FailedSequence)
2860 return false;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00002861
Douglas Gregor9f361132011-01-27 20:28:01 +00002862 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
2863 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
2864 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00002865 }
2866 llvm_unreachable("Unknown type trait or not implemented");
2867}
2868
2869ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
2870 SourceLocation KWLoc,
2871 TypeSourceInfo *LhsTSInfo,
2872 TypeSourceInfo *RhsTSInfo,
2873 SourceLocation RParen) {
2874 QualType LhsT = LhsTSInfo->getType();
2875 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002876
John McCalld89d30f2011-01-28 22:02:36 +00002877 if (BTT == BTT_TypeCompatible) {
Francois Pichetf1872372010-12-08 22:35:30 +00002878 if (getLangOptions().CPlusPlus) {
2879 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
2880 << SourceRange(KWLoc, RParen);
2881 return ExprError();
2882 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00002883 }
2884
2885 bool Value = false;
2886 if (!LhsT->isDependentType() && !RhsT->isDependentType())
2887 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
2888
Francois Pichetf1872372010-12-08 22:35:30 +00002889 // Select trait result type.
2890 QualType ResultType;
2891 switch (BTT) {
Francois Pichetf1872372010-12-08 22:35:30 +00002892 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
John Wiegley20c0da72011-04-27 23:09:49 +00002893 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
2894 case BTT_IsSame: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00002895 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor9f361132011-01-27 20:28:01 +00002896 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00002897 }
2898
Francois Pichet6ad6f282010-12-07 00:08:36 +00002899 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
2900 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00002901 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00002902}
2903
John Wiegley21ff2e52011-04-28 00:16:57 +00002904ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
2905 SourceLocation KWLoc,
2906 ParsedType Ty,
2907 Expr* DimExpr,
2908 SourceLocation RParen) {
2909 TypeSourceInfo *TSInfo;
2910 QualType T = GetTypeFromParser(Ty, &TSInfo);
2911 if (!TSInfo)
2912 TSInfo = Context.getTrivialTypeSourceInfo(T);
2913
2914 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
2915}
2916
2917static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
2918 QualType T, Expr *DimExpr,
2919 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00002920 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley21ff2e52011-04-28 00:16:57 +00002921
2922 switch(ATT) {
2923 case ATT_ArrayRank:
2924 if (T->isArrayType()) {
2925 unsigned Dim = 0;
2926 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
2927 ++Dim;
2928 T = AT->getElementType();
2929 }
2930 return Dim;
John Wiegley21ff2e52011-04-28 00:16:57 +00002931 }
John Wiegleycf566412011-04-28 02:06:46 +00002932 return 0;
2933
John Wiegley21ff2e52011-04-28 00:16:57 +00002934 case ATT_ArrayExtent: {
2935 llvm::APSInt Value;
2936 uint64_t Dim;
John Wiegleycf566412011-04-28 02:06:46 +00002937 if (DimExpr->isIntegerConstantExpr(Value, Self.Context, 0, false)) {
2938 if (Value < llvm::APSInt(Value.getBitWidth(), Value.isUnsigned())) {
2939 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
2940 DimExpr->getSourceRange();
2941 return false;
2942 }
John Wiegley21ff2e52011-04-28 00:16:57 +00002943 Dim = Value.getLimitedValue();
John Wiegleycf566412011-04-28 02:06:46 +00002944 } else {
2945 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
2946 DimExpr->getSourceRange();
2947 return false;
2948 }
John Wiegley21ff2e52011-04-28 00:16:57 +00002949
2950 if (T->isArrayType()) {
2951 unsigned D = 0;
2952 bool Matched = false;
2953 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
2954 if (Dim == D) {
2955 Matched = true;
2956 break;
2957 }
2958 ++D;
2959 T = AT->getElementType();
2960 }
2961
John Wiegleycf566412011-04-28 02:06:46 +00002962 if (Matched && T->isArrayType()) {
2963 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
2964 return CAT->getSize().getLimitedValue();
2965 }
John Wiegley21ff2e52011-04-28 00:16:57 +00002966 }
John Wiegleycf566412011-04-28 02:06:46 +00002967 return 0;
John Wiegley21ff2e52011-04-28 00:16:57 +00002968 }
2969 }
2970 llvm_unreachable("Unknown type trait or not implemented");
2971}
2972
2973ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
2974 SourceLocation KWLoc,
2975 TypeSourceInfo *TSInfo,
2976 Expr* DimExpr,
2977 SourceLocation RParen) {
2978 QualType T = TSInfo->getType();
John Wiegley21ff2e52011-04-28 00:16:57 +00002979
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00002980 // FIXME: This should likely be tracked as an APInt to remove any host
2981 // assumptions about the width of size_t on the target.
Chandler Carruthd064c702011-05-01 08:41:10 +00002982 uint64_t Value = 0;
2983 if (!T->isDependentType())
2984 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
2985
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00002986 // While the specification for these traits from the Embarcadero C++
2987 // compiler's documentation says the return type is 'unsigned int', Clang
2988 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
2989 // compiler, there is no difference. On several other platforms this is an
2990 // important distinction.
John Wiegley21ff2e52011-04-28 00:16:57 +00002991 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
Chandler Carruth06207f62011-05-01 07:49:26 +00002992 DimExpr, RParen,
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00002993 Context.getSizeType()));
John Wiegley21ff2e52011-04-28 00:16:57 +00002994}
2995
John Wiegley55262202011-04-25 06:54:41 +00002996ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00002997 SourceLocation KWLoc,
2998 Expr *Queried,
2999 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003000 // If error parsing the expression, ignore.
3001 if (!Queried)
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003002 return ExprError();
John Wiegley55262202011-04-25 06:54:41 +00003003
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003004 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegley55262202011-04-25 06:54:41 +00003005
3006 return move(Result);
3007}
3008
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003009static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3010 switch (ET) {
3011 case ET_IsLValueExpr: return E->isLValue();
3012 case ET_IsRValueExpr: return E->isRValue();
3013 }
3014 llvm_unreachable("Expression trait not covered by switch");
3015}
3016
John Wiegley55262202011-04-25 06:54:41 +00003017ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003018 SourceLocation KWLoc,
3019 Expr *Queried,
3020 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003021 if (Queried->isTypeDependent()) {
3022 // Delay type-checking for type-dependent expressions.
3023 } else if (Queried->getType()->isPlaceholderType()) {
3024 ExprResult PE = CheckPlaceholderExpr(Queried);
3025 if (PE.isInvalid()) return ExprError();
3026 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3027 }
3028
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003029 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf7ef0002011-05-01 08:48:19 +00003030
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003031 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3032 RParen, Context.BoolTy));
John Wiegley55262202011-04-25 06:54:41 +00003033}
3034
John Wiegley429bb272011-04-08 18:41:53 +00003035QualType Sema::CheckPointerToMemberOperands(ExprResult &lex, ExprResult &rex,
John McCallf89e55a2010-11-18 06:31:45 +00003036 ExprValueKind &VK,
3037 SourceLocation Loc,
3038 bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003039 const char *OpSpelling = isIndirect ? "->*" : ".*";
3040 // C++ 5.5p2
3041 // The binary operator .* [p3: ->*] binds its second operand, which shall
3042 // be of type "pointer to member of T" (where T is a completely-defined
3043 // class type) [...]
John Wiegley429bb272011-04-08 18:41:53 +00003044 QualType RType = rex.get()->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003045 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00003046 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003047 Diag(Loc, diag::err_bad_memptr_rhs)
John Wiegley429bb272011-04-08 18:41:53 +00003048 << OpSpelling << RType << rex.get()->getSourceRange();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003049 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00003050 }
Douglas Gregore7450f52009-03-24 19:52:54 +00003051
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003052 QualType Class(MemPtr->getClass(), 0);
3053
Douglas Gregor7d520ba2010-10-13 20:41:14 +00003054 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3055 // member pointer points must be completely-defined. However, there is no
3056 // reason for this semantic distinction, and the rule is not enforced by
3057 // other compilers. Therefore, we do not check this property, as it is
3058 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00003059
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003060 // C++ 5.5p2
3061 // [...] to its first operand, which shall be of class T or of a class of
3062 // which T is an unambiguous and accessible base class. [p3: a pointer to
3063 // such a class]
John Wiegley429bb272011-04-08 18:41:53 +00003064 QualType LType = lex.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003065 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003066 if (const PointerType *Ptr = LType->getAs<PointerType>())
John McCallf89e55a2010-11-18 06:31:45 +00003067 LType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003068 else {
3069 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00003070 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00003071 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003072 return QualType();
3073 }
3074 }
3075
Douglas Gregora4923eb2009-11-16 21:35:15 +00003076 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00003077 // If we want to check the hierarchy, we need a complete type.
3078 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
3079 << OpSpelling << (int)isIndirect)) {
3080 return QualType();
3081 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003082 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00003083 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00003084 // FIXME: Would it be useful to print full ambiguity paths, or is that
3085 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003086 if (!IsDerivedFrom(LType, Class, Paths) ||
3087 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3088 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
John Wiegley429bb272011-04-08 18:41:53 +00003089 << (int)isIndirect << lex.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003090 return QualType();
3091 }
Eli Friedman3005efe2010-01-16 00:00:48 +00003092 // Cast LHS to type of use.
3093 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
John McCall5baba9d2010-08-25 10:28:54 +00003094 ExprValueKind VK =
John Wiegley429bb272011-04-08 18:41:53 +00003095 isIndirect ? VK_RValue : CastCategory(lex.get());
Sebastian Redl906082e2010-07-20 04:20:21 +00003096
John McCallf871d0c2010-08-07 06:22:56 +00003097 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003098 BuildBasePathArray(Paths, BasePath);
John Wiegley429bb272011-04-08 18:41:53 +00003099 lex = ImpCastExprToType(lex.take(), UseType, CK_DerivedToBase, VK, &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003100 }
3101
John Wiegley429bb272011-04-08 18:41:53 +00003102 if (isa<CXXScalarValueInitExpr>(rex.get()->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00003103 // Diagnose use of pointer-to-member type which when used as
3104 // the functional cast in a pointer-to-member expression.
3105 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3106 return QualType();
3107 }
John McCallf89e55a2010-11-18 06:31:45 +00003108
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003109 // C++ 5.5p2
3110 // The result is an object or a function of the type specified by the
3111 // second operand.
3112 // The cv qualifiers are the union of those in the pointer and the left side,
3113 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003114 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00003115 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00003116
Douglas Gregor6b4df912011-01-26 16:40:18 +00003117 // C++0x [expr.mptr.oper]p6:
3118 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003119 // ill-formed if the second operand is a pointer to member function with
3120 // ref-qualifier &. In a ->* expression or in a .* expression whose object
3121 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor6b4df912011-01-26 16:40:18 +00003122 // is a pointer to member function with ref-qualifier &&.
3123 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3124 switch (Proto->getRefQualifier()) {
3125 case RQ_None:
3126 // Do nothing
3127 break;
3128
3129 case RQ_LValue:
John Wiegley429bb272011-04-08 18:41:53 +00003130 if (!isIndirect && !lex.get()->Classify(Context).isLValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003131 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
John Wiegley429bb272011-04-08 18:41:53 +00003132 << RType << 1 << lex.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003133 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003134
Douglas Gregor6b4df912011-01-26 16:40:18 +00003135 case RQ_RValue:
John Wiegley429bb272011-04-08 18:41:53 +00003136 if (isIndirect || !lex.get()->Classify(Context).isRValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003137 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
John Wiegley429bb272011-04-08 18:41:53 +00003138 << RType << 0 << lex.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003139 break;
3140 }
3141 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003142
John McCallf89e55a2010-11-18 06:31:45 +00003143 // C++ [expr.mptr.oper]p6:
3144 // The result of a .* expression whose second operand is a pointer
3145 // to a data member is of the same value category as its
3146 // first operand. The result of a .* expression whose second
3147 // operand is a pointer to a member function is a prvalue. The
3148 // result of an ->* expression is an lvalue if its second operand
3149 // is a pointer to data member and a prvalue otherwise.
John McCall864c0412011-04-26 20:42:42 +00003150 if (Result->isFunctionType()) {
John McCallf89e55a2010-11-18 06:31:45 +00003151 VK = VK_RValue;
John McCall864c0412011-04-26 20:42:42 +00003152 return Context.BoundMemberTy;
3153 } else if (isIndirect) {
John McCallf89e55a2010-11-18 06:31:45 +00003154 VK = VK_LValue;
John McCall864c0412011-04-26 20:42:42 +00003155 } else {
John Wiegley429bb272011-04-08 18:41:53 +00003156 VK = lex.get()->getValueKind();
John McCall864c0412011-04-26 20:42:42 +00003157 }
John McCallf89e55a2010-11-18 06:31:45 +00003158
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003159 return Result;
3160}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003161
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003162/// \brief Try to convert a type to another according to C++0x 5.16p3.
3163///
3164/// This is part of the parameter validation for the ? operator. If either
3165/// value operand is a class type, the two operands are attempted to be
3166/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003167/// It returns true if the program is ill-formed and has already been diagnosed
3168/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003169static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3170 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00003171 bool &HaveConversion,
3172 QualType &ToType) {
3173 HaveConversion = false;
3174 ToType = To->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003175
3176 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003177 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003178 // C++0x 5.16p3
3179 // The process for determining whether an operand expression E1 of type T1
3180 // can be converted to match an operand expression E2 of type T2 is defined
3181 // as follows:
3182 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00003183 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003184 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003185 // E1 can be converted to match E2 if E1 can be implicitly converted to
3186 // type "lvalue reference to T2", subject to the constraint that in the
3187 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003188 QualType T = Self.Context.getLValueReferenceType(ToType);
3189 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003190
Douglas Gregorb70cf442010-03-26 20:14:36 +00003191 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3192 if (InitSeq.isDirectReferenceBinding()) {
3193 ToType = T;
3194 HaveConversion = true;
3195 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003196 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003197
Douglas Gregorb70cf442010-03-26 20:14:36 +00003198 if (InitSeq.isAmbiguous())
3199 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003200 }
John McCallb1bdc622010-02-25 01:37:24 +00003201
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003202 // -- If E2 is an rvalue, or if the conversion above cannot be done:
3203 // -- if E1 and E2 have class type, and the underlying class types are
3204 // the same or one is a base class of the other:
3205 QualType FTy = From->getType();
3206 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003207 const RecordType *FRec = FTy->getAs<RecordType>();
3208 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003209 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003210 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003211 if (FRec && TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003212 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003213 // E1 can be converted to match E2 if the class of T2 is the
3214 // same type as, or a base class of, the class of T1, and
3215 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00003216 if (FRec == TRec || FDerivedFromT) {
3217 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003218 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3219 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3220 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
3221 HaveConversion = true;
3222 return false;
3223 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003224
Douglas Gregorb70cf442010-03-26 20:14:36 +00003225 if (InitSeq.isAmbiguous())
3226 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003227 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003228 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003229
Douglas Gregorb70cf442010-03-26 20:14:36 +00003230 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003231 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003232
Douglas Gregorb70cf442010-03-26 20:14:36 +00003233 // -- Otherwise: E1 can be converted to match E2 if E1 can be
3234 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003235 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003236 // an rvalue).
3237 //
3238 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3239 // to the array-to-pointer or function-to-pointer conversions.
3240 if (!TTy->getAs<TagType>())
3241 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003242
Douglas Gregorb70cf442010-03-26 20:14:36 +00003243 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3244 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003245 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
Douglas Gregorb70cf442010-03-26 20:14:36 +00003246 ToType = TTy;
3247 if (InitSeq.isAmbiguous())
3248 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3249
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003250 return false;
3251}
3252
3253/// \brief Try to find a common type for two according to C++0x 5.16p5.
3254///
3255/// This is part of the parameter validation for the ? operator. If either
3256/// value operand is a class type, overload resolution is used to find a
3257/// conversion to a common type.
John Wiegley429bb272011-04-08 18:41:53 +00003258static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth82214a82011-02-18 23:54:50 +00003259 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00003260 Expr *Args[2] = { LHS.get(), RHS.get() };
Chandler Carruth82214a82011-02-18 23:54:50 +00003261 OverloadCandidateSet CandidateSet(QuestionLoc);
3262 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3263 CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003264
3265 OverloadCandidateSet::iterator Best;
Chandler Carruth82214a82011-02-18 23:54:50 +00003266 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley429bb272011-04-08 18:41:53 +00003267 case OR_Success: {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003268 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley429bb272011-04-08 18:41:53 +00003269 ExprResult LHSRes =
3270 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3271 Best->Conversions[0], Sema::AA_Converting);
3272 if (LHSRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003273 break;
John Wiegley429bb272011-04-08 18:41:53 +00003274 LHS = move(LHSRes);
3275
3276 ExprResult RHSRes =
3277 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3278 Best->Conversions[1], Sema::AA_Converting);
3279 if (RHSRes.isInvalid())
3280 break;
3281 RHS = move(RHSRes);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003282 if (Best->Function)
3283 Self.MarkDeclarationReferenced(QuestionLoc, Best->Function);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003284 return false;
John Wiegley429bb272011-04-08 18:41:53 +00003285 }
3286
Douglas Gregor20093b42009-12-09 23:02:17 +00003287 case OR_No_Viable_Function:
Chandler Carruth82214a82011-02-18 23:54:50 +00003288
3289 // Emit a better diagnostic if one of the expressions is a null pointer
3290 // constant and the other is a pointer type. In this case, the user most
3291 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00003292 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00003293 return true;
3294
3295 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003296 << LHS.get()->getType() << RHS.get()->getType()
3297 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003298 return true;
3299
Douglas Gregor20093b42009-12-09 23:02:17 +00003300 case OR_Ambiguous:
Chandler Carruth82214a82011-02-18 23:54:50 +00003301 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley429bb272011-04-08 18:41:53 +00003302 << LHS.get()->getType() << RHS.get()->getType()
3303 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00003304 // FIXME: Print the possible common types by printing the return types of
3305 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003306 break;
3307
Douglas Gregor20093b42009-12-09 23:02:17 +00003308 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003309 assert(false && "Conditional operator has only built-in overloads");
3310 break;
3311 }
3312 return true;
3313}
3314
Sebastian Redl76458502009-04-17 16:30:52 +00003315/// \brief Perform an "extended" implicit conversion as returned by
3316/// TryClassUnification.
John Wiegley429bb272011-04-08 18:41:53 +00003317static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003318 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley429bb272011-04-08 18:41:53 +00003319 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003320 SourceLocation());
John Wiegley429bb272011-04-08 18:41:53 +00003321 Expr *Arg = E.take();
3322 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
3323 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00003324 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00003325 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003326
John Wiegley429bb272011-04-08 18:41:53 +00003327 E = Result;
Sebastian Redl76458502009-04-17 16:30:52 +00003328 return false;
3329}
3330
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003331/// \brief Check the operands of ?: under C++ semantics.
3332///
3333/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
3334/// extension. In this case, LHS == Cond. (But they're not aliases.)
John Wiegley429bb272011-04-08 18:41:53 +00003335QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCall56ca35d2011-02-17 10:25:35 +00003336 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003337 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00003338 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
3339 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003340
3341 // C++0x 5.16p1
3342 // The first expression is contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00003343 if (!Cond.get()->isTypeDependent()) {
3344 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
3345 if (CondRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003346 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003347 Cond = move(CondRes);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003348 }
3349
John McCallf89e55a2010-11-18 06:31:45 +00003350 // Assume r-value.
3351 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00003352 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00003353
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003354 // Either of the arguments dependent?
John Wiegley429bb272011-04-08 18:41:53 +00003355 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003356 return Context.DependentTy;
3357
3358 // C++0x 5.16p2
3359 // If either the second or the third operand has type (cv) void, ...
John Wiegley429bb272011-04-08 18:41:53 +00003360 QualType LTy = LHS.get()->getType();
3361 QualType RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003362 bool LVoid = LTy->isVoidType();
3363 bool RVoid = RTy->isVoidType();
3364 if (LVoid || RVoid) {
3365 // ... then the [l2r] conversions are performed on the second and third
3366 // operands ...
John Wiegley429bb272011-04-08 18:41:53 +00003367 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3368 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3369 if (LHS.isInvalid() || RHS.isInvalid())
3370 return QualType();
3371 LTy = LHS.get()->getType();
3372 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003373
3374 // ... and one of the following shall hold:
3375 // -- The second or the third operand (but not both) is a throw-
3376 // expression; the result is of the type of the other and is an rvalue.
John Wiegley429bb272011-04-08 18:41:53 +00003377 bool LThrow = isa<CXXThrowExpr>(LHS.get());
3378 bool RThrow = isa<CXXThrowExpr>(RHS.get());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003379 if (LThrow && !RThrow)
3380 return RTy;
3381 if (RThrow && !LThrow)
3382 return LTy;
3383
3384 // -- Both the second and third operands have type void; the result is of
3385 // type void and is an rvalue.
3386 if (LVoid && RVoid)
3387 return Context.VoidTy;
3388
3389 // Neither holds, error.
3390 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3391 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley429bb272011-04-08 18:41:53 +00003392 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003393 return QualType();
3394 }
3395
3396 // Neither is void.
3397
3398 // C++0x 5.16p3
3399 // Otherwise, if the second and third operand have different types, and
3400 // either has (cv) class type, and attempt is made to convert each of those
3401 // operands to the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003402 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003403 (LTy->isRecordType() || RTy->isRecordType())) {
3404 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3405 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003406 QualType L2RType, R2LType;
3407 bool HaveL2R, HaveR2L;
John Wiegley429bb272011-04-08 18:41:53 +00003408 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003409 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003410 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003411 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003412
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003413 // If both can be converted, [...] the program is ill-formed.
3414 if (HaveL2R && HaveR2L) {
3415 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley429bb272011-04-08 18:41:53 +00003416 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003417 return QualType();
3418 }
3419
3420 // If exactly one conversion is possible, that conversion is applied to
3421 // the chosen operand and the converted operands are used in place of the
3422 // original operands for the remainder of this section.
3423 if (HaveL2R) {
John Wiegley429bb272011-04-08 18:41:53 +00003424 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003425 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003426 LTy = LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003427 } else if (HaveR2L) {
John Wiegley429bb272011-04-08 18:41:53 +00003428 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003429 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003430 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003431 }
3432 }
3433
3434 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00003435 // If the second and third operands are glvalues of the same value
3436 // category and have the same type, the result is of that type and
3437 // value category and it is a bit-field if the second or the third
3438 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00003439 // We only extend this to bitfields, not to the crazy other kinds of
3440 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003441 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00003442 if (Same &&
John Wiegley429bb272011-04-08 18:41:53 +00003443 LHS.get()->isGLValue() &&
3444 LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
3445 LHS.get()->isOrdinaryOrBitFieldObject() &&
3446 RHS.get()->isOrdinaryOrBitFieldObject()) {
3447 VK = LHS.get()->getValueKind();
3448 if (LHS.get()->getObjectKind() == OK_BitField ||
3449 RHS.get()->getObjectKind() == OK_BitField)
John McCall09431682010-11-18 19:01:18 +00003450 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00003451 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00003452 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003453
3454 // C++0x 5.16p5
3455 // Otherwise, the result is an rvalue. If the second and third operands
3456 // do not have the same type, and either has (cv) class type, ...
3457 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3458 // ... overload resolution is used to determine the conversions (if any)
3459 // to be applied to the operands. If the overload resolution fails, the
3460 // program is ill-formed.
3461 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3462 return QualType();
3463 }
3464
3465 // C++0x 5.16p6
3466 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3467 // conversions are performed on the second and third operands.
John Wiegley429bb272011-04-08 18:41:53 +00003468 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3469 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3470 if (LHS.isInvalid() || RHS.isInvalid())
3471 return QualType();
3472 LTy = LHS.get()->getType();
3473 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003474
3475 // After those conversions, one of the following shall hold:
3476 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00003477 // is of that type. If the operands have class type, the result
3478 // is a prvalue temporary of the result type, which is
3479 // copy-initialized from either the second operand or the third
3480 // operand depending on the value of the first operand.
3481 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3482 if (LTy->isRecordType()) {
3483 // The operands have class type. Make a temporary copy.
3484 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003485 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3486 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00003487 LHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00003488 if (LHSCopy.isInvalid())
3489 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003490
3491 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3492 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00003493 RHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00003494 if (RHSCopy.isInvalid())
3495 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003496
John Wiegley429bb272011-04-08 18:41:53 +00003497 LHS = LHSCopy;
3498 RHS = RHSCopy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003499 }
3500
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003501 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003502 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003503
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003504 // Extension: conditional operator involving vector types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003505 if (LTy->isVectorType() || RTy->isVectorType())
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003506 return CheckVectorOperands(QuestionLoc, LHS, RHS);
3507
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003508 // -- The second and third operands have arithmetic or enumeration type;
3509 // the usual arithmetic conversions are performed to bring them to a
3510 // common type, and the result is of that type.
3511 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3512 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00003513 if (LHS.isInvalid() || RHS.isInvalid())
3514 return QualType();
3515 return LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003516 }
3517
3518 // -- The second and third operands have pointer type, or one has pointer
3519 // type and the other is a null pointer constant; pointer conversions
3520 // and qualification conversions are performed to bring them to their
3521 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00003522 // -- The second and third operands have pointer to member type, or one has
3523 // pointer to member type and the other is a null pointer constant;
3524 // pointer to member conversions and qualification conversions are
3525 // performed to bring them to a common type, whose cv-qualification
3526 // shall match the cv-qualification of either the second or the third
3527 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003528 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003529 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003530 isSFINAEContext()? 0 : &NonStandardCompositeType);
3531 if (!Composite.isNull()) {
3532 if (NonStandardCompositeType)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003533 Diag(QuestionLoc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003534 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3535 << LTy << RTy << Composite
John Wiegley429bb272011-04-08 18:41:53 +00003536 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003537
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003538 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003539 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003540
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003541 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00003542 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3543 if (!Composite.isNull())
3544 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003545
Chandler Carruth7ef93242011-02-19 00:13:59 +00003546 // Check if we are using a null with a non-pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00003547 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth7ef93242011-02-19 00:13:59 +00003548 return QualType();
3549
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003550 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003551 << LHS.get()->getType() << RHS.get()->getType()
3552 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003553 return QualType();
3554}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003555
3556/// \brief Find a merged pointer type and convert the two expressions to it.
3557///
Douglas Gregor20b3e992009-08-24 17:42:35 +00003558/// This finds the composite pointer type (or member pointer type) for @p E1
3559/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3560/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003561/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003562///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003563/// \param Loc The location of the operator requiring these two expressions to
3564/// be converted to the composite pointer type.
3565///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003566/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3567/// a non-standard (but still sane) composite type to which both expressions
3568/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3569/// will be set true.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003570QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003571 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003572 bool *NonStandardCompositeType) {
3573 if (NonStandardCompositeType)
3574 *NonStandardCompositeType = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003575
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003576 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3577 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003578
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00003579 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3580 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00003581 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003582
3583 // C++0x 5.9p2
3584 // Pointer conversions and qualification conversions are performed on
3585 // pointer operands to bring them to their composite pointer type. If
3586 // one operand is a null pointer constant, the composite pointer type is
3587 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00003588 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003589 if (T2->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00003590 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003591 else
John Wiegley429bb272011-04-08 18:41:53 +00003592 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003593 return T2;
3594 }
Douglas Gregorce940492009-09-25 04:25:58 +00003595 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003596 if (T1->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00003597 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003598 else
John Wiegley429bb272011-04-08 18:41:53 +00003599 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003600 return T1;
3601 }
Mike Stump1eb44332009-09-09 15:08:12 +00003602
Douglas Gregor20b3e992009-08-24 17:42:35 +00003603 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003604 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3605 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003606 return QualType();
3607
3608 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3609 // the other has type "pointer to cv2 T" and the composite pointer type is
3610 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3611 // Otherwise, the composite pointer type is a pointer type similar to the
3612 // type of one of the operands, with a cv-qualification signature that is
3613 // the union of the cv-qualification signatures of the operand types.
3614 // In practice, the first part here is redundant; it's subsumed by the second.
3615 // What we do here is, we build the two possible composite types, and try the
3616 // conversions in both directions. If only one works, or if the two composite
3617 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00003618 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00003619 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
3620 QualifierVector QualifierUnion;
3621 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
3622 ContainingClassVector;
3623 ContainingClassVector MemberOfClass;
3624 QualType Composite1 = Context.getCanonicalType(T1),
3625 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003626 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00003627 do {
3628 const PointerType *Ptr1, *Ptr2;
3629 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3630 (Ptr2 = Composite2->getAs<PointerType>())) {
3631 Composite1 = Ptr1->getPointeeType();
3632 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003633
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003634 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003635 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003636 if (NonStandardCompositeType &&
3637 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3638 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003639
Douglas Gregor20b3e992009-08-24 17:42:35 +00003640 QualifierUnion.push_back(
3641 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3642 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3643 continue;
3644 }
Mike Stump1eb44332009-09-09 15:08:12 +00003645
Douglas Gregor20b3e992009-08-24 17:42:35 +00003646 const MemberPointerType *MemPtr1, *MemPtr2;
3647 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3648 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3649 Composite1 = MemPtr1->getPointeeType();
3650 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003651
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003652 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003653 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003654 if (NonStandardCompositeType &&
3655 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3656 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003657
Douglas Gregor20b3e992009-08-24 17:42:35 +00003658 QualifierUnion.push_back(
3659 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3660 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3661 MemPtr2->getClass()));
3662 continue;
3663 }
Mike Stump1eb44332009-09-09 15:08:12 +00003664
Douglas Gregor20b3e992009-08-24 17:42:35 +00003665 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00003666
Douglas Gregor20b3e992009-08-24 17:42:35 +00003667 // Cannot unwrap any more types.
3668 break;
3669 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00003670
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003671 if (NeedConstBefore && NonStandardCompositeType) {
3672 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003673 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003674 // requirements of C++ [conv.qual]p4 bullet 3.
3675 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3676 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3677 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3678 *NonStandardCompositeType = true;
3679 }
3680 }
3681 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003682
Douglas Gregor20b3e992009-08-24 17:42:35 +00003683 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003684 ContainingClassVector::reverse_iterator MOC
3685 = MemberOfClass.rbegin();
3686 for (QualifierVector::reverse_iterator
3687 I = QualifierUnion.rbegin(),
3688 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00003689 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00003690 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003691 if (MOC->first && MOC->second) {
3692 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00003693 Composite1 = Context.getMemberPointerType(
3694 Context.getQualifiedType(Composite1, Quals),
3695 MOC->first);
3696 Composite2 = Context.getMemberPointerType(
3697 Context.getQualifiedType(Composite2, Quals),
3698 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00003699 } else {
3700 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00003701 Composite1
3702 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3703 Composite2
3704 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00003705 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003706 }
3707
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003708 // Try to convert to the first composite pointer type.
3709 InitializedEntity Entity1
3710 = InitializedEntity::InitializeTemporary(Composite1);
3711 InitializationKind Kind
3712 = InitializationKind::CreateCopy(Loc, SourceLocation());
3713 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3714 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00003715
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003716 if (E1ToC1 && E2ToC1) {
3717 // Conversion to Composite1 is viable.
3718 if (!Context.hasSameType(Composite1, Composite2)) {
3719 // Composite2 is a different type from Composite1. Check whether
3720 // Composite2 is also viable.
3721 InitializedEntity Entity2
3722 = InitializedEntity::InitializeTemporary(Composite2);
3723 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3724 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3725 if (E1ToC2 && E2ToC2) {
3726 // Both Composite1 and Composite2 are viable and are different;
3727 // this is an ambiguity.
3728 return QualType();
3729 }
3730 }
3731
3732 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003733 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00003734 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003735 if (E1Result.isInvalid())
3736 return QualType();
3737 E1 = E1Result.takeAs<Expr>();
3738
3739 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00003740 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00003741 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003742 if (E2Result.isInvalid())
3743 return QualType();
3744 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003745
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003746 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003747 }
3748
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003749 // Check whether Composite2 is viable.
3750 InitializedEntity Entity2
3751 = InitializedEntity::InitializeTemporary(Composite2);
3752 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3753 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3754 if (!E1ToC2 || !E2ToC2)
3755 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003756
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003757 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00003758 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00003759 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003760 if (E1Result.isInvalid())
3761 return QualType();
3762 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003763
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003764 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00003765 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00003766 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003767 if (E2Result.isInvalid())
3768 return QualType();
3769 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003770
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003771 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003772}
Anders Carlsson165a0a02009-05-17 18:41:29 +00003773
John McCall60d7b3a2010-08-24 06:29:42 +00003774ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00003775 if (!E)
3776 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003777
Anders Carlsson089c2602009-08-15 23:41:35 +00003778 if (!Context.getLangOptions().CPlusPlus)
3779 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003780
Douglas Gregor51326552009-12-24 18:51:59 +00003781 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
3782
Ted Kremenek6217b802009-07-29 21:53:49 +00003783 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00003784 if (!RT)
3785 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003786
Douglas Gregor5e6fcd42011-02-08 02:14:35 +00003787 // If the result is a glvalue, we shouldn't bind it.
3788 if (E->Classify(Context).isGLValue())
3789 return Owned(E);
John McCall86ff3082010-02-04 22:26:26 +00003790
3791 // That should be enough to guarantee that this type is complete.
3792 // If it has a trivial destructor, we can avoid the extra copy.
Jeffrey Yasskinb7ee2e52011-01-27 19:17:54 +00003793 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall507384f2010-08-12 02:40:37 +00003794 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00003795 return Owned(E);
3796
Douglas Gregordb89f282010-07-01 22:47:18 +00003797 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
Anders Carlsson860306e2009-05-30 21:21:49 +00003798 ExprTemporaries.push_back(Temp);
Douglas Gregordb89f282010-07-01 22:47:18 +00003799 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003800 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00003801 CheckDestructorAccess(E->getExprLoc(), Destructor,
3802 PDiag(diag::err_access_dtor_temp)
3803 << E->getType());
3804 }
Anders Carlssondef11992009-05-30 20:36:53 +00003805 // FIXME: Add the temporary to the temporaries vector.
3806 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
3807}
3808
John McCall4765fa02010-12-06 08:20:24 +00003809Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003810 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00003811
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003812 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3813 assert(ExprTemporaries.size() >= FirstTemporary);
3814 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003815 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003816
John McCall4765fa02010-12-06 08:20:24 +00003817 Expr *E = ExprWithCleanups::Create(Context, SubExpr,
3818 &ExprTemporaries[FirstTemporary],
3819 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00003820 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
3821 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00003822
Anders Carlsson99ba36d2009-06-05 15:38:08 +00003823 return E;
3824}
3825
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003826ExprResult
John McCall4765fa02010-12-06 08:20:24 +00003827Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00003828 if (SubExpr.isInvalid())
3829 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003830
John McCall4765fa02010-12-06 08:20:24 +00003831 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00003832}
3833
John McCall4765fa02010-12-06 08:20:24 +00003834Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003835 assert(SubStmt && "sub statement can't be null!");
3836
3837 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3838 assert(ExprTemporaries.size() >= FirstTemporary);
3839 if (ExprTemporaries.size() == FirstTemporary)
3840 return SubStmt;
3841
3842 // FIXME: In order to attach the temporaries, wrap the statement into
3843 // a StmtExpr; currently this is only used for asm statements.
3844 // This is hacky, either create a new CXXStmtWithTemporaries statement or
3845 // a new AsmStmtWithTemporaries.
3846 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
3847 SourceLocation(),
3848 SourceLocation());
3849 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
3850 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00003851 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00003852}
3853
John McCall60d7b3a2010-08-24 06:29:42 +00003854ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003855Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00003856 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00003857 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003858 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003859 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003860 if (Result.isInvalid()) return ExprError();
3861 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003862
John McCall9ae2f072010-08-23 23:25:46 +00003863 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00003864 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003865 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00003866 // If we have a pointer to a dependent type and are using the -> operator,
3867 // the object type is the type that the pointer points to. We might still
3868 // have enough information about that type to do something useful.
3869 if (OpKind == tok::arrow)
3870 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3871 BaseType = Ptr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003872
John McCallb3d87482010-08-24 05:47:05 +00003873 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00003874 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00003875 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003876 }
Mike Stump1eb44332009-09-09 15:08:12 +00003877
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003878 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00003879 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003880 // returned, with the original second operand.
3881 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00003882 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00003883 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00003884 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00003885 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003886
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003887 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00003888 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
3889 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003890 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00003891 Base = Result.get();
3892 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00003893 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00003894 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00003895 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00003896 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003897 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00003898 for (unsigned i = 0; i < Locations.size(); i++)
3899 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00003900 return ExprError();
3901 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003902 }
Mike Stump1eb44332009-09-09 15:08:12 +00003903
Douglas Gregor31658df2009-11-20 19:58:21 +00003904 if (BaseType->isPointerType())
3905 BaseType = BaseType->getPointeeType();
3906 }
Mike Stump1eb44332009-09-09 15:08:12 +00003907
3908 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003909 // vector types or Objective-C interfaces. Just return early and let
3910 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00003911 if (!BaseType->isRecordType()) {
3912 // C++ [basic.lookup.classref]p2:
3913 // [...] If the type of the object expression is of pointer to scalar
3914 // type, the unqualified-id is looked up in the context of the complete
3915 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00003916 //
3917 // This also indicates that we should be parsing a
3918 // pseudo-destructor-name.
John McCallb3d87482010-08-24 05:47:05 +00003919 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00003920 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00003921 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00003922 }
Mike Stump1eb44332009-09-09 15:08:12 +00003923
Douglas Gregor03c57052009-11-17 05:17:33 +00003924 // The object type must be complete (or dependent).
3925 if (!BaseType->isDependentType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003926 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor03c57052009-11-17 05:17:33 +00003927 PDiag(diag::err_incomplete_member_access)))
3928 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003929
Douglas Gregorc68afe22009-09-03 21:38:09 +00003930 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00003931 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00003932 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00003933 // type C (or of pointer to a class type C), the unqualified-id is looked
3934 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00003935 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00003936 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00003937}
3938
John McCall60d7b3a2010-08-24 06:29:42 +00003939ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003940 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00003941 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00003942 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
3943 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00003944 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003945
Douglas Gregor77549082010-02-24 21:29:12 +00003946 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00003947 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00003948 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00003949 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00003950 /*RPLoc*/ ExpectedLParenLoc);
3951}
Douglas Gregord4dca082010-02-24 18:44:31 +00003952
John McCall60d7b3a2010-08-24 06:29:42 +00003953ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00003954 SourceLocation OpLoc,
3955 tok::TokenKind OpKind,
3956 const CXXScopeSpec &SS,
3957 TypeSourceInfo *ScopeTypeInfo,
3958 SourceLocation CCLoc,
3959 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003960 PseudoDestructorTypeStorage Destructed,
John McCall2d9f5fa2011-02-25 05:21:17 +00003961 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003962 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003963
Douglas Gregorb57fb492010-02-24 22:38:50 +00003964 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003965 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregorb57fb492010-02-24 22:38:50 +00003966 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003967 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00003968 QualType ObjectType = Base->getType();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003969 if (OpKind == tok::arrow) {
3970 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3971 ObjectType = Ptr->getPointeeType();
John McCall9ae2f072010-08-23 23:25:46 +00003972 } else if (!Base->isTypeDependent()) {
Douglas Gregorb57fb492010-02-24 22:38:50 +00003973 // The user wrote "p->" when she probably meant "p."; fix it.
3974 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3975 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00003976 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00003977 if (isSFINAEContext())
3978 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003979
Douglas Gregorb57fb492010-02-24 22:38:50 +00003980 OpKind = tok::period;
3981 }
3982 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003983
Douglas Gregorb57fb492010-02-24 22:38:50 +00003984 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
3985 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCall9ae2f072010-08-23 23:25:46 +00003986 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00003987 return ExprError();
3988 }
3989
3990 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003991 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb57fb492010-02-24 22:38:50 +00003992 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003993 if (DestructedTypeInfo) {
3994 QualType DestructedType = DestructedTypeInfo->getType();
3995 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003996 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00003997 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
3998 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
3999 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00004000 << ObjectType << DestructedType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004001 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004002
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004003 // Recover by setting the destructed type to the object type.
4004 DestructedType = ObjectType;
4005 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4006 DestructedTypeStart);
4007 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4008 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00004009 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004010
Douglas Gregorb57fb492010-02-24 22:38:50 +00004011 // C++ [expr.pseudo]p2:
4012 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4013 // form
4014 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004015 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb57fb492010-02-24 22:38:50 +00004016 //
4017 // shall designate the same scalar type.
4018 if (ScopeTypeInfo) {
4019 QualType ScopeType = ScopeTypeInfo->getType();
4020 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00004021 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004022
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004023 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00004024 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00004025 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004026 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004027
Douglas Gregorb57fb492010-02-24 22:38:50 +00004028 ScopeType = QualType();
4029 ScopeTypeInfo = 0;
4030 }
4031 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004032
John McCall9ae2f072010-08-23 23:25:46 +00004033 Expr *Result
4034 = new (Context) CXXPseudoDestructorExpr(Context, Base,
4035 OpKind == tok::arrow, OpLoc,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004036 SS.getWithLocInContext(Context),
John McCall9ae2f072010-08-23 23:25:46 +00004037 ScopeTypeInfo,
4038 CCLoc,
4039 TildeLoc,
4040 Destructed);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004041
Douglas Gregorb57fb492010-02-24 22:38:50 +00004042 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00004043 return Owned(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004044
John McCall9ae2f072010-08-23 23:25:46 +00004045 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00004046}
4047
John McCall60d7b3a2010-08-24 06:29:42 +00004048ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004049 SourceLocation OpLoc,
4050 tok::TokenKind OpKind,
4051 CXXScopeSpec &SS,
4052 UnqualifiedId &FirstTypeName,
4053 SourceLocation CCLoc,
4054 SourceLocation TildeLoc,
4055 UnqualifiedId &SecondTypeName,
4056 bool HasTrailingLParen) {
Douglas Gregor77549082010-02-24 21:29:12 +00004057 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4058 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4059 "Invalid first type name in pseudo-destructor");
4060 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4061 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4062 "Invalid second type name in pseudo-destructor");
4063
Douglas Gregor77549082010-02-24 21:29:12 +00004064 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004065 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregor77549082010-02-24 21:29:12 +00004066 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004067 // This scalar type is the object type.
John McCall9ae2f072010-08-23 23:25:46 +00004068 QualType ObjectType = Base->getType();
Douglas Gregor77549082010-02-24 21:29:12 +00004069 if (OpKind == tok::arrow) {
4070 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4071 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004072 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00004073 // The user wrote "p->" when she probably meant "p."; fix it.
4074 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004075 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00004076 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00004077 if (isSFINAEContext())
4078 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004079
Douglas Gregor77549082010-02-24 21:29:12 +00004080 OpKind = tok::period;
4081 }
4082 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004083
4084 // Compute the object type that we should use for name lookup purposes. Only
4085 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00004086 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004087 if (!SS.isSet()) {
John McCall2d9f5fa2011-02-25 05:21:17 +00004088 if (ObjectType->isRecordType())
4089 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallb3d87482010-08-24 05:47:05 +00004090 else if (ObjectType->isDependentType())
4091 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004092 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004093
4094 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb57fb492010-02-24 22:38:50 +00004095 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00004096 QualType DestructedType;
4097 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004098 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00004099 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004100 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00004101 SecondTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00004102 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004103 if (!T &&
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004104 ((SS.isSet() && !computeDeclContext(SS, false)) ||
4105 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004106 // The name of the type being destroyed is a dependent name, and we
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004107 // couldn't find anything useful in scope. Just store the identifier and
4108 // it's location, and we'll perform (qualified) name lookup again at
4109 // template instantiation time.
4110 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
4111 SecondTypeName.StartLocation);
4112 } else if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004113 Diag(SecondTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00004114 diag::err_pseudo_dtor_destructor_non_type)
4115 << SecondTypeName.Identifier << ObjectType;
4116 if (isSFINAEContext())
4117 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004118
Douglas Gregor77549082010-02-24 21:29:12 +00004119 // Recover by assuming we had the right type all along.
4120 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004121 } else
Douglas Gregor77549082010-02-24 21:29:12 +00004122 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004123 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004124 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00004125 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004126 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4127 TemplateId->getTemplateArgs(),
4128 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00004129 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4130 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004131 TemplateId->TemplateNameLoc,
4132 TemplateId->LAngleLoc,
4133 TemplateArgsPtr,
4134 TemplateId->RAngleLoc);
4135 if (T.isInvalid() || !T.get()) {
4136 // Recover by assuming we had the right type all along.
4137 DestructedType = ObjectType;
4138 } else
4139 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004140 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004141
4142 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb57fb492010-02-24 22:38:50 +00004143 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004144 if (!DestructedType.isNull()) {
4145 if (!DestructedTypeInfo)
4146 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004147 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004148 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4149 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004150
Douglas Gregorb57fb492010-02-24 22:38:50 +00004151 // Convert the name of the scope type (the type prior to '::') into a type.
4152 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00004153 QualType ScopeType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004154 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor77549082010-02-24 21:29:12 +00004155 FirstTypeName.Identifier) {
4156 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004157 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00004158 FirstTypeName.StartLocation,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004159 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00004160 if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004161 Diag(FirstTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00004162 diag::err_pseudo_dtor_destructor_non_type)
4163 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004164
Douglas Gregorb57fb492010-02-24 22:38:50 +00004165 if (isSFINAEContext())
4166 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004167
Douglas Gregorb57fb492010-02-24 22:38:50 +00004168 // Just drop this type. It's unnecessary anyway.
4169 ScopeType = QualType();
4170 } else
4171 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004172 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004173 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00004174 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004175 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4176 TemplateId->getTemplateArgs(),
4177 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00004178 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4179 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004180 TemplateId->TemplateNameLoc,
4181 TemplateId->LAngleLoc,
4182 TemplateArgsPtr,
4183 TemplateId->RAngleLoc);
4184 if (T.isInvalid() || !T.get()) {
4185 // Recover by dropping this type.
4186 ScopeType = QualType();
4187 } else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004188 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004189 }
4190 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004191
Douglas Gregorb4a418f2010-02-24 23:02:30 +00004192 if (!ScopeType.isNull() && !ScopeTypeInfo)
4193 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
4194 FirstTypeName.StartLocation);
4195
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004196
John McCall9ae2f072010-08-23 23:25:46 +00004197 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00004198 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004199 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00004200}
4201
John Wiegley429bb272011-04-08 18:41:53 +00004202ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004203 CXXMethodDecl *Method) {
John Wiegley429bb272011-04-08 18:41:53 +00004204 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
4205 FoundDecl, Method);
4206 if (Exp.isInvalid())
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004207 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00004208
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004209 MemberExpr *ME =
John Wiegley429bb272011-04-08 18:41:53 +00004210 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
John McCallf89e55a2010-11-18 06:31:45 +00004211 SourceLocation(), Method->getType(),
4212 VK_RValue, OK_Ordinary);
4213 QualType ResultType = Method->getResultType();
4214 ExprValueKind VK = Expr::getValueKindForType(ResultType);
4215 ResultType = ResultType.getNonLValueExprType(Context);
4216
John Wiegley429bb272011-04-08 18:41:53 +00004217 MarkDeclarationReferenced(Exp.get()->getLocStart(), Method);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004218 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00004219 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
John Wiegley429bb272011-04-08 18:41:53 +00004220 Exp.get()->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00004221 return CE;
4222}
4223
Sebastian Redl2e156222010-09-10 20:55:43 +00004224ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4225 SourceLocation RParen) {
Sebastian Redl2e156222010-09-10 20:55:43 +00004226 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
4227 Operand->CanThrow(Context),
4228 KeyLoc, RParen));
4229}
4230
4231ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
4232 Expr *Operand, SourceLocation RParen) {
4233 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00004234}
4235
John McCallf6a16482010-12-04 03:47:34 +00004236/// Perform the conversions required for an expression used in a
4237/// context that ignores the result.
John Wiegley429bb272011-04-08 18:41:53 +00004238ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCalla878cda2010-12-02 02:07:15 +00004239 // C99 6.3.2.1:
4240 // [Except in specific positions,] an lvalue that does not have
4241 // array type is converted to the value stored in the
4242 // designated object (and is no longer an lvalue).
John Wiegley429bb272011-04-08 18:41:53 +00004243 if (E->isRValue()) return Owned(E);
John McCalla878cda2010-12-02 02:07:15 +00004244
John McCallf6a16482010-12-04 03:47:34 +00004245 // We always want to do this on ObjC property references.
4246 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley429bb272011-04-08 18:41:53 +00004247 ExprResult Res = ConvertPropertyForRValue(E);
4248 if (Res.isInvalid()) return Owned(E);
4249 E = Res.take();
4250 if (E->isRValue()) return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004251 }
4252
4253 // Otherwise, this rule does not apply in C++, at least not for the moment.
John Wiegley429bb272011-04-08 18:41:53 +00004254 if (getLangOptions().CPlusPlus) return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004255
4256 // GCC seems to also exclude expressions of incomplete enum type.
4257 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
4258 if (!T->getDecl()->isComplete()) {
4259 // FIXME: stupid workaround for a codegen bug!
John Wiegley429bb272011-04-08 18:41:53 +00004260 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
4261 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004262 }
4263 }
4264
John Wiegley429bb272011-04-08 18:41:53 +00004265 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
4266 if (Res.isInvalid())
4267 return Owned(E);
4268 E = Res.take();
4269
John McCall85515d62010-12-04 12:29:11 +00004270 if (!E->getType()->isVoidType())
4271 RequireCompleteType(E->getExprLoc(), E->getType(),
4272 diag::err_incomplete_type);
John Wiegley429bb272011-04-08 18:41:53 +00004273 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004274}
4275
John Wiegley429bb272011-04-08 18:41:53 +00004276ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
4277 ExprResult FullExpr = Owned(FE);
4278
4279 if (!FullExpr.get())
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00004280 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00004281
John Wiegley429bb272011-04-08 18:41:53 +00004282 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregord0937222010-12-13 22:49:22 +00004283 return ExprError();
4284
John McCallfb8721c2011-04-10 19:13:55 +00004285 FullExpr = CheckPlaceholderExpr(FullExpr.take());
4286 if (FullExpr.isInvalid())
4287 return ExprError();
Douglas Gregor353ee242011-03-07 02:05:23 +00004288
John Wiegley429bb272011-04-08 18:41:53 +00004289 FullExpr = IgnoredValueConversions(FullExpr.take());
4290 if (FullExpr.isInvalid())
4291 return ExprError();
4292
4293 CheckImplicitConversions(FullExpr.get());
John McCall4765fa02010-12-06 08:20:24 +00004294 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00004295}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004296
4297StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
4298 if (!FullStmt) return StmtError();
4299
John McCall4765fa02010-12-06 08:20:24 +00004300 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004301}
Francois Pichet1e862692011-05-06 20:48:22 +00004302
4303bool Sema::CheckMicrosoftIfExistsSymbol(CXXScopeSpec &SS,
4304 UnqualifiedId &Name) {
4305 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
4306 DeclarationName TargetName = TargetNameInfo.getName();
4307 if (!TargetName)
4308 return false;
4309
4310 // Do the redeclaration lookup in the current scope.
4311 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
4312 Sema::NotForRedeclaration);
4313 R.suppressDiagnostics();
4314 LookupParsedName(R, getCurScope(), &SS);
4315 return !R.empty();
4316}