blob: 50462abd3a44d9072b67c7f82488d4c8f5bb86e0 [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner29375652006-12-04 18:06:35 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall19c1bfd2010-08-25 05:32:35 +000015#include "clang/Sema/DeclSpec.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
John McCall19c1bfd2010-08-25 05:32:35 +000018#include "clang/Sema/ParsedTemplate.h"
John McCallc63de662011-02-02 13:00:07 +000019#include "clang/Sema/ScopeInfo.h"
John McCall19c1bfd2010-08-25 05:32:35 +000020#include "clang/Sema/TemplateDeduction.h"
Steve Naroffaac94152007-08-25 14:02:58 +000021#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000024#include "clang/AST/ExprCXX.h"
Fariborz Jahanian1d446082010-06-16 18:56:04 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000026#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000027#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000028#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000029#include "clang/Lex/Preprocessor.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000030#include "llvm/ADT/STLExtras.h"
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +000031#include "llvm/Support/ErrorHandling.h"
Chris Lattner29375652006-12-04 18:06:35 +000032using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000033using namespace sema;
Chris Lattner29375652006-12-04 18:06:35 +000034
John McCallba7bf592010-08-24 05:47:05 +000035ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000036 IdentifierInfo &II,
John McCallba7bf592010-08-24 05:47:05 +000037 SourceLocation NameLoc,
38 Scope *S, CXXScopeSpec &SS,
39 ParsedType ObjectTypePtr,
40 bool EnteringContext) {
Douglas Gregorfe17d252010-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 Gregor46841e12010-02-23 00:15:22 +000060 // See also PR6358 and PR6359.
Sebastian Redla771d222010-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 Gregorfe17d252010-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 Gregor46841e12010-02-23 00:15:22 +000075 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000076
Douglas Gregor46841e12010-02-23 00:15:22 +000077 bool AlreadySearched = false;
78 bool LookAtPrefix = true;
Sebastian Redla771d222010-07-07 23:17:38 +000079 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000080 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redla771d222010-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 Takumi7c288862011-01-27 07:09:49 +000083 //
84 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redla771d222010-07-07 23:17:38 +000085 //
86 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth8f254812010-02-21 10:19:54 +000087 // a qualified-id of the form:
Douglas Gregorfe17d252010-02-16 19:09:40 +000088 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +000089 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregorfe17d252010-02-16 19:09:40 +000090 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000091 // the class-names are looked up as types in the scope designated by
Sebastian Redla771d222010-07-07 23:17:38 +000092 // the nested-name-specifier.
Douglas Gregorfe17d252010-02-16 19:09:40 +000093 //
Sebastian Redla771d222010-07-07 23:17:38 +000094 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000095 // code below is permitted to look at the prefix of the
Sebastian Redla771d222010-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 Takumif9cbcc42011-01-27 07:10:08 +0000104
Sebastian Redla771d222010-07-07 23:17:38 +0000105 // The second case from the C++03 rules quoted further above.
Douglas Gregor46841e12010-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 Gregor10176412011-02-25 16:07:42 +0000111 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor46841e12010-02-23 00:15:22 +0000112 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
113 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor46841e12010-02-23 00:15:22 +0000114 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000115 LookupCtx = computeDeclContext(SearchType);
116 isDependent = SearchType->isDependentType();
117 } else {
118 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000119 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000120 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000121
Douglas Gregorcd3f49f2010-02-25 04:46:04 +0000122 LookInScope = false;
Douglas Gregorfe17d252010-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 Takumif9cbcc42011-01-27 07:10:08 +0000133 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregorfe17d252010-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 Gregor4cf85a72011-03-04 22:32:08 +0000142 TypeDecl *NonMatchingTypeDecl = 0;
Douglas Gregorfe17d252010-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 Gregor4cf85a72011-03-04 22:32:08 +0000146 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregorfe17d252010-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 Gregor678f90d2010-02-25 01:56:36 +0000151 else if (Step == 1 && LookInScope && S)
Douglas Gregorfe17d252010-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 McCallba7bf592010-08-24 05:47:05 +0000158 return ParsedType();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000159
160 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
161 QualType T = Context.getTypeDeclType(Type);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000162
163 if (SearchType.isNull() || SearchType->isDependentType() ||
164 Context.hasSameUnqualifiedType(T, SearchType)) {
165 // We found our type!
166
John McCallba7bf592010-08-24 05:47:05 +0000167 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000168 }
John Wiegleyb4a9e512011-03-08 08:13:22 +0000169
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000170 if (!SearchType.isNull())
171 NonMatchingTypeDecl = Type;
Douglas Gregorfe17d252010-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 Takumif9cbcc42011-01-27 07:10:08 +0000179 // issue 399, for which there isn't even an obvious direction.
Douglas Gregorfe17d252010-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 McCalle78aac42010-03-10 03:28:59 +0000185 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
186 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000187 }
188 }
189 if (MemberOfType.isNull())
190 MemberOfType = SearchType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000191
Douglas Gregorfe17d252010-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 McCallba7bf592010-08-24 05:47:05 +0000203 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000204 }
205
206 continue;
207 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000208
Douglas Gregorfe17d252010-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 McCallba7bf592010-08-24 05:47:05 +0000222 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-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 Takumif9cbcc42011-01-27 07:10:08 +0000229 if (DependentTemplateName *DepTemplate
Douglas Gregorfe17d252010-02-16 19:09:40 +0000230 = SpecName.getAsDependentTemplateName()) {
231 if (DepTemplate->isIdentifier() &&
232 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallba7bf592010-08-24 05:47:05 +0000233 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-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 Gregor9cbc22b2011-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 McCallba7bf592010-08-24 05:47:05 +0000249 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000250 }
251
Douglas Gregor4cf85a72011-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 Takumif9cbcc42011-01-27 07:10:08 +0000260 << &II;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000261 else
262 Diag(NameLoc, diag::err_destructor_class_name);
263
John McCallba7bf592010-08-24 05:47:05 +0000264 return ParsedType();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000265}
266
Douglas Gregor9da64192010-04-26 22:37:10 +0000267/// \brief Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000268ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000269 SourceLocation TypeidLoc,
270 TypeSourceInfo *Operand,
271 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000272 // C++ [expr.typeid]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000273 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor9da64192010-04-26 22:37:10 +0000274 // that is the operand of typeid are always ignored.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000275 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor9da64192010-04-26 22:37:10 +0000276 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000277 Qualifiers Quals;
278 QualType T
279 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
280 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000281 if (T->getAs<RecordType>() &&
282 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
283 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000284
Douglas Gregor9da64192010-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 McCalldadc5752010-08-24 06:29:42 +0000291ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000292 SourceLocation TypeidLoc,
293 Expr *E,
294 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000295 bool isUnevaluatedOperand = true;
Douglas Gregor9da64192010-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 Takumif9cbcc42011-01-27 07:10:08 +0000305
Douglas Gregor9da64192010-04-26 22:37:10 +0000306 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000307 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000308 // polymorphic class type [...] [the] expression is an unevaluated
309 // operand. [...]
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000310 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000311 isUnevaluatedOperand = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000312
313 // We require a vtable to query the type at run time.
314 MarkVTableUsed(TypeidLoc, RecordD);
315 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000316 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000317
Douglas Gregor9da64192010-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 Takumif9cbcc42011-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 Gregor9da64192010-04-26 22:37:10 +0000322 // type.
Douglas Gregor876cec22010-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 Wiegley01296292011-04-08 18:41:53 +0000327 E = ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E)).take();
Douglas Gregor9da64192010-04-26 22:37:10 +0000328 }
329 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000330
Douglas Gregor9da64192010-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 Takumif9cbcc42011-01-27 07:10:08 +0000336
Douglas Gregor9da64192010-04-26 22:37:10 +0000337 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCallb268a282010-08-23 23:25:46 +0000338 E,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000339 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor9da64192010-04-26 22:37:10 +0000340}
341
342/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000343ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000344Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
345 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000346 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000347 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000348 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000349
Douglas Gregor4c7c1092010-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 Takumif9cbcc42011-01-27 07:10:08 +0000358
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000359 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000360
Douglas Gregor9da64192010-04-26 22:37:10 +0000361 if (isType) {
362 // The operand is a type; handle it as such.
363 TypeSourceInfo *TInfo = 0;
John McCallba7bf592010-08-24 05:47:05 +0000364 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
365 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000366 if (T.isNull())
367 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000368
Douglas Gregor9da64192010-04-26 22:37:10 +0000369 if (!TInfo)
370 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000371
Douglas Gregor9da64192010-04-26 22:37:10 +0000372 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000373 }
Mike Stump11289f42009-09-09 15:08:12 +0000374
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000375 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000376 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000377}
378
Francois Pichetb7577652010-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 McCall424cec92011-01-19 06:33:43 +0000382 const Type *Ty = QT.getTypePtr();;
Francois Pichet9dddd402010-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 Pichet59d2b012011-05-08 10:02:20 +0000388 // Loop all record redeclaration looking for an uuid attribute.
Francois Pichetb7577652010-12-27 01:32:00 +0000389 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Francois Pichet59d2b012011-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 Pichetb7577652010-12-27 01:32:00 +0000393 return Uuid;
Francois Pichetb7577652010-12-27 01:32:00 +0000394 }
Francois Pichet59d2b012011-05-08 10:02:20 +0000395
Francois Pichetb7577652010-12-27 01:32:00 +0000396 return 0;
Francois Pichet9dddd402010-12-20 03:51:03 +0000397}
398
Francois Pichet9f4f2072010-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 Pichetb7577652010-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 Takumif9cbcc42011-01-27 07:10:08 +0000408
Francois Pichet9f4f2072010-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 Pichetb7577652010-12-27 01:32:00 +0000420 if (!E->getType()->isDependentType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000421 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichetb7577652010-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 Pichet9f4f2072010-09-08 12:20:18 +0000426 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
427 E,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000428 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet9f4f2072010-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 Takumif9cbcc42011-01-27 07:10:08 +0000435 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-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 Takumif9cbcc42011-01-27 07:10:08 +0000443 }
444
Francois Pichet9f4f2072010-09-08 12:20:18 +0000445 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000446
Francois Pichet9f4f2072010-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 Takumif9cbcc42011-01-27 07:10:08 +0000454
Francois Pichet9f4f2072010-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 Takumif9cbcc42011-01-27 07:10:08 +0000461 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000462 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
463}
464
Steve Naroff66356bd2007-09-16 14:56:35 +0000465/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000466ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000467Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000468 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000469 "Unknown C++ Boolean value!");
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000470 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
471 Context.BoolTy, OpLoc));
Bill Wendling4073ed52007-02-13 01:51:42 +0000472}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000473
Sebastian Redl576fd422009-05-10 18:38:11 +0000474/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000475ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000476Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
477 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
478}
479
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000480/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000481ExprResult
John McCallb268a282010-08-23 23:25:46 +0000482Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000483 // Don't report an error if 'throw' is used in system headers.
Anders Carlssone96ab552011-02-28 02:27:16 +0000484 if (!getLangOptions().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000485 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb94ad3e2011-02-19 21:53:09 +0000486 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Anders Carlsson68b36af2011-02-19 19:26:44 +0000487
John Wiegley01296292011-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 Redl4de47b42009-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 Wiegley01296292011-04-08 18:41:53 +0000498ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000499 // C++ [except.throw]p3:
Douglas Gregor247894b2009-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 Takumif9cbcc42011-01-27 07:10:08 +0000503 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor247894b2009-12-23 22:04:40 +0000504 // or "pointer to function returning T", [...]
505 if (E->getType().hasQualifiers())
John Wiegley01296292011-04-08 18:41:53 +0000506 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
507 CastCategory(E)).take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000508
John Wiegley01296292011-04-08 18:41:53 +0000509 ExprResult Res = DefaultFunctionArrayConversion(E);
510 if (Res.isInvalid())
511 return ExprError();
512 E = Res.take();
Sebastian Redl4de47b42009-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 McCall2e6567a2010-04-22 01:10:34 +0000517 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000518 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000519 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000520 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000521 }
522 if (!isPointer || !Ty->isVoidType()) {
523 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlsson029fc692009-08-26 22:59:12 +0000524 PDiag(isPointer ? diag::err_throw_incomplete_ptr
525 : diag::err_throw_incomplete)
526 << E->getSourceRange()))
John Wiegley01296292011-04-08 18:41:53 +0000527 return ExprError();
Rafael Espindola70e040d2010-03-02 21:28:26 +0000528
Douglas Gregore8154332010-04-15 18:05:39 +0000529 if (RequireNonAbstractType(ThrowLoc, E->getType(),
530 PDiag(diag::err_throw_abstract_type)
531 << E->getSourceRange()))
John Wiegley01296292011-04-08 18:41:53 +0000532 return ExprError();
Sebastian Redl4de47b42009-04-27 20:27:31 +0000533 }
534
John McCall2e6567a2010-04-22 01:10:34 +0000535 // Initialize the exception result. This implicitly weeds out
536 // abstract types or types with inaccessible copy constructors.
Douglas Gregorc74edc22011-01-21 22:46:35 +0000537 const VarDecl *NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
538
Douglas Gregor5d369002011-01-21 18:05:27 +0000539 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p32.
John McCall2e6567a2010-04-22 01:10:34 +0000540 InitializedEntity Entity =
Douglas Gregorc74edc22011-01-21 22:46:35 +0000541 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
542 /*NRVO=*/false);
John Wiegley01296292011-04-08 18:41:53 +0000543 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
544 QualType(), E);
John McCall2e6567a2010-04-22 01:10:34 +0000545 if (Res.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000546 return ExprError();
547 E = Res.take();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000548
Eli Friedman91a3d272010-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 Wiegley01296292011-04-08 18:41:53 +0000552 return Owned(E);
Eli Friedman91a3d272010-06-03 20:39:03 +0000553 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
554
Douglas Gregor88d292c2010-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 Friedman91a3d272010-06-03 20:39:03 +0000557 MarkVTableUsed(ThrowLoc, RD);
558
Eli Friedman36ebbec2010-10-12 20:32:36 +0000559 // If a pointer is thrown, the referenced object will not be destroyed.
560 if (isPointer)
John Wiegley01296292011-04-08 18:41:53 +0000561 return Owned(E);
Eli Friedman36ebbec2010-10-12 20:32:36 +0000562
Eli Friedman91a3d272010-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 Wiegley01296292011-04-08 18:41:53 +0000565 return Owned(E);
Eli Friedman91a3d272010-06-03 20:39:03 +0000566
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000567 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +0000568 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman91a3d272010-06-03 20:39:03 +0000569 if (!Destructor)
John Wiegley01296292011-04-08 18:41:53 +0000570 return Owned(E);
Eli Friedman91a3d272010-06-03 20:39:03 +0000571
572 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
573 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregor747eb782010-07-08 06:14:04 +0000574 PDiag(diag::err_access_dtor_exception) << Ty);
John Wiegley01296292011-04-08 18:41:53 +0000575 return Owned(E);
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000576}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000577
John McCallf3a88602011-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 McCallc63de662011-02-02 13:00:07 +0000583 DeclContext *DC = CurContext;
John McCallf3a88602011-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 Kyrtzidised983422008-07-01 10:37:29 +0000589
John McCallf3a88602011-02-03 08:15:49 +0000590 // If we're not in an instance method, error out.
John McCallc63de662011-02-02 13:00:07 +0000591 CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC);
592 if (!method || !method->isInstance())
John McCallf3a88602011-02-03 08:15:49 +0000593 return 0;
John McCallc63de662011-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 McCallf3a88602011-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 McCallc63de662011-02-02 13:00:07 +0000613 /*isImplicit=*/false));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000614}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000615
John McCalldadc5752010-08-24 06:29:42 +0000616ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +0000617Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000618 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000619 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000620 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +0000621 if (!TypeRep)
622 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000623
John McCall97513962010-01-15 18:39:57 +0000624 TypeSourceInfo *TInfo;
625 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
626 if (!TInfo)
627 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-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 Redl6d4256c2009-03-15 17:47:39 +0000642 unsigned NumExprs = exprs.size();
643 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregor2b88c112010-09-08 00:15:04 +0000644 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000645 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
646
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000647 if (Ty->isDependentType() ||
Douglas Gregor0950e412009-03-13 21:01:28 +0000648 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000649 exprs.release();
Mike Stump11289f42009-09-09 15:08:12 +0000650
Douglas Gregor2b88c112010-09-08 00:15:04 +0000651 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregorce934142009-05-20 18:46:25 +0000652 LParenLoc,
653 Exprs, NumExprs,
654 RParenLoc));
Douglas Gregor0950e412009-03-13 21:01:28 +0000655 }
656
Anders Carlsson55243162009-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 Takumif9cbcc42011-01-27 07:10:08 +0000665
Anders Carlsson55243162009-08-27 03:53:50 +0000666 if (RequireNonAbstractType(TyBeginLoc, Ty,
667 diag::err_allocation_of_abstract_type))
668 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000669
670
Douglas Gregordd04d332009-01-16 18:33:17 +0000671 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-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 McCall8cb679e2010-11-15 09:13:47 +0000677 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +0000678 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +0000679 CXXCastPath BasePath;
John Wiegley01296292011-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 Redl6d4256c2009-03-15 17:47:39 +0000685 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +0000686 Exprs[0] = CastExpr.take();
Anders Carlssone9766d52009-09-09 21:33:21 +0000687
688 exprs.release();
Anders Carlssone9766d52009-09-09 21:33:21 +0000689
John McCallcf142162010-08-07 06:22:56 +0000690 return Owned(CXXFunctionalCastExpr::Create(Context,
Douglas Gregor2b88c112010-09-08 00:15:04 +0000691 Ty.getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +0000692 VK, TInfo, TyBeginLoc, Kind,
John McCallcf142162010-08-07 06:22:56 +0000693 Exprs[0], &BasePath,
694 RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000695 }
696
Douglas Gregor8ec51732010-09-08 21:40:08 +0000697 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
698 InitializationKind Kind
699 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
700 LParenLoc, RParenLoc)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000701 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor8ec51732010-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 Redl6d4256c2009-03-15 17:47:39 +0000705
Douglas Gregor8ec51732010-09-08 21:40:08 +0000706 // FIXME: Improve AST representation?
707 return move(Result);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000708}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000709
John McCall284c48f2011-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 Kyrtzidis7620ee42008-09-10 02:17:11 +0000765
Sebastian Redlbd150f42008-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 McCalldadc5752010-08-24 06:29:42 +0000771ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000772Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000773 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000774 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl351bb782008-12-02 14:43:59 +0000775 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000776 MultiExprArg ConstructorArgs,
Mike Stump11289f42009-09-09 15:08:12 +0000777 SourceLocation ConstructorRParen) {
Richard Smith30482bc2011-02-20 03:19:35 +0000778 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
779
Sebastian Redl351bb782008-12-02 14:43:59 +0000780 Expr *ArraySize = 0;
Sebastian Redl351bb782008-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 Smith30482bc2011-02-20 03:19:35 +0000785 if (TypeContainsAuto)
786 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
787 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000788 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000789 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
790 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000791 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000792 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
793 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000794
Sebastian Redl351bb782008-12-02 14:43:59 +0000795 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000796 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +0000797 }
798
Douglas Gregor73341c42009-09-11 00:18:58 +0000799 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000800 if (ArraySize) {
801 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-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 Redld7b3d7d2009-10-25 21:45:37 +0000816
Richard Smith30482bc2011-02-20 03:19:35 +0000817 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0, /*OwnedDecl=*/0,
818 /*AllowAuto=*/true);
John McCall8cb7bdf2010-06-04 23:28:52 +0000819 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000820 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000821 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000822
Mike Stump11289f42009-09-09 15:08:12 +0000823 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000824 PlacementLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000825 move(PlacementArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +0000826 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000827 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +0000828 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +0000829 TInfo,
John McCallb268a282010-08-23 23:25:46 +0000830 ArraySize,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000831 ConstructorLParen,
832 move(ConstructorArgs),
Richard Smith30482bc2011-02-20 03:19:35 +0000833 ConstructorRParen,
834 TypeContainsAuto);
Douglas Gregord0fefba2009-05-21 00:00:09 +0000835}
836
John McCalldadc5752010-08-24 06:29:42 +0000837ExprResult
Douglas Gregord0fefba2009-05-21 00:00:09 +0000838Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
839 SourceLocation PlacementLParen,
840 MultiExprArg PlacementArgs,
841 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000842 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000843 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +0000844 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +0000845 Expr *ArraySize,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000846 SourceLocation ConstructorLParen,
847 MultiExprArg ConstructorArgs,
Richard Smith30482bc2011-02-20 03:19:35 +0000848 SourceLocation ConstructorRParen,
849 bool TypeMayContainAuto) {
Douglas Gregor0744ef62010-09-07 21:49:58 +0000850 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redl351bb782008-12-02 14:43:59 +0000851
Richard Smith30482bc2011-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 Smith9647d3c2011-03-17 16:11:59 +0000863 TypeSourceInfo *DeducedType = 0;
864 if (!DeduceAutoType(AllocTypeInfo, ConstructorArgs.get()[0], DeducedType))
Richard Smith30482bc2011-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 Smith9647d3c2011-03-17 16:11:59 +0000870 if (!DeducedType)
871 return ExprError();
Richard Smith30482bc2011-02-20 03:19:35 +0000872
Richard Smith9647d3c2011-03-17 16:11:59 +0000873 AllocTypeInfo = DeducedType;
874 AllocType = AllocTypeInfo->getType();
Richard Smith30482bc2011-02-20 03:19:35 +0000875 }
876
Douglas Gregorcda95f42010-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 McCallb268a282010-08-23 23:25:46 +0000879 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +0000880 if (const ConstantArrayType *Array
881 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000882 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
883 Context.getSizeType(),
884 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +0000885 AllocType = Array->getElementType();
886 }
887 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000888
Douglas Gregor3999e152010-10-06 16:00:31 +0000889 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
890 return ExprError();
891
Douglas Gregorcda95f42010-05-16 16:01:03 +0000892 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl351bb782008-12-02 14:43:59 +0000893
Sebastian Redlbd150f42008-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 Redl8d2ccae2009-02-26 14:39:58 +0000896 if (ArraySize && !ArraySize->isTypeDependent()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000897
Sebastian Redl351bb782008-12-02 14:43:59 +0000898 QualType SizeType = ArraySize->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000899
John McCalldadc5752010-08-24 06:29:42 +0000900 ExprResult ConvertedSize
John McCallb268a282010-08-23 23:25:46 +0000901 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
Douglas Gregor4799d032010-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 Takumif9cbcc42011-01-27 07:10:08 +0000909 PDiag(getLangOptions().CPlusPlus0x? 0
Douglas Gregor4799d032010-06-30 00:20:43 +0000910 : diag::ext_array_size_conversion));
911 if (ConvertedSize.isInvalid())
912 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000913
John McCallb268a282010-08-23 23:25:46 +0000914 ArraySize = ConvertedSize.take();
Douglas Gregor4799d032010-06-30 00:20:43 +0000915 SizeType = ArraySize->getType();
Douglas Gregor0bf31402010-10-08 23:50:27 +0000916 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +0000917 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000918
Sebastian Redl351bb782008-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 Redl8d2ccae2009-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 Takumif9cbcc42011-01-27 07:10:08 +0000926 llvm::APInt::getNullValue(Value.getBitWidth()),
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000927 Value.isUnsigned()))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000928 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregorcaa1bf42010-08-18 00:39:00 +0000929 diag::err_typecheck_negative_array_size)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000930 << ArraySize->getSourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000931
Douglas Gregorcaa1bf42010-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 Takumif9cbcc42011-01-27 07:10:08 +0000936 Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregorcaa1bf42010-08-18 00:39:00 +0000937 diag::err_array_too_large)
938 << Value.toString(10)
939 << ArraySize->getSourceRange();
940 return ExprError();
941 }
942 }
Douglas Gregorf2753b32010-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 Takumif9cbcc42011-01-27 07:10:08 +0000949
Douglas Gregorf2753b32010-07-13 15:54:32 +0000950 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000951 }
Sebastian Redl351bb782008-12-02 14:43:59 +0000952 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000953
John McCall036f2f62011-05-15 07:14:44 +0000954 // Note that we do *not* convert the argument in any way. It can
955 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +0000956 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000957
Sebastian Redlbd150f42008-11-21 19:14:01 +0000958 FunctionDecl *OperatorNew = 0;
959 FunctionDecl *OperatorDelete = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000960 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
961 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000962
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000963 if (!AllocType->isDependentType() &&
964 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
965 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000966 SourceRange(PlacementLParen, PlacementRParen),
967 UseGlobal, AllocType, ArraySize, PlaceArgs,
968 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000969 return ExprError();
John McCall284c48f2011-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 Jahanian835026e2009-11-24 18:29:37 +0000978 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000979 if (OperatorNew) {
980 // Add default arguments, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000981 const FunctionProtoType *Proto =
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000982 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000983 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +0000984 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000985
Anders Carlssonc144bc22010-05-03 02:07:56 +0000986 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000987 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlssonc144bc22010-05-03 02:07:56 +0000988 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000989 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000990
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000991 NumPlaceArgs = AllPlaceArgs.size();
992 if (NumPlaceArgs > 0)
993 PlaceArgs = &AllPlaceArgs[0];
994 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000995
Sebastian Redlbd150f42008-11-21 19:14:01 +0000996 bool Init = ConstructorLParen.isValid();
997 // --- Choosing a constructor ---
Sebastian Redlbd150f42008-11-21 19:14:01 +0000998 CXXConstructorDecl *Constructor = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000999 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
1000 unsigned NumConsArgs = ConstructorArgs.size();
John McCall37ad5512010-08-23 06:44:23 +00001001 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmanfd8d4e12009-11-08 22:15:39 +00001002
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001003 // Array 'new' can't have any initializers.
Anders Carlssone6ae81b2010-05-16 16:24:20 +00001004 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001005 SourceRange InitRange(ConsArgs[0]->getLocStart(),
1006 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001007
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001008 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1009 return ExprError();
1010 }
1011
Douglas Gregor85dabae2009-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 Gregor0744ef62010-09-07 21:49:58 +00001021 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001022 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor85dabae2009-12-16 01:38:02 +00001023 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor0744ef62010-09-07 21:49:58 +00001024 : InitializationKind::CreateDirect(TypeRange.getBegin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001025 ConstructorLParen,
Douglas Gregor85dabae2009-12-16 01:38:02 +00001026 ConstructorRParen);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001027
Douglas Gregor85dabae2009-12-16 01:38:02 +00001028 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00001029 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00001030 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001031 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor85dabae2009-12-16 01:38:02 +00001032 move(ConstructorArgs));
1033 if (FullInit.isInvalid())
1034 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001035
1036 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor85dabae2009-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 McCallc3007a22010-10-26 07:05:15 +00001048 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor85dabae2009-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 Takumif9cbcc42011-01-27 07:10:08 +00001056
Douglas Gregor85dabae2009-12-16 01:38:02 +00001057 // Take the converted arguments and use them for the new expression.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001058 NumConsArgs = ConvertedConstructorArgs.size();
1059 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001060 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001061
Douglas Gregor6642ca22010-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 Redlbd150f42008-11-21 19:14:01 +00001068 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001069
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001070 PlacementArgs.release();
1071 ConstructorArgs.release();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001072
Ted Kremenek9d6eb402010-02-11 22:51:03 +00001073 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001074 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenek9d6eb402010-02-11 22:51:03 +00001075 ArraySize, Constructor, Init,
1076 ConsArgs, NumConsArgs, OperatorDelete,
John McCall284c48f2011-01-27 09:37:56 +00001077 UsualArrayDeleteWantsSize,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001078 ResultType, AllocTypeInfo,
1079 StartLoc,
Ted Kremenek9d6eb402010-02-11 22:51:03 +00001080 Init ? ConstructorRParen :
Chandler Carruth01718152010-10-25 08:47:36 +00001081 TypeRange.getEnd(),
1082 ConstructorLParen, ConstructorRParen));
Sebastian Redlbd150f42008-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 Gregord0fefba2009-05-21 00:00:09 +00001088bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00001089 SourceRange R) {
Sebastian Redlbd150f42008-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 Gregorac1fb652009-03-24 19:52:54 +00001092 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00001093 return Diag(Loc, diag::err_bad_new_type)
1094 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00001095 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00001096 return Diag(Loc, diag::err_bad_new_type)
1097 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00001098 else if (!AllocType->isDependentType() &&
Douglas Gregord0fefba2009-05-21 00:00:09 +00001099 RequireCompleteType(Loc, AllocType,
Anders Carlssond624e162009-08-26 23:45:07 +00001100 PDiag(diag::err_new_incomplete_type)
1101 << R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00001102 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00001103 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00001104 diag::err_allocation_of_abstract_type))
1105 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00001106 else if (AllocType->isVariablyModifiedType())
1107 return Diag(Loc, diag::err_variably_modified_new_type)
1108 << AllocType;
Douglas Gregor39d1a092011-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 Redlbd150f42008-11-21 19:14:01 +00001113 return false;
1114}
1115
Douglas Gregor6642ca22010-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 Redlfaf68082008-12-03 20:26:15 +00001130/// FindAllocationFunctions - Finds the overloads of operator new and delete
1131/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-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 Redlfaf68082008-12-03 20:26:15 +00001136 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +00001137 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-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 Redlfaf68082008-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 Kyrtzidis43b20572010-08-28 09:06:06 +00001151 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Anders Carlssona471db02009-08-16 20:29:29 +00001152 Context.Target.getPointerWidth(0)),
1153 Context.getSizeType(),
1154 SourceLocation());
1155 AllocArgs[0] = &Size;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001156 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1157
Douglas Gregor6642ca22010-02-26 05:06:18 +00001158 // C++ [expr.new]p8:
1159 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001160 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00001161 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-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 Redlfaf68082008-12-03 20:26:15 +00001164 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1165 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001166 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1167 IsArray ? OO_Array_Delete : OO_Delete);
1168
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001169 QualType AllocElemType = Context.getBaseElementType(AllocType);
1170
1171 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +00001172 CXXRecordDecl *Record
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001173 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001174 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +00001175 AllocArgs.size(), Record, /*AllowMissing=*/true,
1176 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00001177 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001178 }
1179 if (!OperatorNew) {
1180 // Didn't find a member overload. Look for a global one.
1181 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +00001182 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001183 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +00001184 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1185 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00001186 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001187 }
1188
John McCall0f55a032010-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 Carlsson6f9dabf2009-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 Stump11289f42009-09-09 15:08:12 +00001200
Douglas Gregor6642ca22010-02-26 05:06:18 +00001201 // C++ [expr.new]p19:
1202 //
1203 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001204 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00001205 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001206 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-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 Takumi7c288862011-01-27 07:09:49 +00001209 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00001210 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001211 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001212 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001213 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00001214 LookupQualifiedName(FoundDelete, RD);
1215 }
John McCallfb6f5262010-03-18 08:19:33 +00001216 if (FoundDelete.isAmbiguous())
1217 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00001218
1219 if (FoundDelete.empty()) {
1220 DeclareGlobalNewDelete();
1221 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1222 }
1223
1224 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00001225
1226 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1227
John McCalld3be2c82010-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 Gregor6642ca22010-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 Takumif9cbcc42011-01-27 07:10:08 +00001242 //
Douglas Gregor6642ca22010-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 McCalldb40c7f2010-12-14 08:05:40 +00001246 //
1247 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6642ca22010-02-26 05:06:18 +00001248 QualType ExpectedFunctionType;
1249 {
1250 const FunctionProtoType *Proto
1251 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00001252
Douglas Gregor6642ca22010-02-26 05:06:18 +00001253 llvm::SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001254 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6642ca22010-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 McCalldb40c7f2010-12-14 08:05:40 +00001258 FunctionProtoType::ExtProtoInfo EPI;
1259 EPI.Variadic = Proto->isVariadic();
1260
Douglas Gregor6642ca22010-02-26 05:06:18 +00001261 ExpectedFunctionType
1262 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalldb40c7f2010-12-14 08:05:40 +00001263 ArgTypes.size(), EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001264 }
1265
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001266 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001267 DEnd = FoundDelete.end();
1268 D != DEnd; ++D) {
1269 FunctionDecl *Fn = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001270 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6642ca22010-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 McCalla0296f72010-03-19 07:35:19 +00001281 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-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 Takumif9cbcc42011-01-27 07:10:08 +00001287 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-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 McCalla0296f72010-03-19 07:35:19 +00001292 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-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 McCalla0296f72010-03-19 07:35:19 +00001301 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-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 Takumif9cbcc42011-01-27 07:10:08 +00001312 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001313 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1314 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1315 << DeleteName;
John McCallfb6f5262010-03-18 08:19:33 +00001316 } else {
1317 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCalla0296f72010-03-19 07:35:19 +00001318 Matches[0].first);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001319 }
1320 }
1321
Sebastian Redlfaf68082008-12-03 20:26:15 +00001322 return false;
1323}
1324
Sebastian Redl33a31012008-12-04 22:20:51 +00001325/// FindAllocationOverload - Find an fitting overload for the allocation
1326/// function in the specified scope.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001327bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1328 DeclarationName Name, Expr** Args,
1329 unsigned NumArgs, DeclContext *Ctx,
Alexis Hunt1f69a022011-05-12 22:46:29 +00001330 bool AllowMissing, FunctionDecl *&Operator,
1331 bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00001332 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1333 LookupQualifiedName(R, Ctx);
John McCall9f3059a2009-10-09 21:13:30 +00001334 if (R.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001335 if (AllowMissing || !Diagnose)
Sebastian Redl33a31012008-12-04 22:20:51 +00001336 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +00001337 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001338 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +00001339 }
1340
John McCallfb6f5262010-03-18 08:19:33 +00001341 if (R.isAmbiguous())
1342 return true;
1343
1344 R.suppressDiagnostics();
John McCall9f3059a2009-10-09 21:13:30 +00001345
John McCallbc077cf2010-02-08 23:07:23 +00001346 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001347 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor80a6cc52009-09-30 00:03:47 +00001348 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor55297ac2008-12-23 00:26:44 +00001349 // Even member operator new/delete are implicitly treated as
1350 // static, so don't use AddMemberCandidate.
John McCalla0296f72010-03-19 07:35:19 +00001351 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth93538422010-02-03 11:02:14 +00001352
John McCalla0296f72010-03-19 07:35:19 +00001353 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1354 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth93538422010-02-03 11:02:14 +00001355 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1356 Candidates,
1357 /*SuppressUserConversions=*/false);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001358 continue;
Chandler Carruth93538422010-02-03 11:02:14 +00001359 }
1360
John McCalla0296f72010-03-19 07:35:19 +00001361 FunctionDecl *Fn = cast<FunctionDecl>(D);
1362 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth93538422010-02-03 11:02:14 +00001363 /*SuppressUserConversions=*/false);
Sebastian Redl33a31012008-12-04 22:20:51 +00001364 }
1365
1366 // Do the resolution.
1367 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00001368 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001369 case OR_Success: {
1370 // Got one!
1371 FunctionDecl *FnDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00001372 MarkDeclarationReferenced(StartLoc, FnDecl);
Sebastian Redl33a31012008-12-04 22:20:51 +00001373 // The first argument is size_t, and the first parameter must be size_t,
1374 // too. This is checked on declaration and can be assumed. (It can't be
1375 // asserted on, though, since invalid decls are left in there.)
John McCallfb6f5262010-03-18 08:19:33 +00001376 // Watch out for variadic allocator function.
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001377 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1378 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001379 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1380 FnDecl->getParamDecl(i));
1381
1382 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1383 return true;
1384
John McCalldadc5752010-08-24 06:29:42 +00001385 ExprResult Result
Alexis Hunt1f69a022011-05-12 22:46:29 +00001386 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
Douglas Gregor34147272010-03-26 20:35:59 +00001387 if (Result.isInvalid())
Sebastian Redl33a31012008-12-04 22:20:51 +00001388 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001389
Douglas Gregor34147272010-03-26 20:35:59 +00001390 Args[i] = Result.takeAs<Expr>();
Sebastian Redl33a31012008-12-04 22:20:51 +00001391 }
1392 Operator = FnDecl;
Alexis Hunt1f69a022011-05-12 22:46:29 +00001393 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl,
1394 Diagnose);
Sebastian Redl33a31012008-12-04 22:20:51 +00001395 return false;
1396 }
1397
1398 case OR_No_Viable_Function:
Chandler Carruthe6c88182011-06-08 10:26:03 +00001399 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001400 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1401 << Name << Range;
Chandler Carruthe6c88182011-06-08 10:26:03 +00001402 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1403 }
Sebastian Redl33a31012008-12-04 22:20:51 +00001404 return true;
1405
1406 case OR_Ambiguous:
Chandler Carruthe6c88182011-06-08 10:26:03 +00001407 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001408 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1409 << Name << Range;
Chandler Carruthe6c88182011-06-08 10:26:03 +00001410 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
1411 }
Sebastian Redl33a31012008-12-04 22:20:51 +00001412 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001413
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001414 case OR_Deleted: {
Chandler Carruthe6c88182011-06-08 10:26:03 +00001415 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001416 Diag(StartLoc, diag::err_ovl_deleted_call)
1417 << Best->Function->isDeleted()
1418 << Name
1419 << getDeletedOrUnavailableSuffix(Best->Function)
1420 << Range;
Chandler Carruthe6c88182011-06-08 10:26:03 +00001421 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1422 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00001423 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +00001424 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001425 }
Sebastian Redl33a31012008-12-04 22:20:51 +00001426 assert(false && "Unreachable, bad result from BestViableFunction");
1427 return true;
1428}
1429
1430
Sebastian Redlfaf68082008-12-03 20:26:15 +00001431/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1432/// delete. These are:
1433/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00001434/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00001435/// void* operator new(std::size_t) throw(std::bad_alloc);
1436/// void* operator new[](std::size_t) throw(std::bad_alloc);
1437/// void operator delete(void *) throw();
1438/// void operator delete[](void *) throw();
Sebastian Redl37588092011-03-14 18:08:30 +00001439/// // C++0x:
1440/// void* operator new(std::size_t);
1441/// void* operator new[](std::size_t);
1442/// void operator delete(void *);
1443/// void operator delete[](void *);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001444/// @endcode
Sebastian Redl37588092011-03-14 18:08:30 +00001445/// C++0x operator delete is implicitly noexcept.
Sebastian Redlfaf68082008-12-03 20:26:15 +00001446/// Note that the placement and nothrow forms of new are *not* implicitly
1447/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00001448void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001449 if (GlobalNewDeleteDeclared)
1450 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001451
Douglas Gregor87f54062009-09-15 22:30:29 +00001452 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001453 // [...] The following allocation and deallocation functions (18.4) are
1454 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00001455 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001456 //
Sebastian Redl37588092011-03-14 18:08:30 +00001457 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00001458 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001459 // void* operator new[](std::size_t) throw(std::bad_alloc);
1460 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00001461 // void operator delete[](void*) throw();
Sebastian Redl37588092011-03-14 18:08:30 +00001462 // C++0x:
1463 // void* operator new(std::size_t);
1464 // void* operator new[](std::size_t);
1465 // void operator delete(void*);
1466 // void operator delete[](void*);
Douglas Gregor87f54062009-09-15 22:30:29 +00001467 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001468 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00001469 // new, operator new[], operator delete, operator delete[].
1470 //
1471 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1472 // "std" or "bad_alloc" as necessary to form the exception specification.
1473 // However, we do not make these implicit declarations visible to name
1474 // lookup.
Sebastian Redl37588092011-03-14 18:08:30 +00001475 // Note that the C++0x versions of operator delete are deallocation functions,
1476 // and thus are implicitly noexcept.
1477 if (!StdBadAlloc && !getLangOptions().CPlusPlus0x) {
Douglas Gregor87f54062009-09-15 22:30:29 +00001478 // The "std::bad_alloc" class has not yet been declared, so build it
1479 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001480 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1481 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001482 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001483 &PP.getIdentifierTable().get("bad_alloc"),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001484 0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001485 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00001486 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001487
Sebastian Redlfaf68082008-12-03 20:26:15 +00001488 GlobalNewDeleteDeclared = true;
1489
1490 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1491 QualType SizeT = Context.getSizeType();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001492 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001493
Sebastian Redlfaf68082008-12-03 20:26:15 +00001494 DeclareGlobalAllocationFunction(
1495 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001496 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001497 DeclareGlobalAllocationFunction(
1498 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001499 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001500 DeclareGlobalAllocationFunction(
1501 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1502 Context.VoidTy, VoidPtr);
1503 DeclareGlobalAllocationFunction(
1504 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1505 Context.VoidTy, VoidPtr);
1506}
1507
1508/// DeclareGlobalAllocationFunction - Declares a single implicit global
1509/// allocation function if it doesn't already exist.
1510void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopes13c88c72009-12-16 16:59:22 +00001511 QualType Return, QualType Argument,
1512 bool AddMallocAttr) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001513 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1514
1515 // Check if this function is already declared.
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001516 {
Douglas Gregor17eb26b2008-12-23 22:05:29 +00001517 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001518 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001519 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth93538422010-02-03 11:02:14 +00001520 // Only look at non-template functions, as it is the predefined,
1521 // non-templated allocation function we are trying to declare here.
1522 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1523 QualType InitialParamType =
Douglas Gregor684d7bd2009-12-22 23:42:49 +00001524 Context.getCanonicalType(
Chandler Carruth93538422010-02-03 11:02:14 +00001525 Func->getParamDecl(0)->getType().getUnqualifiedType());
1526 // FIXME: Do we need to check for default arguments here?
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00001527 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1528 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001529 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth93538422010-02-03 11:02:14 +00001530 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00001531 }
Chandler Carruth93538422010-02-03 11:02:14 +00001532 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00001533 }
1534 }
1535
Douglas Gregor87f54062009-09-15 22:30:29 +00001536 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001537 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00001538 = (Name.getCXXOverloadedOperator() == OO_New ||
1539 Name.getCXXOverloadedOperator() == OO_Array_New);
Sebastian Redl37588092011-03-14 18:08:30 +00001540 if (HasBadAllocExceptionSpec && !getLangOptions().CPlusPlus0x) {
Douglas Gregor87f54062009-09-15 22:30:29 +00001541 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001542 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +00001543 }
John McCalldb40c7f2010-12-14 08:05:40 +00001544
1545 FunctionProtoType::ExtProtoInfo EPI;
John McCalldb40c7f2010-12-14 08:05:40 +00001546 if (HasBadAllocExceptionSpec) {
Sebastian Redl37588092011-03-14 18:08:30 +00001547 if (!getLangOptions().CPlusPlus0x) {
1548 EPI.ExceptionSpecType = EST_Dynamic;
1549 EPI.NumExceptions = 1;
1550 EPI.Exceptions = &BadAllocType;
1551 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001552 } else {
Sebastian Redl37588092011-03-14 18:08:30 +00001553 EPI.ExceptionSpecType = getLangOptions().CPlusPlus0x ?
1554 EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00001555 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001556
John McCalldb40c7f2010-12-14 08:05:40 +00001557 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001558 FunctionDecl *Alloc =
Abramo Bagnaradff19302011-03-08 08:55:46 +00001559 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1560 SourceLocation(), Name,
John McCall8e7d6562010-08-26 03:08:43 +00001561 FnType, /*TInfo=*/0, SC_None,
1562 SC_None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001563 Alloc->setImplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001564
Nuno Lopes13c88c72009-12-16 16:59:22 +00001565 if (AddMallocAttr)
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001566 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001567
Sebastian Redlfaf68082008-12-03 20:26:15 +00001568 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001569 SourceLocation(), 0,
1570 Argument, /*TInfo=*/0,
1571 SC_None, SC_None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00001572 Alloc->setParams(&Param, 1);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001573
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001574 // FIXME: Also add this declaration to the IdentifierResolver, but
1575 // make sure it is at the end of the chain to coincide with the
1576 // global scope.
John McCallcc14d1f2010-08-24 08:50:51 +00001577 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001578}
1579
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001580bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1581 DeclarationName Name,
Alexis Hunt1f69a022011-05-12 22:46:29 +00001582 FunctionDecl* &Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00001583 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001584 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00001585 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001586
John McCall27b18f82009-11-17 02:14:36 +00001587 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001588 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001589
Chandler Carruthb6f99172010-06-28 00:30:51 +00001590 Found.suppressDiagnostics();
1591
John McCall66a87592010-08-04 00:31:26 +00001592 llvm::SmallVector<DeclAccessPair,4> Matches;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001593 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1594 F != FEnd; ++F) {
Chandler Carruth9b418232010-08-08 07:04:00 +00001595 NamedDecl *ND = (*F)->getUnderlyingDecl();
1596
1597 // Ignore template operator delete members from the check for a usual
1598 // deallocation function.
1599 if (isa<FunctionTemplateDecl>(ND))
1600 continue;
1601
1602 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall66a87592010-08-04 00:31:26 +00001603 Matches.push_back(F.getPair());
1604 }
1605
1606 // There's exactly one suitable operator; pick it.
1607 if (Matches.size() == 1) {
1608 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
Alexis Hunt1f69a022011-05-12 22:46:29 +00001609
1610 if (Operator->isDeleted()) {
1611 if (Diagnose) {
1612 Diag(StartLoc, diag::err_deleted_function_use);
1613 Diag(Operator->getLocation(), diag::note_unavailable_here) << true;
1614 }
1615 return true;
1616 }
1617
John McCall66a87592010-08-04 00:31:26 +00001618 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Alexis Hunt1f69a022011-05-12 22:46:29 +00001619 Matches[0], Diagnose);
John McCall66a87592010-08-04 00:31:26 +00001620 return false;
1621
1622 // We found multiple suitable operators; complain about the ambiguity.
1623 } else if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001624 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00001625 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1626 << Name << RD;
John McCall66a87592010-08-04 00:31:26 +00001627
Alexis Huntf91729462011-05-12 22:46:25 +00001628 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1629 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1630 Diag((*F)->getUnderlyingDecl()->getLocation(),
1631 diag::note_member_declared_here) << Name;
1632 }
John McCall66a87592010-08-04 00:31:26 +00001633 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001634 }
1635
1636 // We did find operator delete/operator delete[] declarations, but
1637 // none of them were suitable.
1638 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001639 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00001640 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1641 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001642
Alexis Huntf91729462011-05-12 22:46:25 +00001643 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1644 F != FEnd; ++F)
1645 Diag((*F)->getUnderlyingDecl()->getLocation(),
1646 diag::note_member_declared_here) << Name;
1647 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001648 return true;
1649 }
1650
1651 // Look for a global declaration.
1652 DeclareGlobalNewDelete();
1653 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001654
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001655 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1656 Expr* DeallocArgs[1];
1657 DeallocArgs[0] = &Null;
1658 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
Alexis Hunt1f69a022011-05-12 22:46:29 +00001659 DeallocArgs, 1, TUDecl, !Diagnose,
1660 Operator, Diagnose))
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001661 return true;
1662
1663 assert(Operator && "Did not find a deallocation function!");
1664 return false;
1665}
1666
Sebastian Redlbd150f42008-11-21 19:14:01 +00001667/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1668/// @code ::delete ptr; @endcode
1669/// or
1670/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00001671ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001672Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00001673 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001674 // C++ [expr.delete]p1:
1675 // The operand shall have a pointer type, or a class type having a single
1676 // conversion function to a pointer type. The result has type void.
1677 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00001678 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1679
John Wiegley01296292011-04-08 18:41:53 +00001680 ExprResult Ex = Owned(ExE);
Anders Carlssona471db02009-08-16 20:29:29 +00001681 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00001682 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00001683 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00001684
John Wiegley01296292011-04-08 18:41:53 +00001685 if (!Ex.get()->isTypeDependent()) {
1686 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001687
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001688 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001689 if (RequireCompleteType(StartLoc, Type,
Douglas Gregorf65f4902010-07-29 14:44:35 +00001690 PDiag(diag::err_delete_incomplete_class_type)))
1691 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001692
John McCallda4458e2010-03-31 01:36:47 +00001693 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1694
Fariborz Jahanianb54ccb22009-09-11 21:44:33 +00001695 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001696 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001697 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001698 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00001699 NamedDecl *D = I.getDecl();
1700 if (isa<UsingShadowDecl>(D))
1701 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1702
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001703 // Skip over templated conversion functions; they aren't considered.
John McCallda4458e2010-03-31 01:36:47 +00001704 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001705 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001706
John McCallda4458e2010-03-31 01:36:47 +00001707 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001708
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001709 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1710 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00001711 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001712 ObjectPtrConversions.push_back(Conv);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001713 }
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001714 if (ObjectPtrConversions.size() == 1) {
1715 // We have a single conversion to a pointer-to-object type. Perform
1716 // that conversion.
John McCallda4458e2010-03-31 01:36:47 +00001717 // TODO: don't redo the conversion calculation.
John Wiegley01296292011-04-08 18:41:53 +00001718 ExprResult Res =
1719 PerformImplicitConversion(Ex.get(),
John McCallda4458e2010-03-31 01:36:47 +00001720 ObjectPtrConversions.front()->getConversionType(),
John Wiegley01296292011-04-08 18:41:53 +00001721 AA_Converting);
1722 if (Res.isUsable()) {
1723 Ex = move(Res);
1724 Type = Ex.get()->getType();
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001725 }
1726 }
1727 else if (ObjectPtrConversions.size() > 1) {
1728 Diag(StartLoc, diag::err_ambiguous_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00001729 << Type << Ex.get()->getSourceRange();
John McCallda4458e2010-03-31 01:36:47 +00001730 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1731 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001732 return ExprError();
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001733 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001734 }
1735
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001736 if (!Type->isPointerType())
1737 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00001738 << Type << Ex.get()->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001739
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001740 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregorbb3348e2010-05-24 17:01:56 +00001741 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001742 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00001743 // effectively bans deletion of "void*". However, most compilers support
1744 // this, so we treat it as a warning unless we're in a SFINAE context.
1745 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00001746 << Type << Ex.get()->getSourceRange();
Douglas Gregorbb3348e2010-05-24 17:01:56 +00001747 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001748 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00001749 << Type << Ex.get()->getSourceRange());
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001750 else if (!Pointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00001751 RequireCompleteType(StartLoc, Pointee,
Anders Carlssond624e162009-08-26 23:45:07 +00001752 PDiag(diag::warn_delete_incomplete)
John Wiegley01296292011-04-08 18:41:53 +00001753 << Ex.get()->getSourceRange()))
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001754 return ExprError();
Douglas Gregor39d1a092011-04-15 19:46:20 +00001755 else if (unsigned AddressSpace = Pointee.getAddressSpace())
1756 return Diag(Ex.get()->getLocStart(),
1757 diag::err_address_space_qualified_delete)
1758 << Pointee.getUnqualifiedType() << AddressSpace;
Douglas Gregor98496dc2009-09-29 21:38:53 +00001759 // C++ [expr.delete]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001760 // [Note: a pointer to a const type can be the operand of a
1761 // delete-expression; it is not necessary to cast away the constness
1762 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor98496dc2009-09-29 21:38:53 +00001763 // of the delete-expression. ]
John Wiegley01296292011-04-08 18:41:53 +00001764 Ex = ImpCastExprToType(Ex.take(), Context.getPointerType(Context.VoidTy),
John McCalle3027922010-08-25 11:45:40 +00001765 CK_NoOp);
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00001766
1767 if (Pointee->isArrayType() && !ArrayForm) {
1768 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00001769 << Type << Ex.get()->getSourceRange()
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00001770 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1771 ArrayForm = true;
1772 }
1773
Anders Carlssona471db02009-08-16 20:29:29 +00001774 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1775 ArrayForm ? OO_Array_Delete : OO_Delete);
1776
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001777 QualType PointeeElem = Context.getBaseElementType(Pointee);
1778 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001779 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1780
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001781 if (!UseGlobal &&
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001782 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00001783 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001784
John McCall284c48f2011-01-27 09:37:56 +00001785 // If we're allocating an array of records, check whether the
1786 // usual operator delete[] has a size_t parameter.
1787 if (ArrayForm) {
1788 // If the user specifically asked to use the global allocator,
1789 // we'll need to do the lookup into the class.
1790 if (UseGlobal)
1791 UsualArrayDeleteWantsSize =
1792 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1793
1794 // Otherwise, the usual operator delete[] should be the
1795 // function we just found.
1796 else if (isa<CXXMethodDecl>(OperatorDelete))
1797 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1798 }
1799
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001800 if (!RD->hasTrivialDestructor())
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001801 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
Mike Stump11289f42009-09-09 15:08:12 +00001802 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001803 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001804 DiagnoseUseOfDecl(Dtor, StartLoc);
1805 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00001806
1807 // C++ [expr.delete]p3:
1808 // In the first alternative (delete object), if the static type of the
1809 // object to be deleted is different from its dynamic type, the static
1810 // type shall be a base class of the dynamic type of the object to be
1811 // deleted and the static type shall have a virtual destructor or the
1812 // behavior is undefined.
1813 //
1814 // Note: a final class cannot be derived from, no issue there
1815 if (!ArrayForm && RD->isPolymorphic() && !RD->hasAttr<FinalAttr>()) {
1816 CXXDestructorDecl *dtor = RD->getDestructor();
1817 if (!dtor || !dtor->isVirtual())
1818 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
1819 }
Anders Carlssona471db02009-08-16 20:29:29 +00001820 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001821
Anders Carlssona471db02009-08-16 20:29:29 +00001822 if (!OperatorDelete) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001823 // Look for a global declaration.
Anders Carlssona471db02009-08-16 20:29:29 +00001824 DeclareGlobalNewDelete();
1825 DeclContext *TUDecl = Context.getTranslationUnitDecl();
John Wiegley01296292011-04-08 18:41:53 +00001826 Expr *Arg = Ex.get();
Mike Stump11289f42009-09-09 15:08:12 +00001827 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
John Wiegley01296292011-04-08 18:41:53 +00001828 &Arg, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssona471db02009-08-16 20:29:29 +00001829 OperatorDelete))
1830 return ExprError();
1831 }
Mike Stump11289f42009-09-09 15:08:12 +00001832
John McCall0f55a032010-04-20 02:18:25 +00001833 MarkDeclarationReferenced(StartLoc, OperatorDelete);
John McCall284c48f2011-01-27 09:37:56 +00001834
Douglas Gregorfa778132011-02-01 15:50:11 +00001835 // Check access and ambiguity of operator delete and destructor.
1836 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1837 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1838 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
John Wiegley01296292011-04-08 18:41:53 +00001839 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregorfa778132011-02-01 15:50:11 +00001840 PDiag(diag::err_access_dtor) << PointeeElem);
1841 }
1842 }
1843
Sebastian Redlbd150f42008-11-21 19:14:01 +00001844 }
1845
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001846 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall284c48f2011-01-27 09:37:56 +00001847 ArrayFormAsWritten,
1848 UsualArrayDeleteWantsSize,
John Wiegley01296292011-04-08 18:41:53 +00001849 OperatorDelete, Ex.take(), StartLoc));
Sebastian Redlbd150f42008-11-21 19:14:01 +00001850}
1851
Douglas Gregor633caca2009-11-23 23:44:04 +00001852/// \brief Check the use of the given variable as a C++ condition in an if,
1853/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00001854ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00001855 SourceLocation StmtLoc,
1856 bool ConvertToBoolean) {
Douglas Gregor633caca2009-11-23 23:44:04 +00001857 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001858
Douglas Gregor633caca2009-11-23 23:44:04 +00001859 // C++ [stmt.select]p2:
1860 // The declarator shall not specify a function or an array.
1861 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001862 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00001863 diag::err_invalid_use_of_function_type)
1864 << ConditionVar->getSourceRange());
1865 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001866 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00001867 diag::err_invalid_use_of_array_type)
1868 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00001869
John Wiegley01296292011-04-08 18:41:53 +00001870 ExprResult Condition =
1871 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
Douglas Gregorea972d32011-02-28 21:54:11 +00001872 ConditionVar,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001873 ConditionVar->getLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00001874 ConditionVar->getType().getNonReferenceType(),
John Wiegley01296292011-04-08 18:41:53 +00001875 VK_LValue));
1876 if (ConvertToBoolean) {
1877 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
1878 if (Condition.isInvalid())
1879 return ExprError();
1880 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001881
John Wiegley01296292011-04-08 18:41:53 +00001882 return move(Condition);
Douglas Gregor633caca2009-11-23 23:44:04 +00001883}
1884
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001885/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley01296292011-04-08 18:41:53 +00001886ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001887 // C++ 6.4p4:
1888 // The value of a condition that is an initialized declaration in a statement
1889 // other than a switch statement is the value of the declared variable
1890 // implicitly converted to type bool. If that conversion is ill-formed, the
1891 // program is ill-formed.
1892 // The value of a condition that is an expression is the value of the
1893 // expression, implicitly converted to bool.
1894 //
Douglas Gregor5fb53972009-01-14 15:45:31 +00001895 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001896}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001897
1898/// Helper function to determine whether this is the (deprecated) C++
1899/// conversion from a string literal to a pointer to non-const char or
1900/// non-const wchar_t (for narrow and wide string literals,
1901/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00001902bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001903Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1904 // Look inside the implicit cast, if it exists.
1905 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1906 From = Cast->getSubExpr();
1907
1908 // A string literal (2.13.4) that is not a wide string literal can
1909 // be converted to an rvalue of type "pointer to char"; a wide
1910 // string literal can be converted to an rvalue of type "pointer
1911 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00001912 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001913 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001914 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00001915 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001916 // This conversion is considered only when there is an
1917 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall8ccfcb52009-09-24 19:53:00 +00001918 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001919 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1920 (!StrLit->isWide() &&
1921 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1922 ToPointeeType->getKind() == BuiltinType::Char_S))))
1923 return true;
1924 }
1925
1926 return false;
1927}
Douglas Gregor39c16d42008-10-24 04:54:22 +00001928
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001929static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00001930 SourceLocation CastLoc,
1931 QualType Ty,
1932 CastKind Kind,
1933 CXXMethodDecl *Method,
Douglas Gregor2bbfba02011-01-20 01:32:05 +00001934 NamedDecl *FoundDecl,
John McCalle3027922010-08-25 11:45:40 +00001935 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00001936 switch (Kind) {
1937 default: assert(0 && "Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00001938 case CK_ConstructorConversion: {
John McCall37ad5512010-08-23 06:44:23 +00001939 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001940
Douglas Gregora4253922010-04-16 22:17:36 +00001941 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
John McCallfaf5fb42010-08-26 23:41:50 +00001942 MultiExprArg(&From, 1),
Douglas Gregora4253922010-04-16 22:17:36 +00001943 CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00001944 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001945
1946 ExprResult Result =
1947 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
John McCallbfd822c2010-08-24 07:32:53 +00001948 move_arg(ConstructorArgs),
Chandler Carruth01718152010-10-25 08:47:36 +00001949 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete,
1950 SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00001951 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00001952 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001953
Douglas Gregora4253922010-04-16 22:17:36 +00001954 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1955 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001956
John McCalle3027922010-08-25 11:45:40 +00001957 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00001958 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001959
Douglas Gregora4253922010-04-16 22:17:36 +00001960 // Create an implicit call expr that calls it.
Douglas Gregor2bbfba02011-01-20 01:32:05 +00001961 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method);
Douglas Gregor668443e2011-01-20 00:18:04 +00001962 if (Result.isInvalid())
1963 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001964
Douglas Gregor668443e2011-01-20 00:18:04 +00001965 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00001966 }
1967 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001968}
Douglas Gregora4253922010-04-16 22:17:36 +00001969
Douglas Gregor5fb53972009-01-14 15:45:31 +00001970/// PerformImplicitConversion - Perform an implicit conversion of the
1971/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00001972/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001973/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001974/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00001975ExprResult
1976Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001977 const ImplicitConversionSequence &ICS,
Douglas Gregor58281352011-01-27 00:58:17 +00001978 AssignmentAction Action, bool CStyle) {
John McCall0d1da222010-01-12 00:44:57 +00001979 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00001980 case ImplicitConversionSequence::StandardConversion: {
1981 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
1982 Action, CStyle);
1983 if (Res.isInvalid())
1984 return ExprError();
1985 From = Res.take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00001986 break;
John Wiegley01296292011-04-08 18:41:53 +00001987 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001988
Anders Carlsson110b07b2009-09-15 06:28:28 +00001989 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001990
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001991 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00001992 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001993 QualType BeforeToType;
1994 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00001995 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001996
Anders Carlsson110b07b2009-09-15 06:28:28 +00001997 // If the user-defined conversion is specified by a conversion function,
1998 // the initial standard conversion sequence converts the source type to
1999 // the implicit object parameter of the conversion function.
2000 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00002001 } else {
2002 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00002003 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002004 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00002005 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002006 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian55824512009-11-06 00:23:08 +00002007 // initial standard conversion sequence converts the source type to the
2008 // type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00002009 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2010 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002011 }
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00002012 // Watch out for elipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00002013 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00002014 ExprResult Res =
2015 PerformImplicitConversion(From, BeforeToType,
2016 ICS.UserDefined.Before, AA_Converting,
2017 CStyle);
2018 if (Res.isInvalid())
2019 return ExprError();
2020 From = Res.take();
Fariborz Jahanian55824512009-11-06 00:23:08 +00002021 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002022
2023 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00002024 = BuildCXXCastArgument(*this,
2025 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00002026 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002027 CastKind, cast<CXXMethodDecl>(FD),
2028 ICS.UserDefined.FoundConversionFunction,
John McCallb268a282010-08-23 23:25:46 +00002029 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00002030
2031 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00002032 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00002033
John Wiegley01296292011-04-08 18:41:53 +00002034 From = CastArg.take();
Eli Friedmane96f1d32009-11-27 04:41:50 +00002035
Eli Friedmane96f1d32009-11-27 04:41:50 +00002036 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor58281352011-01-27 00:58:17 +00002037 AA_Converting, CStyle);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00002038 }
John McCall0d1da222010-01-12 00:44:57 +00002039
2040 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00002041 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00002042 PDiag(diag::err_typecheck_ambiguous_condition)
2043 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00002044 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002045
Douglas Gregor39c16d42008-10-24 04:54:22 +00002046 case ImplicitConversionSequence::EllipsisConversion:
2047 assert(false && "Cannot perform an ellipsis conversion");
John Wiegley01296292011-04-08 18:41:53 +00002048 return Owned(From);
Douglas Gregor39c16d42008-10-24 04:54:22 +00002049
2050 case ImplicitConversionSequence::BadConversion:
John Wiegley01296292011-04-08 18:41:53 +00002051 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002052 }
2053
2054 // Everything went well.
John Wiegley01296292011-04-08 18:41:53 +00002055 return Owned(From);
Douglas Gregor39c16d42008-10-24 04:54:22 +00002056}
2057
2058/// PerformImplicitConversion - Perform an implicit conversion of the
2059/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00002060/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00002061/// expression. Flavor is the context in which we're performing this
2062/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00002063ExprResult
2064Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002065 const StandardConversionSequence& SCS,
Douglas Gregor58281352011-01-27 00:58:17 +00002066 AssignmentAction Action, bool CStyle) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002067 // Overall FIXME: we are recomputing too many types here and doing far too
2068 // much extra work. What this means is that we need to keep track of more
2069 // information that is computed when we try the implicit conversion initially,
2070 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00002071 QualType FromType = From->getType();
2072
Douglas Gregor2fe98832008-11-03 19:09:14 +00002073 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00002074 // FIXME: When can ToType be a reference type?
2075 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002076 if (SCS.Second == ICK_Derived_To_Base) {
John McCall37ad5512010-08-23 06:44:23 +00002077 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002078 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCall37ad5512010-08-23 06:44:23 +00002079 MultiExprArg(*this, &From, 1),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002080 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002081 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00002082 return ExprError();
2083 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2084 ToType, SCS.CopyConstructor,
2085 move_arg(ConstructorArgs),
2086 /*ZeroInit*/ false,
2087 CXXConstructExpr::CK_Complete,
2088 SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002089 }
John Wiegley01296292011-04-08 18:41:53 +00002090 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2091 ToType, SCS.CopyConstructor,
2092 MultiExprArg(*this, &From, 1),
2093 /*ZeroInit*/ false,
2094 CXXConstructExpr::CK_Complete,
2095 SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00002096 }
2097
Douglas Gregor980fb162010-04-29 18:24:40 +00002098 // Resolve overloaded function references.
2099 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2100 DeclAccessPair Found;
2101 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2102 true, Found);
2103 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00002104 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00002105
2106 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
John Wiegley01296292011-04-08 18:41:53 +00002107 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002108
Douglas Gregor980fb162010-04-29 18:24:40 +00002109 From = FixOverloadedFunctionReference(From, Found, Fn);
2110 FromType = From->getType();
2111 }
2112
Douglas Gregor39c16d42008-10-24 04:54:22 +00002113 // Perform the first implicit conversion.
2114 switch (SCS.First) {
2115 case ICK_Identity:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002116 // Nothing to do.
2117 break;
2118
John McCall34376a62010-12-04 03:47:34 +00002119 case ICK_Lvalue_To_Rvalue:
2120 // Should this get its own ICK?
2121 if (From->getObjectKind() == OK_ObjCProperty) {
John Wiegley01296292011-04-08 18:41:53 +00002122 ExprResult FromRes = ConvertPropertyForRValue(From);
2123 if (FromRes.isInvalid())
2124 return ExprError();
2125 From = FromRes.take();
John McCalled75c092010-12-07 22:54:16 +00002126 if (!From->isGLValue()) break;
John McCall34376a62010-12-04 03:47:34 +00002127 }
2128
Chandler Carruth1af88f12011-02-17 21:10:52 +00002129 // Check for trivial buffer overflows.
Ted Kremenekdf26df72011-03-01 18:41:00 +00002130 CheckArrayAccess(From);
Chandler Carruth1af88f12011-02-17 21:10:52 +00002131
John McCall34376a62010-12-04 03:47:34 +00002132 FromType = FromType.getUnqualifiedType();
2133 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2134 From, 0, VK_RValue);
2135 break;
2136
Douglas Gregor39c16d42008-10-24 04:54:22 +00002137 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00002138 FromType = Context.getArrayDecayedType(FromType);
John Wiegley01296292011-04-08 18:41:53 +00002139 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay).take();
Douglas Gregor171c45a2009-02-18 21:56:37 +00002140 break;
2141
2142 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002143 FromType = Context.getPointerType(FromType);
John Wiegley01296292011-04-08 18:41:53 +00002144 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay).take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002145 break;
2146
2147 default:
2148 assert(false && "Improper first standard conversion");
2149 break;
2150 }
2151
2152 // Perform the second implicit conversion
2153 switch (SCS.Second) {
2154 case ICK_Identity:
Sebastian Redl5d431642009-10-10 12:04:10 +00002155 // If both sides are functions (or pointers/references to them), there could
2156 // be incompatible exception declarations.
2157 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00002158 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00002159 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00002160 break;
2161
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00002162 case ICK_NoReturn_Adjustment:
2163 // If both sides are functions (or pointers/references to them), there could
2164 // be incompatible exception declarations.
2165 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00002166 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002167
John Wiegley01296292011-04-08 18:41:53 +00002168 From = ImpCastExprToType(From, ToType, CK_NoOp).take();
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00002169 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002170
Douglas Gregor39c16d42008-10-24 04:54:22 +00002171 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002172 case ICK_Integral_Conversion:
John Wiegley01296292011-04-08 18:41:53 +00002173 From = ImpCastExprToType(From, ToType, CK_IntegralCast).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002174 break;
2175
2176 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002177 case ICK_Floating_Conversion:
John Wiegley01296292011-04-08 18:41:53 +00002178 From = ImpCastExprToType(From, ToType, CK_FloatingCast).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002179 break;
2180
2181 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00002182 case ICK_Complex_Conversion: {
2183 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2184 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2185 CastKind CK;
2186 if (FromEl->isRealFloatingType()) {
2187 if (ToEl->isRealFloatingType())
2188 CK = CK_FloatingComplexCast;
2189 else
2190 CK = CK_FloatingComplexToIntegralComplex;
2191 } else if (ToEl->isRealFloatingType()) {
2192 CK = CK_IntegralComplexToFloatingComplex;
2193 } else {
2194 CK = CK_IntegralComplexCast;
2195 }
John Wiegley01296292011-04-08 18:41:53 +00002196 From = ImpCastExprToType(From, ToType, CK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002197 break;
John McCall8cb679e2010-11-15 09:13:47 +00002198 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00002199
Douglas Gregor39c16d42008-10-24 04:54:22 +00002200 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00002201 if (ToType->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002202 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002203 else
John Wiegley01296292011-04-08 18:41:53 +00002204 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002205 break;
2206
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002207 case ICK_Compatible_Conversion:
John Wiegley01296292011-04-08 18:41:53 +00002208 From = ImpCastExprToType(From, ToType, CK_NoOp).take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002209 break;
2210
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002211 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00002212 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002213 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00002214 if (Action == AA_Initializing || Action == AA_Assigning)
Fariborz Jahanian413e0642011-03-21 19:08:42 +00002215 Diag(From->getSourceRange().getBegin(),
2216 diag::ext_typecheck_convert_incompatible_pointer)
2217 << ToType << From->getType() << Action
2218 << From->getSourceRange();
2219 else
2220 Diag(From->getSourceRange().getBegin(),
2221 diag::ext_typecheck_convert_incompatible_pointer)
2222 << From->getType() << ToType << Action
2223 << From->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00002224
2225 if (From->getType()->isObjCObjectPointerType() &&
2226 ToType->isObjCObjectPointerType())
2227 EmitRelatedResultTypeNote(From);
Douglas Gregor47d3f272008-12-19 17:40:08 +00002228 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002229
John McCall8cb679e2010-11-15 09:13:47 +00002230 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00002231 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00002232 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00002233 return ExprError();
2234 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath).take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002235 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002236 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002237
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002238 case ICK_Pointer_Member: {
John McCall8cb679e2010-11-15 09:13:47 +00002239 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00002240 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00002241 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00002242 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00002243 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00002244 return ExprError();
2245 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath).take();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002246 break;
2247 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002248
Abramo Bagnara7ccce982011-04-07 09:26:19 +00002249 case ICK_Boolean_Conversion:
John Wiegley01296292011-04-08 18:41:53 +00002250 From = ImpCastExprToType(From, Context.BoolTy,
2251 ScalarTypeToBooleanCastKind(FromType)).take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002252 break;
2253
Douglas Gregor88d292c2010-05-13 16:44:06 +00002254 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00002255 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002256 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00002257 ToType.getNonReferenceType(),
2258 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002259 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00002260 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00002261 CStyle))
John Wiegley01296292011-04-08 18:41:53 +00002262 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00002263
John Wiegley01296292011-04-08 18:41:53 +00002264 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
John McCalle3027922010-08-25 11:45:40 +00002265 CK_DerivedToBase, CastCategory(From),
John Wiegley01296292011-04-08 18:41:53 +00002266 &BasePath).take();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00002267 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00002268 }
2269
Douglas Gregor46188682010-05-18 22:42:18 +00002270 case ICK_Vector_Conversion:
John Wiegley01296292011-04-08 18:41:53 +00002271 From = ImpCastExprToType(From, ToType, CK_BitCast).take();
Douglas Gregor46188682010-05-18 22:42:18 +00002272 break;
2273
2274 case ICK_Vector_Splat:
John Wiegley01296292011-04-08 18:41:53 +00002275 From = ImpCastExprToType(From, ToType, CK_VectorSplat).take();
Douglas Gregor46188682010-05-18 22:42:18 +00002276 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002277
Douglas Gregor46188682010-05-18 22:42:18 +00002278 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00002279 // Case 1. x -> _Complex y
2280 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2281 QualType ElType = ToComplex->getElementType();
2282 bool isFloatingComplex = ElType->isRealFloatingType();
2283
2284 // x -> y
2285 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2286 // do nothing
2287 } else if (From->getType()->isRealFloatingType()) {
John Wiegley01296292011-04-08 18:41:53 +00002288 From = ImpCastExprToType(From, ElType,
2289 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
John McCall8cb679e2010-11-15 09:13:47 +00002290 } else {
2291 assert(From->getType()->isIntegerType());
John Wiegley01296292011-04-08 18:41:53 +00002292 From = ImpCastExprToType(From, ElType,
2293 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
John McCall8cb679e2010-11-15 09:13:47 +00002294 }
2295 // y -> _Complex y
John Wiegley01296292011-04-08 18:41:53 +00002296 From = ImpCastExprToType(From, ToType,
John McCall8cb679e2010-11-15 09:13:47 +00002297 isFloatingComplex ? CK_FloatingRealToComplex
John Wiegley01296292011-04-08 18:41:53 +00002298 : CK_IntegralRealToComplex).take();
John McCall8cb679e2010-11-15 09:13:47 +00002299
2300 // Case 2. _Complex x -> y
2301 } else {
2302 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2303 assert(FromComplex);
2304
2305 QualType ElType = FromComplex->getElementType();
2306 bool isFloatingComplex = ElType->isRealFloatingType();
2307
2308 // _Complex x -> x
John Wiegley01296292011-04-08 18:41:53 +00002309 From = ImpCastExprToType(From, ElType,
John McCall8cb679e2010-11-15 09:13:47 +00002310 isFloatingComplex ? CK_FloatingComplexToReal
John Wiegley01296292011-04-08 18:41:53 +00002311 : CK_IntegralComplexToReal).take();
John McCall8cb679e2010-11-15 09:13:47 +00002312
2313 // x -> y
2314 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2315 // do nothing
2316 } else if (ToType->isRealFloatingType()) {
John Wiegley01296292011-04-08 18:41:53 +00002317 From = ImpCastExprToType(From, ToType,
2318 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating).take();
John McCall8cb679e2010-11-15 09:13:47 +00002319 } else {
2320 assert(ToType->isIntegerType());
John Wiegley01296292011-04-08 18:41:53 +00002321 From = ImpCastExprToType(From, ToType,
2322 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast).take();
John McCall8cb679e2010-11-15 09:13:47 +00002323 }
2324 }
Douglas Gregor46188682010-05-18 22:42:18 +00002325 break;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002326
2327 case ICK_Block_Pointer_Conversion: {
John Wiegley01296292011-04-08 18:41:53 +00002328 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2329 VK_RValue).take();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002330 break;
2331 }
2332
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00002333 case ICK_TransparentUnionConversion: {
John Wiegley01296292011-04-08 18:41:53 +00002334 ExprResult FromRes = Owned(From);
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00002335 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002336 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2337 if (FromRes.isInvalid())
2338 return ExprError();
2339 From = FromRes.take();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00002340 assert ((ConvTy == Sema::Compatible) &&
2341 "Improper transparent union conversion");
2342 (void)ConvTy;
2343 break;
2344 }
2345
Douglas Gregor46188682010-05-18 22:42:18 +00002346 case ICK_Lvalue_To_Rvalue:
2347 case ICK_Array_To_Pointer:
2348 case ICK_Function_To_Pointer:
2349 case ICK_Qualification:
2350 case ICK_Num_Conversion_Kinds:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002351 assert(false && "Improper second standard conversion");
2352 break;
2353 }
2354
2355 switch (SCS.Third) {
2356 case ICK_Identity:
2357 // Nothing to do.
2358 break;
2359
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002360 case ICK_Qualification: {
2361 // The qualification keeps the category of the inner expression, unless the
2362 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00002363 ExprValueKind VK = ToType->isReferenceType() ?
2364 CastCategory(From) : VK_RValue;
John Wiegley01296292011-04-08 18:41:53 +00002365 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2366 CK_NoOp, VK).take();
Douglas Gregore489a7d2010-02-28 18:30:25 +00002367
Douglas Gregore981bb02011-03-14 16:13:32 +00002368 if (SCS.DeprecatedStringLiteralToCharPtr &&
2369 !getLangOptions().WritableStrings)
Douglas Gregore489a7d2010-02-28 18:30:25 +00002370 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2371 << ToType.getNonReferenceType();
2372
Douglas Gregor39c16d42008-10-24 04:54:22 +00002373 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002374 }
2375
Douglas Gregor39c16d42008-10-24 04:54:22 +00002376 default:
Douglas Gregor46188682010-05-18 22:42:18 +00002377 assert(false && "Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002378 break;
2379 }
2380
John Wiegley01296292011-04-08 18:41:53 +00002381 return Owned(From);
Douglas Gregor39c16d42008-10-24 04:54:22 +00002382}
2383
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002384ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor54e5b132010-09-09 16:14:44 +00002385 SourceLocation KWLoc,
2386 ParsedType Ty,
2387 SourceLocation RParen) {
2388 TypeSourceInfo *TSInfo;
2389 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump11289f42009-09-09 15:08:12 +00002390
Douglas Gregor54e5b132010-09-09 16:14:44 +00002391 if (!TSInfo)
2392 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002393 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor54e5b132010-09-09 16:14:44 +00002394}
2395
Chandler Carruth8e172c62011-05-01 06:51:22 +00002396/// \brief Check the completeness of a type in a unary type trait.
2397///
2398/// If the particular type trait requires a complete type, tries to complete
2399/// it. If completing the type fails, a diagnostic is emitted and false
2400/// returned. If completing the type succeeds or no completion was required,
2401/// returns true.
2402static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2403 UnaryTypeTrait UTT,
2404 SourceLocation Loc,
2405 QualType ArgTy) {
2406 // C++0x [meta.unary.prop]p3:
2407 // For all of the class templates X declared in this Clause, instantiating
2408 // that template with a template argument that is a class template
2409 // specialization may result in the implicit instantiation of the template
2410 // argument if and only if the semantics of X require that the argument
2411 // must be a complete type.
2412 // We apply this rule to all the type trait expressions used to implement
2413 // these class templates. We also try to follow any GCC documented behavior
2414 // in these expressions to ensure portability of standard libraries.
2415 switch (UTT) {
Chandler Carruth8e172c62011-05-01 06:51:22 +00002416 // is_complete_type somewhat obviously cannot require a complete type.
2417 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002418 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00002419
2420 // These traits are modeled on the type predicates in C++0x
2421 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2422 // requiring a complete type, as whether or not they return true cannot be
2423 // impacted by the completeness of the type.
2424 case UTT_IsVoid:
2425 case UTT_IsIntegral:
2426 case UTT_IsFloatingPoint:
2427 case UTT_IsArray:
2428 case UTT_IsPointer:
2429 case UTT_IsLvalueReference:
2430 case UTT_IsRvalueReference:
2431 case UTT_IsMemberFunctionPointer:
2432 case UTT_IsMemberObjectPointer:
2433 case UTT_IsEnum:
2434 case UTT_IsUnion:
2435 case UTT_IsClass:
2436 case UTT_IsFunction:
2437 case UTT_IsReference:
2438 case UTT_IsArithmetic:
2439 case UTT_IsFundamental:
2440 case UTT_IsObject:
2441 case UTT_IsScalar:
2442 case UTT_IsCompound:
2443 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002444 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00002445
2446 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2447 // which requires some of its traits to have the complete type. However,
2448 // the completeness of the type cannot impact these traits' semantics, and
2449 // so they don't require it. This matches the comments on these traits in
2450 // Table 49.
2451 case UTT_IsConst:
2452 case UTT_IsVolatile:
2453 case UTT_IsSigned:
2454 case UTT_IsUnsigned:
2455 return true;
2456
2457 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002458 // applied to a complete type.
Chandler Carruth8e172c62011-05-01 06:51:22 +00002459 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00002460 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00002461 case UTT_IsStandardLayout:
2462 case UTT_IsPOD:
2463 case UTT_IsLiteral:
2464 case UTT_IsEmpty:
2465 case UTT_IsPolymorphic:
2466 case UTT_IsAbstract:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002467 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00002468
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002469 // These trait expressions are designed to help implement predicates in
Chandler Carruth8e172c62011-05-01 06:51:22 +00002470 // [meta.unary.prop] despite not being named the same. They are specified
2471 // by both GCC and the Embarcadero C++ compiler, and require the complete
2472 // type due to the overarching C++0x type predicates being implemented
2473 // requiring the complete type.
2474 case UTT_HasNothrowAssign:
2475 case UTT_HasNothrowConstructor:
2476 case UTT_HasNothrowCopy:
2477 case UTT_HasTrivialAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00002478 case UTT_HasTrivialDefaultConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00002479 case UTT_HasTrivialCopy:
2480 case UTT_HasTrivialDestructor:
2481 case UTT_HasVirtualDestructor:
2482 // Arrays of unknown bound are expressly allowed.
2483 QualType ElTy = ArgTy;
2484 if (ArgTy->isIncompleteArrayType())
2485 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2486
2487 // The void type is expressly allowed.
2488 if (ElTy->isVoidType())
2489 return true;
2490
2491 return !S.RequireCompleteType(
2492 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00002493 }
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +00002494 llvm_unreachable("Type trait not handled by switch");
Chandler Carruth8e172c62011-05-01 06:51:22 +00002495}
2496
2497static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2498 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00002499 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00002500
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002501 ASTContext &C = Self.Context;
2502 switch(UTT) {
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002503 // Type trait expressions corresponding to the primary type category
2504 // predicates in C++0x [meta.unary.cat].
2505 case UTT_IsVoid:
2506 return T->isVoidType();
2507 case UTT_IsIntegral:
2508 return T->isIntegralType(C);
2509 case UTT_IsFloatingPoint:
2510 return T->isFloatingType();
2511 case UTT_IsArray:
2512 return T->isArrayType();
2513 case UTT_IsPointer:
2514 return T->isPointerType();
2515 case UTT_IsLvalueReference:
2516 return T->isLValueReferenceType();
2517 case UTT_IsRvalueReference:
2518 return T->isRValueReferenceType();
2519 case UTT_IsMemberFunctionPointer:
2520 return T->isMemberFunctionPointerType();
2521 case UTT_IsMemberObjectPointer:
2522 return T->isMemberDataPointerType();
2523 case UTT_IsEnum:
2524 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00002525 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00002526 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002527 case UTT_IsClass:
Chandler Carruthaf858862011-05-01 09:29:58 +00002528 return T->isClassType() || T->isStructureType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002529 case UTT_IsFunction:
2530 return T->isFunctionType();
2531
2532 // Type trait expressions which correspond to the convenient composition
2533 // predicates in C++0x [meta.unary.comp].
2534 case UTT_IsReference:
2535 return T->isReferenceType();
2536 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00002537 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002538 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00002539 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002540 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00002541 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002542 case UTT_IsScalar:
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00002543 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002544 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00002545 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002546 case UTT_IsMemberPointer:
2547 return T->isMemberPointerType();
2548
2549 // Type trait expressions which correspond to the type property predicates
2550 // in C++0x [meta.unary.prop].
2551 case UTT_IsConst:
2552 return T.isConstQualified();
2553 case UTT_IsVolatile:
2554 return T.isVolatileQualified();
2555 case UTT_IsTrivial:
2556 return T->isTrivialType();
Alexis Huntd9a5cc12011-05-13 00:31:07 +00002557 case UTT_IsTriviallyCopyable:
2558 return T->isTriviallyCopyableType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002559 case UTT_IsStandardLayout:
2560 return T->isStandardLayoutType();
2561 case UTT_IsPOD:
2562 return T->isPODType();
2563 case UTT_IsLiteral:
2564 return T->isLiteralType();
2565 case UTT_IsEmpty:
2566 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2567 return !RD->isUnion() && RD->isEmpty();
2568 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002569 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00002570 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2571 return RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002572 return false;
2573 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00002574 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2575 return RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002576 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00002577 case UTT_IsSigned:
2578 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00002579 case UTT_IsUnsigned:
2580 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002581
2582 // Type trait expressions which query classes regarding their construction,
2583 // destruction, and copying. Rather than being based directly on the
2584 // related type predicates in the standard, they are specified by both
2585 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
2586 // specifications.
2587 //
2588 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
2589 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Alexis Huntf479f1b2011-05-09 18:22:59 +00002590 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002591 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2592 // If __is_pod (type) is true then the trait is true, else if type is
2593 // a cv class or union type (or array thereof) with a trivial default
2594 // constructor ([class.ctor]) then the trait is true, else it is false.
2595 if (T->isPODType())
2596 return true;
2597 if (const RecordType *RT =
2598 C.getBaseElementType(T)->getAs<RecordType>())
Alexis Huntf479f1b2011-05-09 18:22:59 +00002599 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002600 return false;
2601 case UTT_HasTrivialCopy:
2602 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2603 // If __is_pod (type) is true or type is a reference type then
2604 // the trait is true, else if type is a cv class or union type
2605 // with a trivial copy constructor ([class.copy]) then the trait
2606 // is true, else it is false.
2607 if (T->isPODType() || T->isReferenceType())
2608 return true;
2609 if (const RecordType *RT = T->getAs<RecordType>())
2610 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2611 return false;
2612 case UTT_HasTrivialAssign:
2613 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2614 // If type is const qualified or is a reference type then the
2615 // trait is false. Otherwise if __is_pod (type) is true then the
2616 // trait is true, else if type is a cv class or union type with
2617 // a trivial copy assignment ([class.copy]) then the trait is
2618 // true, else it is false.
2619 // Note: the const and reference restrictions are interesting,
2620 // given that const and reference members don't prevent a class
2621 // from having a trivial copy assignment operator (but do cause
2622 // errors if the copy assignment operator is actually used, q.v.
2623 // [class.copy]p12).
2624
2625 if (C.getBaseElementType(T).isConstQualified())
2626 return false;
2627 if (T->isPODType())
2628 return true;
2629 if (const RecordType *RT = T->getAs<RecordType>())
2630 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2631 return false;
2632 case UTT_HasTrivialDestructor:
2633 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2634 // If __is_pod (type) is true or type is a reference type
2635 // then the trait is true, else if type is a cv class or union
2636 // type (or array thereof) with a trivial destructor
2637 // ([class.dtor]) then the trait is true, else it is
2638 // false.
2639 if (T->isPODType() || T->isReferenceType())
2640 return true;
2641 if (const RecordType *RT =
2642 C.getBaseElementType(T)->getAs<RecordType>())
2643 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2644 return false;
2645 // TODO: Propagate nothrowness for implicitly declared special members.
2646 case UTT_HasNothrowAssign:
2647 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2648 // If type is const qualified or is a reference type then the
2649 // trait is false. Otherwise if __has_trivial_assign (type)
2650 // is true then the trait is true, else if type is a cv class
2651 // or union type with copy assignment operators that are known
2652 // not to throw an exception then the trait is true, else it is
2653 // false.
2654 if (C.getBaseElementType(T).isConstQualified())
2655 return false;
2656 if (T->isReferenceType())
2657 return false;
2658 if (T->isPODType())
2659 return true;
2660 if (const RecordType *RT = T->getAs<RecordType>()) {
2661 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2662 if (RD->hasTrivialCopyAssignment())
2663 return true;
2664
2665 bool FoundAssign = false;
2666 bool AllNoThrow = true;
2667 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redl058fc822010-09-14 23:40:14 +00002668 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2669 Sema::LookupOrdinaryName);
2670 if (Self.LookupQualifiedName(Res, RD)) {
2671 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2672 Op != OpEnd; ++Op) {
2673 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2674 if (Operator->isCopyAssignmentOperator()) {
2675 FoundAssign = true;
2676 const FunctionProtoType *CPT
2677 = Operator->getType()->getAs<FunctionProtoType>();
Sebastian Redl31ad7542011-03-13 17:09:40 +00002678 if (!CPT->isNothrow(Self.Context)) {
Sebastian Redl058fc822010-09-14 23:40:14 +00002679 AllNoThrow = false;
2680 break;
2681 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002682 }
2683 }
2684 }
2685
2686 return FoundAssign && AllNoThrow;
2687 }
2688 return false;
2689 case UTT_HasNothrowCopy:
2690 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2691 // If __has_trivial_copy (type) is true then the trait is true, else
2692 // if type is a cv class or union type with copy constructors that are
2693 // known not to throw an exception then the trait is true, else it is
2694 // false.
2695 if (T->isPODType() || T->isReferenceType())
2696 return true;
2697 if (const RecordType *RT = T->getAs<RecordType>()) {
2698 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2699 if (RD->hasTrivialCopyConstructor())
2700 return true;
2701
2702 bool FoundConstructor = false;
2703 bool AllNoThrow = true;
2704 unsigned FoundTQs;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002705 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl951006f2010-09-13 21:10:20 +00002706 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002707 Con != ConEnd; ++Con) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00002708 // A template constructor is never a copy constructor.
2709 // FIXME: However, it may actually be selected at the actual overload
2710 // resolution point.
2711 if (isa<FunctionTemplateDecl>(*Con))
2712 continue;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002713 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2714 if (Constructor->isCopyConstructor(FoundTQs)) {
2715 FoundConstructor = true;
2716 const FunctionProtoType *CPT
2717 = Constructor->getType()->getAs<FunctionProtoType>();
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002718 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00002719 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl31ad7542011-03-13 17:09:40 +00002720 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002721 AllNoThrow = false;
2722 break;
2723 }
2724 }
2725 }
2726
2727 return FoundConstructor && AllNoThrow;
2728 }
2729 return false;
2730 case UTT_HasNothrowConstructor:
2731 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2732 // If __has_trivial_constructor (type) is true then the trait is
2733 // true, else if type is a cv class or union type (or array
2734 // thereof) with a default constructor that is known not to
2735 // throw an exception then the trait is true, else it is false.
2736 if (T->isPODType())
2737 return true;
2738 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2739 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntf479f1b2011-05-09 18:22:59 +00002740 if (RD->hasTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002741 return true;
2742
Sebastian Redlc15c3262010-09-13 22:02:47 +00002743 DeclContext::lookup_const_iterator Con, ConEnd;
2744 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2745 Con != ConEnd; ++Con) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00002746 // FIXME: In C++0x, a constructor template can be a default constructor.
2747 if (isa<FunctionTemplateDecl>(*Con))
2748 continue;
Sebastian Redlc15c3262010-09-13 22:02:47 +00002749 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2750 if (Constructor->isDefaultConstructor()) {
2751 const FunctionProtoType *CPT
2752 = Constructor->getType()->getAs<FunctionProtoType>();
2753 // TODO: check whether evaluating default arguments can throw.
2754 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl31ad7542011-03-13 17:09:40 +00002755 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
Sebastian Redlc15c3262010-09-13 22:02:47 +00002756 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002757 }
2758 }
2759 return false;
2760 case UTT_HasVirtualDestructor:
2761 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2762 // If type is a class type with a virtual destructor ([class.dtor])
2763 // then the trait is true, else it is false.
2764 if (const RecordType *Record = T->getAs<RecordType>()) {
2765 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redl058fc822010-09-14 23:40:14 +00002766 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002767 return Destructor->isVirtual();
2768 }
2769 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002770
2771 // These type trait expressions are modeled on the specifications for the
2772 // Embarcadero C++0x type trait functions:
2773 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
2774 case UTT_IsCompleteType:
2775 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
2776 // Returns True if and only if T is a complete type at the point of the
2777 // function call.
2778 return !T->isIncompleteType();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002779 }
Chandler Carruthb42fb192011-05-01 07:44:17 +00002780 llvm_unreachable("Type trait not covered by switch");
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002781}
2782
2783ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor54e5b132010-09-09 16:14:44 +00002784 SourceLocation KWLoc,
2785 TypeSourceInfo *TSInfo,
2786 SourceLocation RParen) {
2787 QualType T = TSInfo->getType();
Chandler Carruthb0776202011-04-30 10:07:32 +00002788 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
2789 return ExprError();
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002790
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002791 bool Value = false;
2792 if (!T->isDependentType())
Chandler Carruth8e172c62011-05-01 06:51:22 +00002793 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002794
2795 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson1f9648d2009-07-07 19:06:02 +00002796 RParen, Context.BoolTy));
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002797}
Sebastian Redl5822f082009-02-07 20:10:22 +00002798
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002799ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
2800 SourceLocation KWLoc,
2801 ParsedType LhsTy,
2802 ParsedType RhsTy,
2803 SourceLocation RParen) {
2804 TypeSourceInfo *LhsTSInfo;
2805 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
2806 if (!LhsTSInfo)
2807 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
2808
2809 TypeSourceInfo *RhsTSInfo;
2810 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
2811 if (!RhsTSInfo)
2812 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
2813
2814 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
2815}
2816
2817static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
2818 QualType LhsT, QualType RhsT,
2819 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00002820 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
2821 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002822
2823 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00002824 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002825 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00002826 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002827 // Base and Derived are not unions and name the same class type without
2828 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002829
John McCall388ef532011-01-28 22:02:36 +00002830 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
2831 if (!lhsRecord) return false;
2832
2833 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
2834 if (!rhsRecord) return false;
2835
2836 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
2837 == (lhsRecord == rhsRecord));
2838
2839 if (lhsRecord == rhsRecord)
2840 return !lhsRecord->getDecl()->isUnion();
2841
2842 // C++0x [meta.rel]p2:
2843 // If Base and Derived are class types and are different types
2844 // (ignoring possible cv-qualifiers) then Derived shall be a
2845 // complete type.
2846 if (Self.RequireCompleteType(KeyLoc, RhsT,
2847 diag::err_incomplete_type_used_in_type_trait_expr))
2848 return false;
2849
2850 return cast<CXXRecordDecl>(rhsRecord->getDecl())
2851 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
2852 }
John Wiegley65497cc2011-04-27 23:09:49 +00002853 case BTT_IsSame:
2854 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichet34b21132010-12-08 22:35:30 +00002855 case BTT_TypeCompatible:
2856 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
2857 RhsT.getUnqualifiedType());
John Wiegley65497cc2011-04-27 23:09:49 +00002858 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00002859 case BTT_IsConvertibleTo: {
2860 // C++0x [meta.rel]p4:
2861 // Given the following function prototype:
2862 //
2863 // template <class T>
2864 // typename add_rvalue_reference<T>::type create();
2865 //
2866 // the predicate condition for a template specialization
2867 // is_convertible<From, To> shall be satisfied if and only if
2868 // the return expression in the following code would be
2869 // well-formed, including any implicit conversions to the return
2870 // type of the function:
2871 //
2872 // To test() {
2873 // return create<From>();
2874 // }
2875 //
2876 // Access checking is performed as if in a context unrelated to To and
2877 // From. Only the validity of the immediate context of the expression
2878 // of the return-statement (including conversions to the return type)
2879 // is considered.
2880 //
2881 // We model the initialization as a copy-initialization of a temporary
2882 // of the appropriate type, which for this expression is identical to the
2883 // return statement (since NRVO doesn't apply).
2884 if (LhsT->isObjectType() || LhsT->isFunctionType())
2885 LhsT = Self.Context.getRValueReferenceType(LhsT);
2886
2887 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00002888 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00002889 Expr::getValueKindForType(LhsT));
2890 Expr *FromPtr = &From;
2891 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
2892 SourceLocation()));
2893
Douglas Gregoredb76852011-01-27 22:31:44 +00002894 // Perform the initialization within a SFINAE trap at translation unit
2895 // scope.
2896 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
2897 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor8006e762011-01-27 20:28:01 +00002898 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002899 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00002900 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00002901
Douglas Gregor8006e762011-01-27 20:28:01 +00002902 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
2903 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
2904 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002905 }
2906 llvm_unreachable("Unknown type trait or not implemented");
2907}
2908
2909ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
2910 SourceLocation KWLoc,
2911 TypeSourceInfo *LhsTSInfo,
2912 TypeSourceInfo *RhsTSInfo,
2913 SourceLocation RParen) {
2914 QualType LhsT = LhsTSInfo->getType();
2915 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002916
John McCall388ef532011-01-28 22:02:36 +00002917 if (BTT == BTT_TypeCompatible) {
Francois Pichet34b21132010-12-08 22:35:30 +00002918 if (getLangOptions().CPlusPlus) {
2919 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
2920 << SourceRange(KWLoc, RParen);
2921 return ExprError();
2922 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002923 }
2924
2925 bool Value = false;
2926 if (!LhsT->isDependentType() && !RhsT->isDependentType())
2927 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
2928
Francois Pichet34b21132010-12-08 22:35:30 +00002929 // Select trait result type.
2930 QualType ResultType;
2931 switch (BTT) {
Francois Pichet34b21132010-12-08 22:35:30 +00002932 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
John Wiegley65497cc2011-04-27 23:09:49 +00002933 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
2934 case BTT_IsSame: ResultType = Context.BoolTy; break;
Francois Pichet34b21132010-12-08 22:35:30 +00002935 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor8006e762011-01-27 20:28:01 +00002936 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Francois Pichet34b21132010-12-08 22:35:30 +00002937 }
2938
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002939 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
2940 RhsTSInfo, Value, RParen,
Francois Pichet34b21132010-12-08 22:35:30 +00002941 ResultType));
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002942}
2943
John Wiegley6242b6a2011-04-28 00:16:57 +00002944ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
2945 SourceLocation KWLoc,
2946 ParsedType Ty,
2947 Expr* DimExpr,
2948 SourceLocation RParen) {
2949 TypeSourceInfo *TSInfo;
2950 QualType T = GetTypeFromParser(Ty, &TSInfo);
2951 if (!TSInfo)
2952 TSInfo = Context.getTrivialTypeSourceInfo(T);
2953
2954 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
2955}
2956
2957static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
2958 QualType T, Expr *DimExpr,
2959 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00002960 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00002961
2962 switch(ATT) {
2963 case ATT_ArrayRank:
2964 if (T->isArrayType()) {
2965 unsigned Dim = 0;
2966 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
2967 ++Dim;
2968 T = AT->getElementType();
2969 }
2970 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00002971 }
John Wiegleyd3522222011-04-28 02:06:46 +00002972 return 0;
2973
John Wiegley6242b6a2011-04-28 00:16:57 +00002974 case ATT_ArrayExtent: {
2975 llvm::APSInt Value;
2976 uint64_t Dim;
John Wiegleyd3522222011-04-28 02:06:46 +00002977 if (DimExpr->isIntegerConstantExpr(Value, Self.Context, 0, false)) {
2978 if (Value < llvm::APSInt(Value.getBitWidth(), Value.isUnsigned())) {
2979 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
2980 DimExpr->getSourceRange();
2981 return false;
2982 }
John Wiegley6242b6a2011-04-28 00:16:57 +00002983 Dim = Value.getLimitedValue();
John Wiegleyd3522222011-04-28 02:06:46 +00002984 } else {
2985 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
2986 DimExpr->getSourceRange();
2987 return false;
2988 }
John Wiegley6242b6a2011-04-28 00:16:57 +00002989
2990 if (T->isArrayType()) {
2991 unsigned D = 0;
2992 bool Matched = false;
2993 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
2994 if (Dim == D) {
2995 Matched = true;
2996 break;
2997 }
2998 ++D;
2999 T = AT->getElementType();
3000 }
3001
John Wiegleyd3522222011-04-28 02:06:46 +00003002 if (Matched && T->isArrayType()) {
3003 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3004 return CAT->getSize().getLimitedValue();
3005 }
John Wiegley6242b6a2011-04-28 00:16:57 +00003006 }
John Wiegleyd3522222011-04-28 02:06:46 +00003007 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00003008 }
3009 }
3010 llvm_unreachable("Unknown type trait or not implemented");
3011}
3012
3013ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3014 SourceLocation KWLoc,
3015 TypeSourceInfo *TSInfo,
3016 Expr* DimExpr,
3017 SourceLocation RParen) {
3018 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00003019
Chandler Carruthc5276e52011-05-01 08:48:21 +00003020 // FIXME: This should likely be tracked as an APInt to remove any host
3021 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00003022 uint64_t Value = 0;
3023 if (!T->isDependentType())
3024 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3025
Chandler Carruthc5276e52011-05-01 08:48:21 +00003026 // While the specification for these traits from the Embarcadero C++
3027 // compiler's documentation says the return type is 'unsigned int', Clang
3028 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3029 // compiler, there is no difference. On several other platforms this is an
3030 // important distinction.
John Wiegley6242b6a2011-04-28 00:16:57 +00003031 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
Chandler Carruth9cf632c2011-05-01 07:49:26 +00003032 DimExpr, RParen,
Chandler Carruthc5276e52011-05-01 08:48:21 +00003033 Context.getSizeType()));
John Wiegley6242b6a2011-04-28 00:16:57 +00003034}
3035
John Wiegleyf9f65842011-04-25 06:54:41 +00003036ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003037 SourceLocation KWLoc,
3038 Expr *Queried,
3039 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00003040 // If error parsing the expression, ignore.
3041 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003042 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00003043
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003044 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00003045
3046 return move(Result);
3047}
3048
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003049static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3050 switch (ET) {
3051 case ET_IsLValueExpr: return E->isLValue();
3052 case ET_IsRValueExpr: return E->isRValue();
3053 }
3054 llvm_unreachable("Expression trait not covered by switch");
3055}
3056
John Wiegleyf9f65842011-04-25 06:54:41 +00003057ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003058 SourceLocation KWLoc,
3059 Expr *Queried,
3060 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00003061 if (Queried->isTypeDependent()) {
3062 // Delay type-checking for type-dependent expressions.
3063 } else if (Queried->getType()->isPlaceholderType()) {
3064 ExprResult PE = CheckPlaceholderExpr(Queried);
3065 if (PE.isInvalid()) return ExprError();
3066 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3067 }
3068
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003069 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00003070
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003071 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3072 RParen, Context.BoolTy));
John Wiegleyf9f65842011-04-25 06:54:41 +00003073}
3074
John Wiegley01296292011-04-08 18:41:53 +00003075QualType Sema::CheckPointerToMemberOperands(ExprResult &lex, ExprResult &rex,
John McCall7decc9e2010-11-18 06:31:45 +00003076 ExprValueKind &VK,
3077 SourceLocation Loc,
3078 bool isIndirect) {
Sebastian Redl5822f082009-02-07 20:10:22 +00003079 const char *OpSpelling = isIndirect ? "->*" : ".*";
3080 // C++ 5.5p2
3081 // The binary operator .* [p3: ->*] binds its second operand, which shall
3082 // be of type "pointer to member of T" (where T is a completely-defined
3083 // class type) [...]
John Wiegley01296292011-04-08 18:41:53 +00003084 QualType RType = rex.get()->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003085 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00003086 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00003087 Diag(Loc, diag::err_bad_memptr_rhs)
John Wiegley01296292011-04-08 18:41:53 +00003088 << OpSpelling << RType << rex.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00003089 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00003090 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00003091
Sebastian Redl5822f082009-02-07 20:10:22 +00003092 QualType Class(MemPtr->getClass(), 0);
3093
Douglas Gregord07ba342010-10-13 20:41:14 +00003094 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3095 // member pointer points must be completely-defined. However, there is no
3096 // reason for this semantic distinction, and the rule is not enforced by
3097 // other compilers. Therefore, we do not check this property, as it is
3098 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00003099
Sebastian Redl5822f082009-02-07 20:10:22 +00003100 // C++ 5.5p2
3101 // [...] to its first operand, which shall be of class T or of a class of
3102 // which T is an unambiguous and accessible base class. [p3: a pointer to
3103 // such a class]
John Wiegley01296292011-04-08 18:41:53 +00003104 QualType LType = lex.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00003105 if (isIndirect) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003106 if (const PointerType *Ptr = LType->getAs<PointerType>())
John McCall7decc9e2010-11-18 06:31:45 +00003107 LType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00003108 else {
3109 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanian59f64202009-10-26 20:45:27 +00003110 << OpSpelling << 1 << LType
Douglas Gregora771f462010-03-31 17:46:05 +00003111 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00003112 return QualType();
3113 }
3114 }
3115
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003116 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00003117 // If we want to check the hierarchy, we need a complete type.
3118 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
3119 << OpSpelling << (int)isIndirect)) {
3120 return QualType();
3121 }
Anders Carlssona70cff62010-04-24 19:06:50 +00003122 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00003123 /*DetectVirtual=*/false);
Mike Stump87c57ac2009-05-16 07:39:55 +00003124 // FIXME: Would it be useful to print full ambiguity paths, or is that
3125 // overkill?
Sebastian Redl5822f082009-02-07 20:10:22 +00003126 if (!IsDerivedFrom(LType, Class, Paths) ||
3127 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3128 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
John Wiegley01296292011-04-08 18:41:53 +00003129 << (int)isIndirect << lex.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00003130 return QualType();
3131 }
Eli Friedman1fcf66b2010-01-16 00:00:48 +00003132 // Cast LHS to type of use.
3133 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
John McCall2536c6d2010-08-25 10:28:54 +00003134 ExprValueKind VK =
John Wiegley01296292011-04-08 18:41:53 +00003135 isIndirect ? VK_RValue : CastCategory(lex.get());
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003136
John McCallcf142162010-08-07 06:22:56 +00003137 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00003138 BuildBasePathArray(Paths, BasePath);
John Wiegley01296292011-04-08 18:41:53 +00003139 lex = ImpCastExprToType(lex.take(), UseType, CK_DerivedToBase, VK, &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00003140 }
3141
John Wiegley01296292011-04-08 18:41:53 +00003142 if (isa<CXXScalarValueInitExpr>(rex.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00003143 // Diagnose use of pointer-to-member type which when used as
3144 // the functional cast in a pointer-to-member expression.
3145 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3146 return QualType();
3147 }
John McCall7decc9e2010-11-18 06:31:45 +00003148
Sebastian Redl5822f082009-02-07 20:10:22 +00003149 // C++ 5.5p2
3150 // The result is an object or a function of the type specified by the
3151 // second operand.
3152 // The cv qualifiers are the union of those in the pointer and the left side,
3153 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00003154 QualType Result = MemPtr->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00003155 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00003156
Douglas Gregor1d042092011-01-26 16:40:18 +00003157 // C++0x [expr.mptr.oper]p6:
3158 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003159 // ill-formed if the second operand is a pointer to member function with
3160 // ref-qualifier &. In a ->* expression or in a .* expression whose object
3161 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00003162 // is a pointer to member function with ref-qualifier &&.
3163 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3164 switch (Proto->getRefQualifier()) {
3165 case RQ_None:
3166 // Do nothing
3167 break;
3168
3169 case RQ_LValue:
John Wiegley01296292011-04-08 18:41:53 +00003170 if (!isIndirect && !lex.get()->Classify(Context).isLValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00003171 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
John Wiegley01296292011-04-08 18:41:53 +00003172 << RType << 1 << lex.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00003173 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003174
Douglas Gregor1d042092011-01-26 16:40:18 +00003175 case RQ_RValue:
John Wiegley01296292011-04-08 18:41:53 +00003176 if (isIndirect || !lex.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00003177 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
John Wiegley01296292011-04-08 18:41:53 +00003178 << RType << 0 << lex.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00003179 break;
3180 }
3181 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003182
John McCall7decc9e2010-11-18 06:31:45 +00003183 // C++ [expr.mptr.oper]p6:
3184 // The result of a .* expression whose second operand is a pointer
3185 // to a data member is of the same value category as its
3186 // first operand. The result of a .* expression whose second
3187 // operand is a pointer to a member function is a prvalue. The
3188 // result of an ->* expression is an lvalue if its second operand
3189 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00003190 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00003191 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00003192 return Context.BoundMemberTy;
3193 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00003194 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00003195 } else {
John Wiegley01296292011-04-08 18:41:53 +00003196 VK = lex.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00003197 }
John McCall7decc9e2010-11-18 06:31:45 +00003198
Sebastian Redl5822f082009-02-07 20:10:22 +00003199 return Result;
3200}
Sebastian Redl1a99f442009-04-16 17:51:27 +00003201
Sebastian Redl1a99f442009-04-16 17:51:27 +00003202/// \brief Try to convert a type to another according to C++0x 5.16p3.
3203///
3204/// This is part of the parameter validation for the ? operator. If either
3205/// value operand is a class type, the two operands are attempted to be
3206/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00003207/// It returns true if the program is ill-formed and has already been diagnosed
3208/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003209static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3210 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00003211 bool &HaveConversion,
3212 QualType &ToType) {
3213 HaveConversion = false;
3214 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003215
3216 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00003217 SourceLocation());
Sebastian Redl1a99f442009-04-16 17:51:27 +00003218 // C++0x 5.16p3
3219 // The process for determining whether an operand expression E1 of type T1
3220 // can be converted to match an operand expression E2 of type T2 is defined
3221 // as follows:
3222 // -- If E2 is an lvalue:
John McCall086a4642010-11-24 05:12:34 +00003223 bool ToIsLvalue = To->isLValue();
Douglas Gregorf9edf802010-03-26 20:59:55 +00003224 if (ToIsLvalue) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003225 // E1 can be converted to match E2 if E1 can be implicitly converted to
3226 // type "lvalue reference to T2", subject to the constraint that in the
3227 // conversion the reference must bind directly to E1.
Douglas Gregor838fcc32010-03-26 20:14:36 +00003228 QualType T = Self.Context.getLValueReferenceType(ToType);
3229 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003230
Douglas Gregor838fcc32010-03-26 20:14:36 +00003231 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3232 if (InitSeq.isDirectReferenceBinding()) {
3233 ToType = T;
3234 HaveConversion = true;
3235 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003236 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003237
Douglas Gregor838fcc32010-03-26 20:14:36 +00003238 if (InitSeq.isAmbiguous())
3239 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003240 }
John McCall65eb8792010-02-25 01:37:24 +00003241
Sebastian Redl1a99f442009-04-16 17:51:27 +00003242 // -- If E2 is an rvalue, or if the conversion above cannot be done:
3243 // -- if E1 and E2 have class type, and the underlying class types are
3244 // the same or one is a base class of the other:
3245 QualType FTy = From->getType();
3246 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003247 const RecordType *FRec = FTy->getAs<RecordType>();
3248 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003249 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregor838fcc32010-03-26 20:14:36 +00003250 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003251 if (FRec && TRec &&
Douglas Gregor838fcc32010-03-26 20:14:36 +00003252 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003253 // E1 can be converted to match E2 if the class of T2 is the
3254 // same type as, or a base class of, the class of T1, and
3255 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00003256 if (FRec == TRec || FDerivedFromT) {
3257 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00003258 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3259 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00003260 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00003261 HaveConversion = true;
3262 return false;
3263 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003264
Douglas Gregor838fcc32010-03-26 20:14:36 +00003265 if (InitSeq.isAmbiguous())
3266 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003267 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003268 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003269
Douglas Gregor838fcc32010-03-26 20:14:36 +00003270 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003271 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003272
Douglas Gregor838fcc32010-03-26 20:14:36 +00003273 // -- Otherwise: E1 can be converted to match E2 if E1 can be
3274 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003275 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00003276 // an rvalue).
3277 //
3278 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3279 // to the array-to-pointer or function-to-pointer conversions.
3280 if (!TTy->getAs<TagType>())
3281 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003282
Douglas Gregor838fcc32010-03-26 20:14:36 +00003283 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3284 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00003285 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00003286 ToType = TTy;
3287 if (InitSeq.isAmbiguous())
3288 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3289
Sebastian Redl1a99f442009-04-16 17:51:27 +00003290 return false;
3291}
3292
3293/// \brief Try to find a common type for two according to C++0x 5.16p5.
3294///
3295/// This is part of the parameter validation for the ? operator. If either
3296/// value operand is a class type, overload resolution is used to find a
3297/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00003298static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003299 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00003300 Expr *Args[2] = { LHS.get(), RHS.get() };
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003301 OverloadCandidateSet CandidateSet(QuestionLoc);
3302 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3303 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003304
3305 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003306 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00003307 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003308 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley01296292011-04-08 18:41:53 +00003309 ExprResult LHSRes =
3310 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3311 Best->Conversions[0], Sema::AA_Converting);
3312 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00003313 break;
John Wiegley01296292011-04-08 18:41:53 +00003314 LHS = move(LHSRes);
3315
3316 ExprResult RHSRes =
3317 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3318 Best->Conversions[1], Sema::AA_Converting);
3319 if (RHSRes.isInvalid())
3320 break;
3321 RHS = move(RHSRes);
Chandler Carruth30141632011-02-25 19:41:05 +00003322 if (Best->Function)
3323 Self.MarkDeclarationReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003324 return false;
John Wiegley01296292011-04-08 18:41:53 +00003325 }
3326
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003327 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003328
3329 // Emit a better diagnostic if one of the expressions is a null pointer
3330 // constant and the other is a pointer type. In this case, the user most
3331 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00003332 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003333 return true;
3334
3335 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00003336 << LHS.get()->getType() << RHS.get()->getType()
3337 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003338 return true;
3339
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003340 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003341 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00003342 << LHS.get()->getType() << RHS.get()->getType()
3343 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00003344 // FIXME: Print the possible common types by printing the return types of
3345 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003346 break;
3347
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003348 case OR_Deleted:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003349 assert(false && "Conditional operator has only built-in overloads");
3350 break;
3351 }
3352 return true;
3353}
3354
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003355/// \brief Perform an "extended" implicit conversion as returned by
3356/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00003357static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00003358 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley01296292011-04-08 18:41:53 +00003359 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00003360 SourceLocation());
John Wiegley01296292011-04-08 18:41:53 +00003361 Expr *Arg = E.take();
3362 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
3363 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
Douglas Gregor838fcc32010-03-26 20:14:36 +00003364 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003365 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003366
John Wiegley01296292011-04-08 18:41:53 +00003367 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003368 return false;
3369}
3370
Sebastian Redl1a99f442009-04-16 17:51:27 +00003371/// \brief Check the operands of ?: under C++ semantics.
3372///
3373/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
3374/// extension. In this case, LHS == Cond. (But they're not aliases.)
John Wiegley01296292011-04-08 18:41:53 +00003375QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCallc07a0c72011-02-17 10:25:35 +00003376 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00003377 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00003378 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
3379 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003380
3381 // C++0x 5.16p1
3382 // The first expression is contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00003383 if (!Cond.get()->isTypeDependent()) {
3384 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
3385 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00003386 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003387 Cond = move(CondRes);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003388 }
3389
John McCall7decc9e2010-11-18 06:31:45 +00003390 // Assume r-value.
3391 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00003392 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00003393
Sebastian Redl1a99f442009-04-16 17:51:27 +00003394 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00003395 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00003396 return Context.DependentTy;
3397
3398 // C++0x 5.16p2
3399 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00003400 QualType LTy = LHS.get()->getType();
3401 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003402 bool LVoid = LTy->isVoidType();
3403 bool RVoid = RTy->isVoidType();
3404 if (LVoid || RVoid) {
3405 // ... then the [l2r] conversions are performed on the second and third
3406 // operands ...
John Wiegley01296292011-04-08 18:41:53 +00003407 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3408 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3409 if (LHS.isInvalid() || RHS.isInvalid())
3410 return QualType();
3411 LTy = LHS.get()->getType();
3412 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003413
3414 // ... and one of the following shall hold:
3415 // -- The second or the third operand (but not both) is a throw-
3416 // expression; the result is of the type of the other and is an rvalue.
John Wiegley01296292011-04-08 18:41:53 +00003417 bool LThrow = isa<CXXThrowExpr>(LHS.get());
3418 bool RThrow = isa<CXXThrowExpr>(RHS.get());
Sebastian Redl1a99f442009-04-16 17:51:27 +00003419 if (LThrow && !RThrow)
3420 return RTy;
3421 if (RThrow && !LThrow)
3422 return LTy;
3423
3424 // -- Both the second and third operands have type void; the result is of
3425 // type void and is an rvalue.
3426 if (LVoid && RVoid)
3427 return Context.VoidTy;
3428
3429 // Neither holds, error.
3430 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3431 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00003432 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003433 return QualType();
3434 }
3435
3436 // Neither is void.
3437
3438 // C++0x 5.16p3
3439 // Otherwise, if the second and third operand have different types, and
3440 // either has (cv) class type, and attempt is made to convert each of those
3441 // operands to the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003442 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00003443 (LTy->isRecordType() || RTy->isRecordType())) {
3444 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3445 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00003446 QualType L2RType, R2LType;
3447 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00003448 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00003449 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003450 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00003451 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003452
Sebastian Redl1a99f442009-04-16 17:51:27 +00003453 // If both can be converted, [...] the program is ill-formed.
3454 if (HaveL2R && HaveR2L) {
3455 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00003456 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003457 return QualType();
3458 }
3459
3460 // If exactly one conversion is possible, that conversion is applied to
3461 // the chosen operand and the converted operands are used in place of the
3462 // original operands for the remainder of this section.
3463 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00003464 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00003465 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003466 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003467 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00003468 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00003469 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003470 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003471 }
3472 }
3473
3474 // C++0x 5.16p4
John McCall7decc9e2010-11-18 06:31:45 +00003475 // If the second and third operands are glvalues of the same value
3476 // category and have the same type, the result is of that type and
3477 // value category and it is a bit-field if the second or the third
3478 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00003479 // We only extend this to bitfields, not to the crazy other kinds of
3480 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00003481 bool Same = Context.hasSameType(LTy, RTy);
John McCall7decc9e2010-11-18 06:31:45 +00003482 if (Same &&
John Wiegley01296292011-04-08 18:41:53 +00003483 LHS.get()->isGLValue() &&
3484 LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
3485 LHS.get()->isOrdinaryOrBitFieldObject() &&
3486 RHS.get()->isOrdinaryOrBitFieldObject()) {
3487 VK = LHS.get()->getValueKind();
3488 if (LHS.get()->getObjectKind() == OK_BitField ||
3489 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00003490 OK = OK_BitField;
John McCall7decc9e2010-11-18 06:31:45 +00003491 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00003492 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003493
3494 // C++0x 5.16p5
3495 // Otherwise, the result is an rvalue. If the second and third operands
3496 // do not have the same type, and either has (cv) class type, ...
3497 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3498 // ... overload resolution is used to determine the conversions (if any)
3499 // to be applied to the operands. If the overload resolution fails, the
3500 // program is ill-formed.
3501 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3502 return QualType();
3503 }
3504
3505 // C++0x 5.16p6
3506 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3507 // conversions are performed on the second and third operands.
John Wiegley01296292011-04-08 18:41:53 +00003508 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3509 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3510 if (LHS.isInvalid() || RHS.isInvalid())
3511 return QualType();
3512 LTy = LHS.get()->getType();
3513 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003514
3515 // After those conversions, one of the following shall hold:
3516 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003517 // is of that type. If the operands have class type, the result
3518 // is a prvalue temporary of the result type, which is
3519 // copy-initialized from either the second operand or the third
3520 // operand depending on the value of the first operand.
3521 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3522 if (LTy->isRecordType()) {
3523 // The operands have class type. Make a temporary copy.
3524 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003525 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3526 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00003527 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003528 if (LHSCopy.isInvalid())
3529 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003530
3531 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3532 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00003533 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003534 if (RHSCopy.isInvalid())
3535 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003536
John Wiegley01296292011-04-08 18:41:53 +00003537 LHS = LHSCopy;
3538 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003539 }
3540
Sebastian Redl1a99f442009-04-16 17:51:27 +00003541 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003542 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003543
Douglas Gregor46188682010-05-18 22:42:18 +00003544 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003545 if (LTy->isVectorType() || RTy->isVectorType())
Douglas Gregor46188682010-05-18 22:42:18 +00003546 return CheckVectorOperands(QuestionLoc, LHS, RHS);
3547
Sebastian Redl1a99f442009-04-16 17:51:27 +00003548 // -- The second and third operands have arithmetic or enumeration type;
3549 // the usual arithmetic conversions are performed to bring them to a
3550 // common type, and the result is of that type.
3551 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3552 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00003553 if (LHS.isInvalid() || RHS.isInvalid())
3554 return QualType();
3555 return LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003556 }
3557
3558 // -- The second and third operands have pointer type, or one has pointer
3559 // type and the other is a null pointer constant; pointer conversions
3560 // and qualification conversions are performed to bring them to their
3561 // composite pointer type. The result is of the composite pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00003562 // -- The second and third operands have pointer to member type, or one has
3563 // pointer to member type and the other is a null pointer constant;
3564 // pointer to member conversions and qualification conversions are
3565 // performed to bring them to a common type, whose cv-qualification
3566 // shall match the cv-qualification of either the second or the third
3567 // operand. The result is of the common type.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003568 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00003569 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003570 isSFINAEContext()? 0 : &NonStandardCompositeType);
3571 if (!Composite.isNull()) {
3572 if (NonStandardCompositeType)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003573 Diag(QuestionLoc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003574 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3575 << LTy << RTy << Composite
John Wiegley01296292011-04-08 18:41:53 +00003576 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003577
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003578 return Composite;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003579 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003580
Douglas Gregor697a3912010-04-01 22:47:07 +00003581 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00003582 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3583 if (!Composite.isNull())
3584 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003585
Chandler Carruth9c9127e2011-02-19 00:13:59 +00003586 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00003587 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00003588 return QualType();
3589
Sebastian Redl1a99f442009-04-16 17:51:27 +00003590 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00003591 << LHS.get()->getType() << RHS.get()->getType()
3592 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003593 return QualType();
3594}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003595
3596/// \brief Find a merged pointer type and convert the two expressions to it.
3597///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003598/// This finds the composite pointer type (or member pointer type) for @p E1
3599/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3600/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003601/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003602///
Douglas Gregor19175ff2010-04-16 23:20:25 +00003603/// \param Loc The location of the operator requiring these two expressions to
3604/// be converted to the composite pointer type.
3605///
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003606/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3607/// a non-standard (but still sane) composite type to which both expressions
3608/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3609/// will be set true.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003610QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00003611 Expr *&E1, Expr *&E2,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003612 bool *NonStandardCompositeType) {
3613 if (NonStandardCompositeType)
3614 *NonStandardCompositeType = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003615
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003616 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3617 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003618
Fariborz Jahanian33e148f2009-12-08 20:04:24 +00003619 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3620 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003621 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003622
3623 // C++0x 5.9p2
3624 // Pointer conversions and qualification conversions are performed on
3625 // pointer operands to bring them to their composite pointer type. If
3626 // one operand is a null pointer constant, the composite pointer type is
3627 // the type of the other operand.
Douglas Gregor56751b52009-09-25 04:25:58 +00003628 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003629 if (T2->isMemberPointerType())
John Wiegley01296292011-04-08 18:41:53 +00003630 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003631 else
John Wiegley01296292011-04-08 18:41:53 +00003632 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003633 return T2;
3634 }
Douglas Gregor56751b52009-09-25 04:25:58 +00003635 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003636 if (T1->isMemberPointerType())
John Wiegley01296292011-04-08 18:41:53 +00003637 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003638 else
John Wiegley01296292011-04-08 18:41:53 +00003639 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003640 return T1;
3641 }
Mike Stump11289f42009-09-09 15:08:12 +00003642
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003643 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00003644 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3645 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003646 return QualType();
3647
3648 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3649 // the other has type "pointer to cv2 T" and the composite pointer type is
3650 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3651 // Otherwise, the composite pointer type is a pointer type similar to the
3652 // type of one of the operands, with a cv-qualification signature that is
3653 // the union of the cv-qualification signatures of the operand types.
3654 // In practice, the first part here is redundant; it's subsumed by the second.
3655 // What we do here is, we build the two possible composite types, and try the
3656 // conversions in both directions. If only one works, or if the two composite
3657 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00003658 // FIXME: extended qualifiers?
Sebastian Redl658262f2009-11-16 21:03:45 +00003659 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
3660 QualifierVector QualifierUnion;
3661 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
3662 ContainingClassVector;
3663 ContainingClassVector MemberOfClass;
3664 QualType Composite1 = Context.getCanonicalType(T1),
3665 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003666 unsigned NeedConstBefore = 0;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003667 do {
3668 const PointerType *Ptr1, *Ptr2;
3669 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3670 (Ptr2 = Composite2->getAs<PointerType>())) {
3671 Composite1 = Ptr1->getPointeeType();
3672 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003673
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003674 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003675 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003676 if (NonStandardCompositeType &&
3677 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3678 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003679
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003680 QualifierUnion.push_back(
3681 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3682 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3683 continue;
3684 }
Mike Stump11289f42009-09-09 15:08:12 +00003685
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003686 const MemberPointerType *MemPtr1, *MemPtr2;
3687 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3688 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3689 Composite1 = MemPtr1->getPointeeType();
3690 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003691
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003692 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003693 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003694 if (NonStandardCompositeType &&
3695 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3696 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003697
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003698 QualifierUnion.push_back(
3699 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3700 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3701 MemPtr2->getClass()));
3702 continue;
3703 }
Mike Stump11289f42009-09-09 15:08:12 +00003704
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003705 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00003706
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003707 // Cannot unwrap any more types.
3708 break;
3709 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00003710
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003711 if (NeedConstBefore && NonStandardCompositeType) {
3712 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003713 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003714 // requirements of C++ [conv.qual]p4 bullet 3.
3715 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3716 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3717 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3718 *NonStandardCompositeType = true;
3719 }
3720 }
3721 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003722
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003723 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-11-16 21:03:45 +00003724 ContainingClassVector::reverse_iterator MOC
3725 = MemberOfClass.rbegin();
3726 for (QualifierVector::reverse_iterator
3727 I = QualifierUnion.rbegin(),
3728 E = QualifierUnion.rend();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003729 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00003730 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003731 if (MOC->first && MOC->second) {
3732 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00003733 Composite1 = Context.getMemberPointerType(
3734 Context.getQualifiedType(Composite1, Quals),
3735 MOC->first);
3736 Composite2 = Context.getMemberPointerType(
3737 Context.getQualifiedType(Composite2, Quals),
3738 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003739 } else {
3740 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00003741 Composite1
3742 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3743 Composite2
3744 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003745 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003746 }
3747
Douglas Gregor19175ff2010-04-16 23:20:25 +00003748 // Try to convert to the first composite pointer type.
3749 InitializedEntity Entity1
3750 = InitializedEntity::InitializeTemporary(Composite1);
3751 InitializationKind Kind
3752 = InitializationKind::CreateCopy(Loc, SourceLocation());
3753 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3754 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump11289f42009-09-09 15:08:12 +00003755
Douglas Gregor19175ff2010-04-16 23:20:25 +00003756 if (E1ToC1 && E2ToC1) {
3757 // Conversion to Composite1 is viable.
3758 if (!Context.hasSameType(Composite1, Composite2)) {
3759 // Composite2 is a different type from Composite1. Check whether
3760 // Composite2 is also viable.
3761 InitializedEntity Entity2
3762 = InitializedEntity::InitializeTemporary(Composite2);
3763 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3764 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3765 if (E1ToC2 && E2ToC2) {
3766 // Both Composite1 and Composite2 are viable and are different;
3767 // this is an ambiguity.
3768 return QualType();
3769 }
3770 }
3771
3772 // Convert E1 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00003773 ExprResult E1Result
John McCall37ad5512010-08-23 06:44:23 +00003774 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00003775 if (E1Result.isInvalid())
3776 return QualType();
3777 E1 = E1Result.takeAs<Expr>();
3778
3779 // Convert E2 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00003780 ExprResult E2Result
John McCall37ad5512010-08-23 06:44:23 +00003781 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00003782 if (E2Result.isInvalid())
3783 return QualType();
3784 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003785
Douglas Gregor19175ff2010-04-16 23:20:25 +00003786 return Composite1;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003787 }
3788
Douglas Gregor19175ff2010-04-16 23:20:25 +00003789 // Check whether Composite2 is viable.
3790 InitializedEntity Entity2
3791 = InitializedEntity::InitializeTemporary(Composite2);
3792 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3793 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3794 if (!E1ToC2 || !E2ToC2)
3795 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003796
Douglas Gregor19175ff2010-04-16 23:20:25 +00003797 // Convert E1 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00003798 ExprResult E1Result
John McCall37ad5512010-08-23 06:44:23 +00003799 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00003800 if (E1Result.isInvalid())
3801 return QualType();
3802 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003803
Douglas Gregor19175ff2010-04-16 23:20:25 +00003804 // Convert E2 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00003805 ExprResult E2Result
John McCall37ad5512010-08-23 06:44:23 +00003806 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00003807 if (E2Result.isInvalid())
3808 return QualType();
3809 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003810
Douglas Gregor19175ff2010-04-16 23:20:25 +00003811 return Composite2;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003812}
Anders Carlsson85a307d2009-05-17 18:41:29 +00003813
John McCalldadc5752010-08-24 06:29:42 +00003814ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00003815 if (!E)
3816 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003817
Anders Carlssonf86a8d12009-08-15 23:41:35 +00003818 if (!Context.getLangOptions().CPlusPlus)
3819 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00003820
Douglas Gregor363b1512009-12-24 18:51:59 +00003821 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
3822
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003823 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlsson2d4cada2009-05-30 20:36:53 +00003824 if (!RT)
3825 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00003826
Douglas Gregora57a66e2011-02-08 02:14:35 +00003827 // If the result is a glvalue, we shouldn't bind it.
3828 if (E->Classify(Context).isGLValue())
3829 return Owned(E);
John McCall67da35c2010-02-04 22:26:26 +00003830
3831 // That should be enough to guarantee that this type is complete.
3832 // If it has a trivial destructor, we can avoid the extra copy.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00003833 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCallbdb989e2010-08-12 02:40:37 +00003834 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall67da35c2010-02-04 22:26:26 +00003835 return Owned(E);
3836
Douglas Gregore71edda2010-07-01 22:47:18 +00003837 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
Anders Carlssonc78576e2009-05-30 21:21:49 +00003838 ExprTemporaries.push_back(Temp);
Douglas Gregore71edda2010-07-01 22:47:18 +00003839 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Fariborz Jahanian67828442009-08-03 19:13:25 +00003840 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00003841 CheckDestructorAccess(E->getExprLoc(), Destructor,
3842 PDiag(diag::err_access_dtor_temp)
3843 << E->getType());
3844 }
Anders Carlsson2d4cada2009-05-30 20:36:53 +00003845 // FIXME: Add the temporary to the temporaries vector.
3846 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
3847}
3848
John McCall5d413782010-12-06 08:20:24 +00003849Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Anders Carlssonb3d05d62009-06-05 15:38:08 +00003850 assert(SubExpr && "sub expression can't be null!");
Mike Stump11289f42009-09-09 15:08:12 +00003851
Douglas Gregor580cd4a2009-12-03 17:10:37 +00003852 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3853 assert(ExprTemporaries.size() >= FirstTemporary);
3854 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlssonb3d05d62009-06-05 15:38:08 +00003855 return SubExpr;
Mike Stump11289f42009-09-09 15:08:12 +00003856
John McCall5d413782010-12-06 08:20:24 +00003857 Expr *E = ExprWithCleanups::Create(Context, SubExpr,
3858 &ExprTemporaries[FirstTemporary],
3859 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor580cd4a2009-12-03 17:10:37 +00003860 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
3861 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00003862
Anders Carlssonb3d05d62009-06-05 15:38:08 +00003863 return E;
3864}
3865
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003866ExprResult
John McCall5d413782010-12-06 08:20:24 +00003867Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00003868 if (SubExpr.isInvalid())
3869 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003870
John McCall5d413782010-12-06 08:20:24 +00003871 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00003872}
3873
John McCall5d413782010-12-06 08:20:24 +00003874Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00003875 assert(SubStmt && "sub statement can't be null!");
3876
3877 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3878 assert(ExprTemporaries.size() >= FirstTemporary);
3879 if (ExprTemporaries.size() == FirstTemporary)
3880 return SubStmt;
3881
3882 // FIXME: In order to attach the temporaries, wrap the statement into
3883 // a StmtExpr; currently this is only used for asm statements.
3884 // This is hacky, either create a new CXXStmtWithTemporaries statement or
3885 // a new AsmStmtWithTemporaries.
3886 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
3887 SourceLocation(),
3888 SourceLocation());
3889 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
3890 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00003891 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00003892}
3893
John McCalldadc5752010-08-24 06:29:42 +00003894ExprResult
John McCallb268a282010-08-23 23:25:46 +00003895Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallba7bf592010-08-24 05:47:05 +00003896 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00003897 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003898 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003899 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003900 if (Result.isInvalid()) return ExprError();
3901 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00003902
John McCallb268a282010-08-23 23:25:46 +00003903 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00003904 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003905 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00003906 // If we have a pointer to a dependent type and are using the -> operator,
3907 // the object type is the type that the pointer points to. We might still
3908 // have enough information about that type to do something useful.
3909 if (OpKind == tok::arrow)
3910 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3911 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003912
John McCallba7bf592010-08-24 05:47:05 +00003913 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00003914 MayBePseudoDestructor = true;
John McCallb268a282010-08-23 23:25:46 +00003915 return Owned(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003916 }
Mike Stump11289f42009-09-09 15:08:12 +00003917
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003918 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00003919 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003920 // returned, with the original second operand.
3921 if (OpKind == tok::arrow) {
John McCallc1538c02009-09-30 01:01:30 +00003922 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00003923 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00003924 llvm::SmallVector<SourceLocation, 8> Locations;
John McCallbd0465b2009-09-30 01:30:54 +00003925 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003926
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003927 while (BaseType->isRecordType()) {
John McCallb268a282010-08-23 23:25:46 +00003928 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
3929 if (Result.isInvalid())
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003930 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00003931 Base = Result.get();
3932 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonfbd2d492009-10-13 22:55:59 +00003933 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallb268a282010-08-23 23:25:46 +00003934 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00003935 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCallbd0465b2009-09-30 01:30:54 +00003936 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00003937 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00003938 for (unsigned i = 0; i < Locations.size(); i++)
3939 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00003940 return ExprError();
3941 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003942 }
Mike Stump11289f42009-09-09 15:08:12 +00003943
Douglas Gregore4f764f2009-11-20 19:58:21 +00003944 if (BaseType->isPointerType())
3945 BaseType = BaseType->getPointeeType();
3946 }
Mike Stump11289f42009-09-09 15:08:12 +00003947
3948 // We could end up with various non-record types here, such as extended
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003949 // vector types or Objective-C interfaces. Just return early and let
3950 // ActOnMemberReferenceExpr do the work.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00003951 if (!BaseType->isRecordType()) {
3952 // C++ [basic.lookup.classref]p2:
3953 // [...] If the type of the object expression is of pointer to scalar
3954 // type, the unqualified-id is looked up in the context of the complete
3955 // postfix-expression.
Douglas Gregore610ada2010-02-24 18:44:31 +00003956 //
3957 // This also indicates that we should be parsing a
3958 // pseudo-destructor-name.
John McCallba7bf592010-08-24 05:47:05 +00003959 ObjectType = ParsedType();
Douglas Gregore610ada2010-02-24 18:44:31 +00003960 MayBePseudoDestructor = true;
John McCallb268a282010-08-23 23:25:46 +00003961 return Owned(Base);
Douglas Gregor2b6ca462009-09-03 21:38:09 +00003962 }
Mike Stump11289f42009-09-09 15:08:12 +00003963
Douglas Gregor3fad6172009-11-17 05:17:33 +00003964 // The object type must be complete (or dependent).
3965 if (!BaseType->isDependentType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003966 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor3fad6172009-11-17 05:17:33 +00003967 PDiag(diag::err_incomplete_member_access)))
3968 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003969
Douglas Gregor2b6ca462009-09-03 21:38:09 +00003970 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00003971 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00003972 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00003973 // type C (or of pointer to a class type C), the unqualified-id is looked
3974 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00003975 ObjectType = ParsedType::make(BaseType);
Mike Stump11289f42009-09-09 15:08:12 +00003976 return move(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003977}
3978
John McCalldadc5752010-08-24 06:29:42 +00003979ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCallb268a282010-08-23 23:25:46 +00003980 Expr *MemExpr) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003981 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCallb268a282010-08-23 23:25:46 +00003982 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
3983 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregora771f462010-03-31 17:46:05 +00003984 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003985
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003986 return ActOnCallExpr(/*Scope*/ 0,
John McCallb268a282010-08-23 23:25:46 +00003987 MemExpr,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003988 /*LPLoc*/ ExpectedLParenLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00003989 MultiExprArg(),
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003990 /*RPLoc*/ ExpectedLParenLoc);
3991}
Douglas Gregore610ada2010-02-24 18:44:31 +00003992
John McCalldadc5752010-08-24 06:29:42 +00003993ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00003994 SourceLocation OpLoc,
3995 tok::TokenKind OpKind,
3996 const CXXScopeSpec &SS,
3997 TypeSourceInfo *ScopeTypeInfo,
3998 SourceLocation CCLoc,
3999 SourceLocation TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00004000 PseudoDestructorTypeStorage Destructed,
John McCalla2c4e722011-02-25 05:21:17 +00004001 bool HasTrailingLParen) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00004002 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004003
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004004 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004005 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004006 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004007 // This scalar type is the object type.
John McCallb268a282010-08-23 23:25:46 +00004008 QualType ObjectType = Base->getType();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004009 if (OpKind == tok::arrow) {
4010 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4011 ObjectType = Ptr->getPointeeType();
John McCallb268a282010-08-23 23:25:46 +00004012 } else if (!Base->isTypeDependent()) {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004013 // The user wrote "p->" when she probably meant "p."; fix it.
4014 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4015 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00004016 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004017 if (isSFINAEContext())
4018 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004019
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004020 OpKind = tok::period;
4021 }
4022 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004023
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004024 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
4025 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCallb268a282010-08-23 23:25:46 +00004026 << ObjectType << Base->getSourceRange();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004027 return ExprError();
4028 }
4029
4030 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004031 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004032 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00004033 if (DestructedTypeInfo) {
4034 QualType DestructedType = DestructedTypeInfo->getType();
4035 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004036 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregor678f90d2010-02-25 01:56:36 +00004037 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
4038 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
4039 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00004040 << ObjectType << DestructedType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004041 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004042
Douglas Gregor678f90d2010-02-25 01:56:36 +00004043 // Recover by setting the destructed type to the object type.
4044 DestructedType = ObjectType;
4045 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4046 DestructedTypeStart);
4047 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4048 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004049 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004050
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004051 // C++ [expr.pseudo]p2:
4052 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4053 // form
4054 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004055 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004056 //
4057 // shall designate the same scalar type.
4058 if (ScopeTypeInfo) {
4059 QualType ScopeType = ScopeTypeInfo->getType();
4060 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00004061 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004062
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004063 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004064 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00004065 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004066 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004067
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004068 ScopeType = QualType();
4069 ScopeTypeInfo = 0;
4070 }
4071 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004072
John McCallb268a282010-08-23 23:25:46 +00004073 Expr *Result
4074 = new (Context) CXXPseudoDestructorExpr(Context, Base,
4075 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00004076 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00004077 ScopeTypeInfo,
4078 CCLoc,
4079 TildeLoc,
4080 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004081
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004082 if (HasTrailingLParen)
John McCallb268a282010-08-23 23:25:46 +00004083 return Owned(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004084
John McCallb268a282010-08-23 23:25:46 +00004085 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004086}
4087
John McCalldadc5752010-08-24 06:29:42 +00004088ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00004089 SourceLocation OpLoc,
4090 tok::TokenKind OpKind,
4091 CXXScopeSpec &SS,
4092 UnqualifiedId &FirstTypeName,
4093 SourceLocation CCLoc,
4094 SourceLocation TildeLoc,
4095 UnqualifiedId &SecondTypeName,
4096 bool HasTrailingLParen) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004097 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4098 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4099 "Invalid first type name in pseudo-destructor");
4100 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4101 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4102 "Invalid second type name in pseudo-destructor");
4103
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004104 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004105 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004106 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004107 // This scalar type is the object type.
John McCallb268a282010-08-23 23:25:46 +00004108 QualType ObjectType = Base->getType();
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004109 if (OpKind == tok::arrow) {
4110 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4111 ObjectType = Ptr->getPointeeType();
Douglas Gregor678f90d2010-02-25 01:56:36 +00004112 } else if (!ObjectType->isDependentType()) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004113 // The user wrote "p->" when she probably meant "p."; fix it.
4114 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregor678f90d2010-02-25 01:56:36 +00004115 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00004116 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004117 if (isSFINAEContext())
4118 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004119
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004120 OpKind = tok::period;
4121 }
4122 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00004123
4124 // Compute the object type that we should use for name lookup purposes. Only
4125 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00004126 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00004127 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00004128 if (ObjectType->isRecordType())
4129 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00004130 else if (ObjectType->isDependentType())
4131 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00004132 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004133
4134 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004135 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004136 QualType DestructedType;
4137 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregor678f90d2010-02-25 01:56:36 +00004138 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004139 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004140 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00004141 SecondTypeName.StartLocation,
Fariborz Jahanian87967422011-02-08 18:05:59 +00004142 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004143 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00004144 ((SS.isSet() && !computeDeclContext(SS, false)) ||
4145 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004146 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00004147 // couldn't find anything useful in scope. Just store the identifier and
4148 // it's location, and we'll perform (qualified) name lookup again at
4149 // template instantiation time.
4150 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
4151 SecondTypeName.StartLocation);
4152 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004153 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004154 diag::err_pseudo_dtor_destructor_non_type)
4155 << SecondTypeName.Identifier << ObjectType;
4156 if (isSFINAEContext())
4157 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004158
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004159 // Recover by assuming we had the right type all along.
4160 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004161 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004162 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004163 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004164 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004165 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004166 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4167 TemplateId->getTemplateArgs(),
4168 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00004169 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4170 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004171 TemplateId->TemplateNameLoc,
4172 TemplateId->LAngleLoc,
4173 TemplateArgsPtr,
4174 TemplateId->RAngleLoc);
4175 if (T.isInvalid() || !T.get()) {
4176 // Recover by assuming we had the right type all along.
4177 DestructedType = ObjectType;
4178 } else
4179 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004180 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004181
4182 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004183 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00004184 if (!DestructedType.isNull()) {
4185 if (!DestructedTypeInfo)
4186 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004187 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00004188 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4189 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004190
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004191 // Convert the name of the scope type (the type prior to '::') into a type.
4192 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004193 QualType ScopeType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004194 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004195 FirstTypeName.Identifier) {
4196 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004197 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00004198 FirstTypeName.StartLocation,
Douglas Gregora6ce6082011-02-25 18:19:59 +00004199 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004200 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004201 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004202 diag::err_pseudo_dtor_destructor_non_type)
4203 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004204
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004205 if (isSFINAEContext())
4206 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004207
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004208 // Just drop this type. It's unnecessary anyway.
4209 ScopeType = QualType();
4210 } else
4211 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004212 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004213 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004214 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004215 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4216 TemplateId->getTemplateArgs(),
4217 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00004218 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4219 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004220 TemplateId->TemplateNameLoc,
4221 TemplateId->LAngleLoc,
4222 TemplateArgsPtr,
4223 TemplateId->RAngleLoc);
4224 if (T.isInvalid() || !T.get()) {
4225 // Recover by dropping this type.
4226 ScopeType = QualType();
4227 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004228 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004229 }
4230 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004231
Douglas Gregor90ad9222010-02-24 23:02:30 +00004232 if (!ScopeType.isNull() && !ScopeTypeInfo)
4233 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
4234 FirstTypeName.StartLocation);
4235
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004236
John McCallb268a282010-08-23 23:25:46 +00004237 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00004238 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00004239 Destructed, HasTrailingLParen);
Douglas Gregore610ada2010-02-24 18:44:31 +00004240}
4241
John Wiegley01296292011-04-08 18:41:53 +00004242ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Douglas Gregor668443e2011-01-20 00:18:04 +00004243 CXXMethodDecl *Method) {
John Wiegley01296292011-04-08 18:41:53 +00004244 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
4245 FoundDecl, Method);
4246 if (Exp.isInvalid())
Douglas Gregor668443e2011-01-20 00:18:04 +00004247 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00004248
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004249 MemberExpr *ME =
John Wiegley01296292011-04-08 18:41:53 +00004250 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
John McCall7decc9e2010-11-18 06:31:45 +00004251 SourceLocation(), Method->getType(),
4252 VK_RValue, OK_Ordinary);
4253 QualType ResultType = Method->getResultType();
4254 ExprValueKind VK = Expr::getValueKindForType(ResultType);
4255 ResultType = ResultType.getNonLValueExprType(Context);
4256
John Wiegley01296292011-04-08 18:41:53 +00004257 MarkDeclarationReferenced(Exp.get()->getLocStart(), Method);
Douglas Gregor27381f32009-11-23 12:27:39 +00004258 CXXMemberCallExpr *CE =
John McCall7decc9e2010-11-18 06:31:45 +00004259 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
John Wiegley01296292011-04-08 18:41:53 +00004260 Exp.get()->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00004261 return CE;
4262}
4263
Sebastian Redl4202c0f2010-09-10 20:55:43 +00004264ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4265 SourceLocation RParen) {
Sebastian Redl4202c0f2010-09-10 20:55:43 +00004266 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
4267 Operand->CanThrow(Context),
4268 KeyLoc, RParen));
4269}
4270
4271ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
4272 Expr *Operand, SourceLocation RParen) {
4273 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00004274}
4275
John McCall34376a62010-12-04 03:47:34 +00004276/// Perform the conversions required for an expression used in a
4277/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00004278ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCallfee942d2010-12-02 02:07:15 +00004279 // C99 6.3.2.1:
4280 // [Except in specific positions,] an lvalue that does not have
4281 // array type is converted to the value stored in the
4282 // designated object (and is no longer an lvalue).
John Wiegley01296292011-04-08 18:41:53 +00004283 if (E->isRValue()) return Owned(E);
John McCallfee942d2010-12-02 02:07:15 +00004284
John McCall34376a62010-12-04 03:47:34 +00004285 // We always want to do this on ObjC property references.
4286 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley01296292011-04-08 18:41:53 +00004287 ExprResult Res = ConvertPropertyForRValue(E);
4288 if (Res.isInvalid()) return Owned(E);
4289 E = Res.take();
4290 if (E->isRValue()) return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00004291 }
4292
4293 // Otherwise, this rule does not apply in C++, at least not for the moment.
John Wiegley01296292011-04-08 18:41:53 +00004294 if (getLangOptions().CPlusPlus) return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00004295
4296 // GCC seems to also exclude expressions of incomplete enum type.
4297 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
4298 if (!T->getDecl()->isComplete()) {
4299 // FIXME: stupid workaround for a codegen bug!
John Wiegley01296292011-04-08 18:41:53 +00004300 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
4301 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00004302 }
4303 }
4304
John Wiegley01296292011-04-08 18:41:53 +00004305 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
4306 if (Res.isInvalid())
4307 return Owned(E);
4308 E = Res.take();
4309
John McCallca61b652010-12-04 12:29:11 +00004310 if (!E->getType()->isVoidType())
4311 RequireCompleteType(E->getExprLoc(), E->getType(),
4312 diag::err_incomplete_type);
John Wiegley01296292011-04-08 18:41:53 +00004313 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00004314}
4315
John Wiegley01296292011-04-08 18:41:53 +00004316ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
4317 ExprResult FullExpr = Owned(FE);
4318
4319 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004320 return ExprError();
John McCall34376a62010-12-04 03:47:34 +00004321
John Wiegley01296292011-04-08 18:41:53 +00004322 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00004323 return ExprError();
4324
John McCall3aef3d82011-04-10 19:13:55 +00004325 FullExpr = CheckPlaceholderExpr(FullExpr.take());
4326 if (FullExpr.isInvalid())
4327 return ExprError();
Douglas Gregor0ec210b2011-03-07 02:05:23 +00004328
John Wiegley01296292011-04-08 18:41:53 +00004329 FullExpr = IgnoredValueConversions(FullExpr.take());
4330 if (FullExpr.isInvalid())
4331 return ExprError();
4332
4333 CheckImplicitConversions(FullExpr.get());
John McCall5d413782010-12-06 08:20:24 +00004334 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00004335}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004336
4337StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
4338 if (!FullStmt) return StmtError();
4339
John McCall5d413782010-12-06 08:20:24 +00004340 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004341}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00004342
4343bool Sema::CheckMicrosoftIfExistsSymbol(CXXScopeSpec &SS,
4344 UnqualifiedId &Name) {
4345 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
4346 DeclarationName TargetName = TargetNameInfo.getName();
4347 if (!TargetName)
4348 return false;
4349
4350 // Do the redeclaration lookup in the current scope.
4351 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
4352 Sema::NotForRedeclaration);
4353 R.suppressDiagnostics();
4354 LookupParsedName(R, getCurScope(), &SS);
4355 return !R.empty();
4356}