blob: edb4fef348434f47fed143a82993773f111abae5 [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"
Richard Smith938f40b2011-06-11 17:19:42 +000020#include "clang/Sema/Scope.h"
John McCall19c1bfd2010-08-25 05:32:35 +000021#include "clang/Sema/TemplateDeduction.h"
Steve Naroffaac94152007-08-25 14:02:58 +000022#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000025#include "clang/AST/ExprCXX.h"
Fariborz Jahanian1d446082010-06-16 18:56:04 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000027#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000029#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000030#include "clang/Lex/Preprocessor.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +000032#include "llvm/Support/ErrorHandling.h"
Chris Lattner29375652006-12-04 18:06:35 +000033using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000034using namespace sema;
Chris Lattner29375652006-12-04 18:06:35 +000035
John McCallba7bf592010-08-24 05:47:05 +000036ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000037 IdentifierInfo &II,
John McCallba7bf592010-08-24 05:47:05 +000038 SourceLocation NameLoc,
39 Scope *S, CXXScopeSpec &SS,
40 ParsedType ObjectTypePtr,
41 bool EnteringContext) {
Douglas Gregorfe17d252010-02-16 19:09:40 +000042 // Determine where to perform name lookup.
43
44 // FIXME: This area of the standard is very messy, and the current
45 // wording is rather unclear about which scopes we search for the
46 // destructor name; see core issues 399 and 555. Issue 399 in
47 // particular shows where the current description of destructor name
48 // lookup is completely out of line with existing practice, e.g.,
49 // this appears to be ill-formed:
50 //
51 // namespace N {
52 // template <typename T> struct S {
53 // ~S();
54 // };
55 // }
56 //
57 // void f(N::S<int>* s) {
58 // s->N::S<int>::~S();
59 // }
60 //
Douglas Gregor46841e12010-02-23 00:15:22 +000061 // See also PR6358 and PR6359.
Sebastian Redla771d222010-07-07 23:17:38 +000062 // For this reason, we're currently only doing the C++03 version of this
63 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregorfe17d252010-02-16 19:09:40 +000064 QualType SearchType;
65 DeclContext *LookupCtx = 0;
66 bool isDependent = false;
67 bool LookInScope = false;
68
69 // If we have an object type, it's because we are in a
70 // pseudo-destructor-expression or a member access expression, and
71 // we know what type we're looking for.
72 if (ObjectTypePtr)
73 SearchType = GetTypeFromParser(ObjectTypePtr);
74
75 if (SS.isSet()) {
Douglas Gregor46841e12010-02-23 00:15:22 +000076 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000077
Douglas Gregor46841e12010-02-23 00:15:22 +000078 bool AlreadySearched = false;
79 bool LookAtPrefix = true;
Sebastian Redla771d222010-07-07 23:17:38 +000080 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000081 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redla771d222010-07-07 23:17:38 +000082 // the type-names are looked up as types in the scope designated by the
83 // nested-name-specifier. In a qualified-id of the form:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +000084 //
85 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redla771d222010-07-07 23:17:38 +000086 //
87 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth8f254812010-02-21 10:19:54 +000088 // a qualified-id of the form:
Douglas Gregorfe17d252010-02-16 19:09:40 +000089 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +000090 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregorfe17d252010-02-16 19:09:40 +000091 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000092 // the class-names are looked up as types in the scope designated by
Sebastian Redla771d222010-07-07 23:17:38 +000093 // the nested-name-specifier.
Douglas Gregorfe17d252010-02-16 19:09:40 +000094 //
Sebastian Redla771d222010-07-07 23:17:38 +000095 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000096 // code below is permitted to look at the prefix of the
Sebastian Redla771d222010-07-07 23:17:38 +000097 // nested-name-specifier.
98 DeclContext *DC = computeDeclContext(SS, EnteringContext);
99 if (DC && DC->isFileContext()) {
100 AlreadySearched = true;
101 LookupCtx = DC;
102 isDependent = false;
103 } else if (DC && isa<CXXRecordDecl>(DC))
104 LookAtPrefix = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000105
Sebastian Redla771d222010-07-07 23:17:38 +0000106 // The second case from the C++03 rules quoted further above.
Douglas Gregor46841e12010-02-23 00:15:22 +0000107 NestedNameSpecifier *Prefix = 0;
108 if (AlreadySearched) {
109 // Nothing left to do.
110 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
111 CXXScopeSpec PrefixSS;
Douglas Gregor10176412011-02-25 16:07:42 +0000112 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor46841e12010-02-23 00:15:22 +0000113 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
114 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor46841e12010-02-23 00:15:22 +0000115 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000116 LookupCtx = computeDeclContext(SearchType);
117 isDependent = SearchType->isDependentType();
118 } else {
119 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000120 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000121 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000122
Douglas Gregorcd3f49f2010-02-25 04:46:04 +0000123 LookInScope = false;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000124 } else if (ObjectTypePtr) {
125 // C++ [basic.lookup.classref]p3:
126 // If the unqualified-id is ~type-name, the type-name is looked up
127 // in the context of the entire postfix-expression. If the type T
128 // of the object expression is of a class type C, the type-name is
129 // also looked up in the scope of class C. At least one of the
130 // lookups shall find a name that refers to (possibly
131 // cv-qualified) T.
132 LookupCtx = computeDeclContext(SearchType);
133 isDependent = SearchType->isDependentType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000134 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregorfe17d252010-02-16 19:09:40 +0000135 "Caller should have completed object type");
136
137 LookInScope = true;
138 } else {
139 // Perform lookup into the current scope (only).
140 LookInScope = true;
141 }
142
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000143 TypeDecl *NonMatchingTypeDecl = 0;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000144 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
145 for (unsigned Step = 0; Step != 2; ++Step) {
146 // Look for the name first in the computed lookup context (if we
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000147 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregorfe17d252010-02-16 19:09:40 +0000148 // we're allowed to look there).
149 Found.clear();
150 if (Step == 0 && LookupCtx)
151 LookupQualifiedName(Found, LookupCtx);
Douglas Gregor678f90d2010-02-25 01:56:36 +0000152 else if (Step == 1 && LookInScope && S)
Douglas Gregorfe17d252010-02-16 19:09:40 +0000153 LookupName(Found, S);
154 else
155 continue;
156
157 // FIXME: Should we be suppressing ambiguities here?
158 if (Found.isAmbiguous())
John McCallba7bf592010-08-24 05:47:05 +0000159 return ParsedType();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000160
161 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
162 QualType T = Context.getTypeDeclType(Type);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000163
164 if (SearchType.isNull() || SearchType->isDependentType() ||
165 Context.hasSameUnqualifiedType(T, SearchType)) {
166 // We found our type!
167
John McCallba7bf592010-08-24 05:47:05 +0000168 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000169 }
John Wiegleyb4a9e512011-03-08 08:13:22 +0000170
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000171 if (!SearchType.isNull())
172 NonMatchingTypeDecl = Type;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000173 }
174
175 // If the name that we found is a class template name, and it is
176 // the same name as the template name in the last part of the
177 // nested-name-specifier (if present) or the object type, then
178 // this is the destructor for that class.
179 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000180 // issue 399, for which there isn't even an obvious direction.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000181 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
182 QualType MemberOfType;
183 if (SS.isSet()) {
184 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
185 // Figure out the type of the context, if it has one.
John McCalle78aac42010-03-10 03:28:59 +0000186 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
187 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000188 }
189 }
190 if (MemberOfType.isNull())
191 MemberOfType = SearchType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000192
Douglas Gregorfe17d252010-02-16 19:09:40 +0000193 if (MemberOfType.isNull())
194 continue;
195
196 // We're referring into a class template specialization. If the
197 // class template we found is the same as the template being
198 // specialized, we found what we are looking for.
199 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
200 if (ClassTemplateSpecializationDecl *Spec
201 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
202 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
203 Template->getCanonicalDecl())
John McCallba7bf592010-08-24 05:47:05 +0000204 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000205 }
206
207 continue;
208 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000209
Douglas Gregorfe17d252010-02-16 19:09:40 +0000210 // We're referring to an unresolved class template
211 // specialization. Determine whether we class template we found
212 // is the same as the template being specialized or, if we don't
213 // know which template is being specialized, that it at least
214 // has the same name.
215 if (const TemplateSpecializationType *SpecType
216 = MemberOfType->getAs<TemplateSpecializationType>()) {
217 TemplateName SpecName = SpecType->getTemplateName();
218
219 // The class template we found is the same template being
220 // specialized.
221 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
222 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallba7bf592010-08-24 05:47:05 +0000223 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000224
225 continue;
226 }
227
228 // The class template we found has the same name as the
229 // (dependent) template name being specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000230 if (DependentTemplateName *DepTemplate
Douglas Gregorfe17d252010-02-16 19:09:40 +0000231 = SpecName.getAsDependentTemplateName()) {
232 if (DepTemplate->isIdentifier() &&
233 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallba7bf592010-08-24 05:47:05 +0000234 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000235
236 continue;
237 }
238 }
239 }
240 }
241
242 if (isDependent) {
243 // We didn't find our type, but that's okay: it's dependent
244 // anyway.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000245
246 // FIXME: What if we have no nested-name-specifier?
247 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
248 SS.getWithLocInContext(Context),
249 II, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +0000250 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000251 }
252
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000253 if (NonMatchingTypeDecl) {
254 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
255 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
256 << T << SearchType;
257 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
258 << T;
259 } else if (ObjectTypePtr)
260 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000261 << &II;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000262 else
263 Diag(NameLoc, diag::err_destructor_class_name);
264
John McCallba7bf592010-08-24 05:47:05 +0000265 return ParsedType();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000266}
267
Douglas Gregor9da64192010-04-26 22:37:10 +0000268/// \brief Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000269ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000270 SourceLocation TypeidLoc,
271 TypeSourceInfo *Operand,
272 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000273 // C++ [expr.typeid]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000274 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor9da64192010-04-26 22:37:10 +0000275 // that is the operand of typeid are always ignored.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000276 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor9da64192010-04-26 22:37:10 +0000277 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000278 Qualifiers Quals;
279 QualType T
280 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
281 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000282 if (T->getAs<RecordType>() &&
283 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
284 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000285
Douglas Gregor9da64192010-04-26 22:37:10 +0000286 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
287 Operand,
288 SourceRange(TypeidLoc, RParenLoc)));
289}
290
291/// \brief Build a C++ typeid expression with an expression operand.
John McCalldadc5752010-08-24 06:29:42 +0000292ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000293 SourceLocation TypeidLoc,
294 Expr *E,
295 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000296 bool isUnevaluatedOperand = true;
Douglas Gregor9da64192010-04-26 22:37:10 +0000297 if (E && !E->isTypeDependent()) {
John McCall50a2c2c2011-10-11 23:14:30 +0000298 if (E->getType()->isPlaceholderType()) {
299 ExprResult result = CheckPlaceholderExpr(E);
300 if (result.isInvalid()) return ExprError();
301 E = result.take();
302 }
303
Douglas Gregor9da64192010-04-26 22:37:10 +0000304 QualType T = E->getType();
305 if (const RecordType *RecordT = T->getAs<RecordType>()) {
306 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
307 // C++ [expr.typeid]p3:
308 // [...] If the type of the expression is a class type, the class
309 // shall be completely-defined.
310 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
311 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000312
Douglas Gregor9da64192010-04-26 22:37:10 +0000313 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000314 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000315 // polymorphic class type [...] [the] expression is an unevaluated
316 // operand. [...]
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000317 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000318 isUnevaluatedOperand = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000319
320 // We require a vtable to query the type at run time.
321 MarkVTableUsed(TypeidLoc, RecordD);
322 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000323 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000324
Douglas Gregor9da64192010-04-26 22:37:10 +0000325 // C++ [expr.typeid]p4:
326 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000327 // cv-qualified type, the result of the typeid expression refers to a
328 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor9da64192010-04-26 22:37:10 +0000329 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000330 Qualifiers Quals;
331 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
332 if (!Context.hasSameType(T, UnqualT)) {
333 T = UnqualT;
Eli Friedmanbe4b3632011-09-27 21:58:52 +0000334 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take();
Douglas Gregor9da64192010-04-26 22:37:10 +0000335 }
336 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000337
Douglas Gregor9da64192010-04-26 22:37:10 +0000338 // If this is an unevaluated operand, clear out the set of
339 // declaration references we have been computing and eliminate any
340 // temporaries introduced in its computation.
341 if (isUnevaluatedOperand)
342 ExprEvalContexts.back().Context = Unevaluated;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000343
Douglas Gregor9da64192010-04-26 22:37:10 +0000344 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCallb268a282010-08-23 23:25:46 +0000345 E,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000346 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor9da64192010-04-26 22:37:10 +0000347}
348
349/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000350ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000351Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
352 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000353 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000354 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000355 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000356
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000357 if (!CXXTypeInfoDecl) {
358 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
359 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
360 LookupQualifiedName(R, getStdNamespace());
361 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
362 if (!CXXTypeInfoDecl)
363 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
364 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000365
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000366 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000367
Douglas Gregor9da64192010-04-26 22:37:10 +0000368 if (isType) {
369 // The operand is a type; handle it as such.
370 TypeSourceInfo *TInfo = 0;
John McCallba7bf592010-08-24 05:47:05 +0000371 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
372 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000373 if (T.isNull())
374 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000375
Douglas Gregor9da64192010-04-26 22:37:10 +0000376 if (!TInfo)
377 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000378
Douglas Gregor9da64192010-04-26 22:37:10 +0000379 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000380 }
Mike Stump11289f42009-09-09 15:08:12 +0000381
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000382 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000383 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000384}
385
Francois Pichetb7577652010-12-27 01:32:00 +0000386/// Retrieve the UuidAttr associated with QT.
387static UuidAttr *GetUuidAttrOfType(QualType QT) {
388 // Optionally remove one level of pointer, reference or array indirection.
John McCall424cec92011-01-19 06:33:43 +0000389 const Type *Ty = QT.getTypePtr();;
Francois Pichet9dddd402010-12-20 03:51:03 +0000390 if (QT->isPointerType() || QT->isReferenceType())
391 Ty = QT->getPointeeType().getTypePtr();
392 else if (QT->isArrayType())
393 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
394
Francois Pichet59d2b012011-05-08 10:02:20 +0000395 // Loop all record redeclaration looking for an uuid attribute.
Francois Pichetb7577652010-12-27 01:32:00 +0000396 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Francois Pichet59d2b012011-05-08 10:02:20 +0000397 for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(),
398 E = RD->redecls_end(); I != E; ++I) {
399 if (UuidAttr *Uuid = I->getAttr<UuidAttr>())
Francois Pichetb7577652010-12-27 01:32:00 +0000400 return Uuid;
Francois Pichetb7577652010-12-27 01:32:00 +0000401 }
Francois Pichet59d2b012011-05-08 10:02:20 +0000402
Francois Pichetb7577652010-12-27 01:32:00 +0000403 return 0;
Francois Pichet9dddd402010-12-20 03:51:03 +0000404}
405
Francois Pichet9f4f2072010-09-08 12:20:18 +0000406/// \brief Build a Microsoft __uuidof expression with a type operand.
407ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
408 SourceLocation TypeidLoc,
409 TypeSourceInfo *Operand,
410 SourceLocation RParenLoc) {
Francois Pichetb7577652010-12-27 01:32:00 +0000411 if (!Operand->getType()->isDependentType()) {
412 if (!GetUuidAttrOfType(Operand->getType()))
413 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
414 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000415
Francois Pichet9f4f2072010-09-08 12:20:18 +0000416 // FIXME: add __uuidof semantic analysis for type operand.
417 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
418 Operand,
419 SourceRange(TypeidLoc, RParenLoc)));
420}
421
422/// \brief Build a Microsoft __uuidof expression with an expression operand.
423ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
424 SourceLocation TypeidLoc,
425 Expr *E,
426 SourceLocation RParenLoc) {
Francois Pichetb7577652010-12-27 01:32:00 +0000427 if (!E->getType()->isDependentType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000428 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichetb7577652010-12-27 01:32:00 +0000429 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
430 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
431 }
432 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000433 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
434 E,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000435 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000436}
437
438/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
439ExprResult
440Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
441 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000442 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000443 if (!MSVCGuidDecl) {
444 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
445 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
446 LookupQualifiedName(R, Context.getTranslationUnitDecl());
447 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
448 if (!MSVCGuidDecl)
449 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000450 }
451
Francois Pichet9f4f2072010-09-08 12:20:18 +0000452 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000453
Francois Pichet9f4f2072010-09-08 12:20:18 +0000454 if (isType) {
455 // The operand is a type; handle it as such.
456 TypeSourceInfo *TInfo = 0;
457 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
458 &TInfo);
459 if (T.isNull())
460 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000461
Francois Pichet9f4f2072010-09-08 12:20:18 +0000462 if (!TInfo)
463 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
464
465 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
466 }
467
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000468 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000469 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
470}
471
Steve Naroff66356bd2007-09-16 14:56:35 +0000472/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000473ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000474Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000475 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000476 "Unknown C++ Boolean value!");
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000477 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
478 Context.BoolTy, OpLoc));
Bill Wendling4073ed52007-02-13 01:51:42 +0000479}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000480
Sebastian Redl576fd422009-05-10 18:38:11 +0000481/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000482ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000483Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
484 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
485}
486
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000487/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000488ExprResult
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000489Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
490 bool IsThrownVarInScope = false;
491 if (Ex) {
492 // C++0x [class.copymove]p31:
493 // When certain criteria are met, an implementation is allowed to omit the
494 // copy/move construction of a class object [...]
495 //
496 // - in a throw-expression, when the operand is the name of a
497 // non-volatile automatic object (other than a function or catch-
498 // clause parameter) whose scope does not extend beyond the end of the
499 // innermost enclosing try-block (if there is one), the copy/move
500 // operation from the operand to the exception object (15.1) can be
501 // omitted by constructing the automatic object directly into the
502 // exception object
503 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
504 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
505 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
506 for( ; S; S = S->getParent()) {
507 if (S->isDeclScope(Var)) {
508 IsThrownVarInScope = true;
509 break;
510 }
511
512 if (S->getFlags() &
513 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
514 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
515 Scope::TryScope))
516 break;
517 }
518 }
519 }
520 }
521
522 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
523}
524
525ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
526 bool IsThrownVarInScope) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000527 // Don't report an error if 'throw' is used in system headers.
Anders Carlssone96ab552011-02-28 02:27:16 +0000528 if (!getLangOptions().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000529 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb94ad3e2011-02-19 21:53:09 +0000530 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000531
John Wiegley01296292011-04-08 18:41:53 +0000532 if (Ex && !Ex->isTypeDependent()) {
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000533 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
John Wiegley01296292011-04-08 18:41:53 +0000534 if (ExRes.isInvalid())
535 return ExprError();
536 Ex = ExRes.take();
537 }
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000538
539 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
540 IsThrownVarInScope));
Sebastian Redl4de47b42009-04-27 20:27:31 +0000541}
542
543/// CheckCXXThrowOperand - Validate the operand of a throw.
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000544ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
545 bool IsThrownVarInScope) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000546 // C++ [except.throw]p3:
Douglas Gregor247894b2009-12-23 22:04:40 +0000547 // A throw-expression initializes a temporary object, called the exception
548 // object, the type of which is determined by removing any top-level
549 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000550 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor247894b2009-12-23 22:04:40 +0000551 // or "pointer to function returning T", [...]
552 if (E->getType().hasQualifiers())
John Wiegley01296292011-04-08 18:41:53 +0000553 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Eli Friedmanbe4b3632011-09-27 21:58:52 +0000554 E->getValueKind()).take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000555
John Wiegley01296292011-04-08 18:41:53 +0000556 ExprResult Res = DefaultFunctionArrayConversion(E);
557 if (Res.isInvalid())
558 return ExprError();
559 E = Res.take();
Sebastian Redl4de47b42009-04-27 20:27:31 +0000560
561 // If the type of the exception would be an incomplete type or a pointer
562 // to an incomplete type other than (cv) void the program is ill-formed.
563 QualType Ty = E->getType();
John McCall2e6567a2010-04-22 01:10:34 +0000564 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000565 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000566 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000567 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000568 }
569 if (!isPointer || !Ty->isVoidType()) {
570 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlsson029fc692009-08-26 22:59:12 +0000571 PDiag(isPointer ? diag::err_throw_incomplete_ptr
572 : diag::err_throw_incomplete)
573 << E->getSourceRange()))
John Wiegley01296292011-04-08 18:41:53 +0000574 return ExprError();
Rafael Espindola70e040d2010-03-02 21:28:26 +0000575
Douglas Gregore8154332010-04-15 18:05:39 +0000576 if (RequireNonAbstractType(ThrowLoc, E->getType(),
577 PDiag(diag::err_throw_abstract_type)
578 << E->getSourceRange()))
John Wiegley01296292011-04-08 18:41:53 +0000579 return ExprError();
Sebastian Redl4de47b42009-04-27 20:27:31 +0000580 }
581
John McCall2e6567a2010-04-22 01:10:34 +0000582 // Initialize the exception result. This implicitly weeds out
583 // abstract types or types with inaccessible copy constructors.
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000584
585 // C++0x [class.copymove]p31:
586 // When certain criteria are met, an implementation is allowed to omit the
587 // copy/move construction of a class object [...]
588 //
589 // - in a throw-expression, when the operand is the name of a
590 // non-volatile automatic object (other than a function or catch-clause
591 // parameter) whose scope does not extend beyond the end of the
592 // innermost enclosing try-block (if there is one), the copy/move
593 // operation from the operand to the exception object (15.1) can be
594 // omitted by constructing the automatic object directly into the
595 // exception object
596 const VarDecl *NRVOVariable = 0;
597 if (IsThrownVarInScope)
598 NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
599
John McCall2e6567a2010-04-22 01:10:34 +0000600 InitializedEntity Entity =
Douglas Gregorc74edc22011-01-21 22:46:35 +0000601 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000602 /*NRVO=*/NRVOVariable != 0);
John Wiegley01296292011-04-08 18:41:53 +0000603 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000604 QualType(), E,
605 IsThrownVarInScope);
John McCall2e6567a2010-04-22 01:10:34 +0000606 if (Res.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000607 return ExprError();
608 E = Res.take();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000609
Eli Friedman91a3d272010-06-03 20:39:03 +0000610 // If the exception has class type, we need additional handling.
611 const RecordType *RecordTy = Ty->getAs<RecordType>();
612 if (!RecordTy)
John Wiegley01296292011-04-08 18:41:53 +0000613 return Owned(E);
Eli Friedman91a3d272010-06-03 20:39:03 +0000614 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
615
Douglas Gregor88d292c2010-05-13 16:44:06 +0000616 // If we are throwing a polymorphic class type or pointer thereof,
617 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000618 MarkVTableUsed(ThrowLoc, RD);
619
Eli Friedman36ebbec2010-10-12 20:32:36 +0000620 // If a pointer is thrown, the referenced object will not be destroyed.
621 if (isPointer)
John Wiegley01296292011-04-08 18:41:53 +0000622 return Owned(E);
Eli Friedman36ebbec2010-10-12 20:32:36 +0000623
Eli Friedman91a3d272010-06-03 20:39:03 +0000624 // If the class has a non-trivial destructor, we must be able to call it.
625 if (RD->hasTrivialDestructor())
John Wiegley01296292011-04-08 18:41:53 +0000626 return Owned(E);
Eli Friedman91a3d272010-06-03 20:39:03 +0000627
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000628 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +0000629 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman91a3d272010-06-03 20:39:03 +0000630 if (!Destructor)
John Wiegley01296292011-04-08 18:41:53 +0000631 return Owned(E);
Eli Friedman91a3d272010-06-03 20:39:03 +0000632
633 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
634 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregor747eb782010-07-08 06:14:04 +0000635 PDiag(diag::err_access_dtor_exception) << Ty);
John Wiegley01296292011-04-08 18:41:53 +0000636 return Owned(E);
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000637}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000638
Douglas Gregor09deffa2011-10-18 16:47:30 +0000639QualType Sema::getCurrentThisType(bool Capture) {
John McCallf3a88602011-02-03 08:15:49 +0000640 // Ignore block scopes: we can capture through them.
641 // Ignore nested enum scopes: we'll diagnose non-constant expressions
642 // where they're invalid, and other uses are legitimate.
643 // Don't ignore nested class scopes: you can't use 'this' in a local class.
John McCallc63de662011-02-02 13:00:07 +0000644 DeclContext *DC = CurContext;
Richard Smith938f40b2011-06-11 17:19:42 +0000645 unsigned NumBlocks = 0;
John McCallf3a88602011-02-03 08:15:49 +0000646 while (true) {
Richard Smith938f40b2011-06-11 17:19:42 +0000647 if (isa<BlockDecl>(DC)) {
648 DC = cast<BlockDecl>(DC)->getDeclContext();
649 ++NumBlocks;
650 } else if (isa<EnumDecl>(DC))
651 DC = cast<EnumDecl>(DC)->getDeclContext();
John McCallf3a88602011-02-03 08:15:49 +0000652 else break;
653 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000654
Richard Smith938f40b2011-06-11 17:19:42 +0000655 QualType ThisTy;
656 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
657 if (method && method->isInstance())
658 ThisTy = method->getThisType(Context);
659 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
660 // C++0x [expr.prim]p4:
661 // Otherwise, if a member-declarator declares a non-static data member
662 // of a class X, the expression this is a prvalue of type "pointer to X"
663 // within the optional brace-or-equal-initializer.
664 Scope *S = getScopeForContext(DC);
665 if (!S || S->getFlags() & Scope::ThisScope)
666 ThisTy = Context.getPointerType(Context.getRecordType(RD));
667 }
John McCallc63de662011-02-02 13:00:07 +0000668
Douglas Gregor09deffa2011-10-18 16:47:30 +0000669 if (!Capture || ThisTy.isNull())
670 return ThisTy;
671
Richard Smith938f40b2011-06-11 17:19:42 +0000672 // Mark that we're closing on 'this' in all the block scopes we ignored.
Douglas Gregor09deffa2011-10-18 16:47:30 +0000673 for (unsigned idx = FunctionScopes.size() - 1;
674 NumBlocks; --idx, --NumBlocks)
675 cast<BlockScopeInfo>(FunctionScopes[idx])->CapturesCXXThis = true;
John McCallc63de662011-02-02 13:00:07 +0000676
Richard Smith938f40b2011-06-11 17:19:42 +0000677 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +0000678}
679
Richard Smith938f40b2011-06-11 17:19:42 +0000680ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +0000681 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
682 /// is a non-lvalue expression whose value is the address of the object for
683 /// which the function is called.
684
Douglas Gregor09deffa2011-10-18 16:47:30 +0000685 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +0000686 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +0000687
Richard Smith938f40b2011-06-11 17:19:42 +0000688 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000689}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000690
John McCalldadc5752010-08-24 06:29:42 +0000691ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +0000692Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000693 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000694 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000695 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +0000696 if (!TypeRep)
697 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000698
John McCall97513962010-01-15 18:39:57 +0000699 TypeSourceInfo *TInfo;
700 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
701 if (!TInfo)
702 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +0000703
704 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
705}
706
707/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
708/// Can be interpreted either as function-style casting ("int(x)")
709/// or class type construction ("ClassType(x,y,z)")
710/// or creation of a value-initialized type ("int()").
711ExprResult
712Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
713 SourceLocation LParenLoc,
714 MultiExprArg exprs,
715 SourceLocation RParenLoc) {
716 QualType Ty = TInfo->getType();
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000717 unsigned NumExprs = exprs.size();
718 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregor2b88c112010-09-08 00:15:04 +0000719 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000720 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
721
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000722 if (Ty->isDependentType() ||
Douglas Gregor0950e412009-03-13 21:01:28 +0000723 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000724 exprs.release();
Mike Stump11289f42009-09-09 15:08:12 +0000725
Douglas Gregor2b88c112010-09-08 00:15:04 +0000726 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregorce934142009-05-20 18:46:25 +0000727 LParenLoc,
728 Exprs, NumExprs,
729 RParenLoc));
Douglas Gregor0950e412009-03-13 21:01:28 +0000730 }
731
Anders Carlsson55243162009-08-27 03:53:50 +0000732 if (Ty->isArrayType())
733 return ExprError(Diag(TyBeginLoc,
734 diag::err_value_init_for_array_type) << FullRange);
735 if (!Ty->isVoidType() &&
736 RequireCompleteType(TyBeginLoc, Ty,
737 PDiag(diag::err_invalid_incomplete_type_use)
738 << FullRange))
739 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000740
Anders Carlsson55243162009-08-27 03:53:50 +0000741 if (RequireNonAbstractType(TyBeginLoc, Ty,
742 diag::err_allocation_of_abstract_type))
743 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000744
745
Douglas Gregordd04d332009-01-16 18:33:17 +0000746 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000747 // If the expression list is a single expression, the type conversion
748 // expression is equivalent (in definedness, and if defined in meaning) to the
749 // corresponding cast expression.
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000750 if (NumExprs == 1) {
John McCallb50451a2011-10-05 07:41:44 +0000751 Expr *Arg = Exprs[0];
Anders Carlssone9766d52009-09-09 21:33:21 +0000752 exprs.release();
John McCallb50451a2011-10-05 07:41:44 +0000753 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000754 }
755
Douglas Gregor8ec51732010-09-08 21:40:08 +0000756 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
757 InitializationKind Kind
758 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
759 LParenLoc, RParenLoc)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000760 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor8ec51732010-09-08 21:40:08 +0000761 LParenLoc, RParenLoc);
762 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
763 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000764
Douglas Gregor8ec51732010-09-08 21:40:08 +0000765 // FIXME: Improve AST representation?
766 return move(Result);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000767}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000768
John McCall284c48f2011-01-27 09:37:56 +0000769/// doesUsualArrayDeleteWantSize - Answers whether the usual
770/// operator delete[] for the given type has a size_t parameter.
771static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
772 QualType allocType) {
773 const RecordType *record =
774 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
775 if (!record) return false;
776
777 // Try to find an operator delete[] in class scope.
778
779 DeclarationName deleteName =
780 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
781 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
782 S.LookupQualifiedName(ops, record->getDecl());
783
784 // We're just doing this for information.
785 ops.suppressDiagnostics();
786
787 // Very likely: there's no operator delete[].
788 if (ops.empty()) return false;
789
790 // If it's ambiguous, it should be illegal to call operator delete[]
791 // on this thing, so it doesn't matter if we allocate extra space or not.
792 if (ops.isAmbiguous()) return false;
793
794 LookupResult::Filter filter = ops.makeFilter();
795 while (filter.hasNext()) {
796 NamedDecl *del = filter.next()->getUnderlyingDecl();
797
798 // C++0x [basic.stc.dynamic.deallocation]p2:
799 // A template instance is never a usual deallocation function,
800 // regardless of its signature.
801 if (isa<FunctionTemplateDecl>(del)) {
802 filter.erase();
803 continue;
804 }
805
806 // C++0x [basic.stc.dynamic.deallocation]p2:
807 // If class T does not declare [an operator delete[] with one
808 // parameter] but does declare a member deallocation function
809 // named operator delete[] with exactly two parameters, the
810 // second of which has type std::size_t, then this function
811 // is a usual deallocation function.
812 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
813 filter.erase();
814 continue;
815 }
816 }
817 filter.done();
818
819 if (!ops.isSingleResult()) return false;
820
821 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
822 return (del->getNumParams() == 2);
823}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000824
Sebastian Redlbd150f42008-11-21 19:14:01 +0000825/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
826/// @code new (memory) int[size][4] @endcode
827/// or
828/// @code ::new Foo(23, "hello") @endcode
829/// For the interpretation of this heap of arguments, consult the base version.
John McCalldadc5752010-08-24 06:29:42 +0000830ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000831Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000832 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000833 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl351bb782008-12-02 14:43:59 +0000834 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000835 MultiExprArg ConstructorArgs,
Mike Stump11289f42009-09-09 15:08:12 +0000836 SourceLocation ConstructorRParen) {
Richard Smith30482bc2011-02-20 03:19:35 +0000837 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
838
Sebastian Redl351bb782008-12-02 14:43:59 +0000839 Expr *ArraySize = 0;
Sebastian Redl351bb782008-12-02 14:43:59 +0000840 // If the specified type is an array, unwrap it and save the expression.
841 if (D.getNumTypeObjects() > 0 &&
842 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
843 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith30482bc2011-02-20 03:19:35 +0000844 if (TypeContainsAuto)
845 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
846 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000847 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000848 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
849 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000850 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000851 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
852 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000853
Sebastian Redl351bb782008-12-02 14:43:59 +0000854 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000855 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +0000856 }
857
Douglas Gregor73341c42009-09-11 00:18:58 +0000858 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000859 if (ArraySize) {
860 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +0000861 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
862 break;
863
864 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
865 if (Expr *NumElts = (Expr *)Array.NumElts) {
866 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
867 !NumElts->isIntegerConstantExpr(Context)) {
868 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
869 << NumElts->getSourceRange();
870 return ExprError();
871 }
872 }
873 }
874 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000875
Argyrios Kyrtzidis3ff13572011-06-28 03:01:23 +0000876 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
John McCall8cb7bdf2010-06-04 23:28:52 +0000877 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000878 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000879 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000880
Mike Stump11289f42009-09-09 15:08:12 +0000881 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000882 PlacementLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000883 move(PlacementArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +0000884 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000885 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +0000886 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +0000887 TInfo,
John McCallb268a282010-08-23 23:25:46 +0000888 ArraySize,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000889 ConstructorLParen,
890 move(ConstructorArgs),
Richard Smith30482bc2011-02-20 03:19:35 +0000891 ConstructorRParen,
892 TypeContainsAuto);
Douglas Gregord0fefba2009-05-21 00:00:09 +0000893}
894
John McCalldadc5752010-08-24 06:29:42 +0000895ExprResult
Douglas Gregord0fefba2009-05-21 00:00:09 +0000896Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
897 SourceLocation PlacementLParen,
898 MultiExprArg PlacementArgs,
899 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000900 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000901 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +0000902 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +0000903 Expr *ArraySize,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000904 SourceLocation ConstructorLParen,
905 MultiExprArg ConstructorArgs,
Richard Smith30482bc2011-02-20 03:19:35 +0000906 SourceLocation ConstructorRParen,
907 bool TypeMayContainAuto) {
Douglas Gregor0744ef62010-09-07 21:49:58 +0000908 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redl351bb782008-12-02 14:43:59 +0000909
Richard Smith30482bc2011-02-20 03:19:35 +0000910 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
911 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
912 if (ConstructorArgs.size() == 0)
913 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
914 << AllocType << TypeRange);
915 if (ConstructorArgs.size() != 1) {
916 Expr *FirstBad = ConstructorArgs.get()[1];
917 return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
918 diag::err_auto_new_ctor_multiple_expressions)
919 << AllocType << TypeRange);
920 }
Richard Smith9647d3c2011-03-17 16:11:59 +0000921 TypeSourceInfo *DeducedType = 0;
922 if (!DeduceAutoType(AllocTypeInfo, ConstructorArgs.get()[0], DeducedType))
Richard Smith30482bc2011-02-20 03:19:35 +0000923 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
924 << AllocType
925 << ConstructorArgs.get()[0]->getType()
926 << TypeRange
927 << ConstructorArgs.get()[0]->getSourceRange());
Richard Smith9647d3c2011-03-17 16:11:59 +0000928 if (!DeducedType)
929 return ExprError();
Richard Smith30482bc2011-02-20 03:19:35 +0000930
Richard Smith9647d3c2011-03-17 16:11:59 +0000931 AllocTypeInfo = DeducedType;
932 AllocType = AllocTypeInfo->getType();
Richard Smith30482bc2011-02-20 03:19:35 +0000933 }
934
Douglas Gregorcda95f42010-05-16 16:01:03 +0000935 // Per C++0x [expr.new]p5, the type being constructed may be a
936 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +0000937 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +0000938 if (const ConstantArrayType *Array
939 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000940 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
941 Context.getSizeType(),
942 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +0000943 AllocType = Array->getElementType();
944 }
945 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000946
Douglas Gregor3999e152010-10-06 16:00:31 +0000947 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
948 return ExprError();
949
John McCall31168b02011-06-15 23:02:42 +0000950 // In ARC, infer 'retaining' for the allocated
951 if (getLangOptions().ObjCAutoRefCount &&
952 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
953 AllocType->isObjCLifetimeType()) {
954 AllocType = Context.getLifetimeQualifiedType(AllocType,
955 AllocType->getObjCARCImplicitLifetime());
956 }
Sebastian Redl351bb782008-12-02 14:43:59 +0000957
John McCall31168b02011-06-15 23:02:42 +0000958 QualType ResultType = Context.getPointerType(AllocType);
959
Sebastian Redlbd150f42008-11-21 19:14:01 +0000960 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
961 // or enumeration type with a non-negative value."
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000962 if (ArraySize && !ArraySize->isTypeDependent()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000963
Sebastian Redl351bb782008-12-02 14:43:59 +0000964 QualType SizeType = ArraySize->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000965
Richard Smith0bf8a4922011-10-18 20:49:44 +0000966 ExprResult ConvertedSize = ConvertToIntegralOrEnumerationType(
967 StartLoc, ArraySize,
968 PDiag(diag::err_array_size_not_integral),
969 PDiag(diag::err_array_size_incomplete_type)
970 << ArraySize->getSourceRange(),
971 PDiag(diag::err_array_size_explicit_conversion),
972 PDiag(diag::note_array_size_conversion),
973 PDiag(diag::err_array_size_ambiguous_conversion),
974 PDiag(diag::note_array_size_conversion),
975 PDiag(getLangOptions().CPlusPlus0x ?
976 diag::warn_cxx98_compat_array_size_conversion :
977 diag::ext_array_size_conversion));
Douglas Gregor4799d032010-06-30 00:20:43 +0000978 if (ConvertedSize.isInvalid())
979 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000980
John McCallb268a282010-08-23 23:25:46 +0000981 ArraySize = ConvertedSize.take();
Douglas Gregor4799d032010-06-30 00:20:43 +0000982 SizeType = ArraySize->getType();
Douglas Gregor0bf31402010-10-08 23:50:27 +0000983 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +0000984 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000985
Sebastian Redl351bb782008-12-02 14:43:59 +0000986 // Let's see if this is a constant < 0. If so, we reject it out of hand.
987 // We don't care about special rules, so we tell the machinery it's not
988 // evaluated - it gives us a result in more cases.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000989 if (!ArraySize->isValueDependent()) {
990 llvm::APSInt Value;
991 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
992 if (Value < llvm::APSInt(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000993 llvm::APInt::getNullValue(Value.getBitWidth()),
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000994 Value.isUnsigned()))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000995 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregorcaa1bf42010-08-18 00:39:00 +0000996 diag::err_typecheck_negative_array_size)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000997 << ArraySize->getSourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000998
Douglas Gregorcaa1bf42010-08-18 00:39:00 +0000999 if (!AllocType->isDependentType()) {
1000 unsigned ActiveSizeBits
1001 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1002 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001003 Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001004 diag::err_array_too_large)
1005 << Value.toString(10)
1006 << ArraySize->getSourceRange();
1007 return ExprError();
1008 }
1009 }
Douglas Gregorf2753b32010-07-13 15:54:32 +00001010 } else if (TypeIdParens.isValid()) {
1011 // Can't have dynamic array size when the type-id is in parentheses.
1012 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1013 << ArraySize->getSourceRange()
1014 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1015 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001016
Douglas Gregorf2753b32010-07-13 15:54:32 +00001017 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001018 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001019 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001020
John McCall31168b02011-06-15 23:02:42 +00001021 // ARC: warn about ABI issues.
1022 if (getLangOptions().ObjCAutoRefCount) {
1023 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1024 if (BaseAllocType.hasStrongOrWeakObjCLifetime())
1025 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1026 << 0 << BaseAllocType;
1027 }
1028
John McCall036f2f62011-05-15 07:14:44 +00001029 // Note that we do *not* convert the argument in any way. It can
1030 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00001031 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001032
Sebastian Redlbd150f42008-11-21 19:14:01 +00001033 FunctionDecl *OperatorNew = 0;
1034 FunctionDecl *OperatorDelete = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001035 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
1036 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001037
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001038 if (!AllocType->isDependentType() &&
1039 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
1040 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001041 SourceRange(PlacementLParen, PlacementRParen),
1042 UseGlobal, AllocType, ArraySize, PlaceArgs,
1043 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001044 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00001045
1046 // If this is an array allocation, compute whether the usual array
1047 // deallocation function for the type has a size_t parameter.
1048 bool UsualArrayDeleteWantsSize = false;
1049 if (ArraySize && !AllocType->isDependentType())
1050 UsualArrayDeleteWantsSize
1051 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1052
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001053 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001054 if (OperatorNew) {
1055 // Add default arguments, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001056 const FunctionProtoType *Proto =
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001057 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001058 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00001059 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001060
Anders Carlssonc144bc22010-05-03 02:07:56 +00001061 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001062 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlssonc144bc22010-05-03 02:07:56 +00001063 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001064 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001065
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001066 NumPlaceArgs = AllPlaceArgs.size();
1067 if (NumPlaceArgs > 0)
1068 PlaceArgs = &AllPlaceArgs[0];
1069 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001070
Sebastian Redlbd150f42008-11-21 19:14:01 +00001071 bool Init = ConstructorLParen.isValid();
1072 // --- Choosing a constructor ---
Sebastian Redlbd150f42008-11-21 19:14:01 +00001073 CXXConstructorDecl *Constructor = 0;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00001074 bool HadMultipleCandidates = false;
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001075 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
1076 unsigned NumConsArgs = ConstructorArgs.size();
John McCall37ad5512010-08-23 06:44:23 +00001077 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmanfd8d4e12009-11-08 22:15:39 +00001078
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001079 // Array 'new' can't have any initializers.
Anders Carlssone6ae81b2010-05-16 16:24:20 +00001080 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001081 SourceRange InitRange(ConsArgs[0]->getLocStart(),
1082 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001083
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001084 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1085 return ExprError();
1086 }
1087
Douglas Gregor85dabae2009-12-16 01:38:02 +00001088 if (!AllocType->isDependentType() &&
1089 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
1090 // C++0x [expr.new]p15:
1091 // A new-expression that creates an object of type T initializes that
1092 // object as follows:
1093 InitializationKind Kind
1094 // - If the new-initializer is omitted, the object is default-
1095 // initialized (8.5); if no initialization is performed,
1096 // the object has indeterminate value
Douglas Gregor0744ef62010-09-07 21:49:58 +00001097 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001098 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor85dabae2009-12-16 01:38:02 +00001099 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor0744ef62010-09-07 21:49:58 +00001100 : InitializationKind::CreateDirect(TypeRange.getBegin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001101 ConstructorLParen,
Douglas Gregor85dabae2009-12-16 01:38:02 +00001102 ConstructorRParen);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001103
Douglas Gregor85dabae2009-12-16 01:38:02 +00001104 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00001105 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00001106 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001107 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor85dabae2009-12-16 01:38:02 +00001108 move(ConstructorArgs));
1109 if (FullInit.isInvalid())
1110 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001111
1112 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor85dabae2009-12-16 01:38:02 +00001113 // constructor call, which CXXNewExpr handles directly.
1114 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1115 if (CXXBindTemporaryExpr *Binder
1116 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1117 FullInitExpr = Binder->getSubExpr();
1118 if (CXXConstructExpr *Construct
1119 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1120 Constructor = Construct->getConstructor();
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00001121 HadMultipleCandidates = Construct->hadMultipleCandidates();
Douglas Gregor85dabae2009-12-16 01:38:02 +00001122 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1123 AEnd = Construct->arg_end();
1124 A != AEnd; ++A)
John McCallc3007a22010-10-26 07:05:15 +00001125 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor85dabae2009-12-16 01:38:02 +00001126 } else {
1127 // Take the converted initializer.
1128 ConvertedConstructorArgs.push_back(FullInit.release());
1129 }
1130 } else {
1131 // No initialization required.
1132 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001133
Douglas Gregor85dabae2009-12-16 01:38:02 +00001134 // Take the converted arguments and use them for the new expression.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001135 NumConsArgs = ConvertedConstructorArgs.size();
1136 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001137 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001138
Douglas Gregor6642ca22010-02-26 05:06:18 +00001139 // Mark the new and delete operators as referenced.
1140 if (OperatorNew)
1141 MarkDeclarationReferenced(StartLoc, OperatorNew);
1142 if (OperatorDelete)
1143 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1144
John McCall928a2572011-07-13 20:12:57 +00001145 // C++0x [expr.new]p17:
1146 // If the new expression creates an array of objects of class type,
1147 // access and ambiguity control are done for the destructor.
1148 if (ArraySize && Constructor) {
1149 if (CXXDestructorDecl *dtor = LookupDestructor(Constructor->getParent())) {
1150 MarkDeclarationReferenced(StartLoc, dtor);
1151 CheckDestructorAccess(StartLoc, dtor,
1152 PDiag(diag::err_access_dtor)
1153 << Context.getBaseElementType(AllocType));
1154 }
1155 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001156
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001157 PlacementArgs.release();
1158 ConstructorArgs.release();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001159
Ted Kremenek9d6eb402010-02-11 22:51:03 +00001160 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001161 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenek9d6eb402010-02-11 22:51:03 +00001162 ArraySize, Constructor, Init,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00001163 ConsArgs, NumConsArgs,
1164 HadMultipleCandidates,
1165 OperatorDelete,
John McCall284c48f2011-01-27 09:37:56 +00001166 UsualArrayDeleteWantsSize,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001167 ResultType, AllocTypeInfo,
1168 StartLoc,
Ted Kremenek9d6eb402010-02-11 22:51:03 +00001169 Init ? ConstructorRParen :
Chandler Carruth01718152010-10-25 08:47:36 +00001170 TypeRange.getEnd(),
1171 ConstructorLParen, ConstructorRParen));
Sebastian Redlbd150f42008-11-21 19:14:01 +00001172}
1173
1174/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1175/// in a new-expression.
1176/// dimension off and stores the size expression in ArraySize.
Douglas Gregord0fefba2009-05-21 00:00:09 +00001177bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00001178 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00001179 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1180 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00001181 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00001182 return Diag(Loc, diag::err_bad_new_type)
1183 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00001184 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00001185 return Diag(Loc, diag::err_bad_new_type)
1186 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00001187 else if (!AllocType->isDependentType() &&
Douglas Gregord0fefba2009-05-21 00:00:09 +00001188 RequireCompleteType(Loc, AllocType,
Anders Carlssond624e162009-08-26 23:45:07 +00001189 PDiag(diag::err_new_incomplete_type)
1190 << R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00001191 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00001192 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00001193 diag::err_allocation_of_abstract_type))
1194 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00001195 else if (AllocType->isVariablyModifiedType())
1196 return Diag(Loc, diag::err_variably_modified_new_type)
1197 << AllocType;
Douglas Gregor39d1a092011-04-15 19:46:20 +00001198 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1199 return Diag(Loc, diag::err_address_space_qualified_new)
1200 << AllocType.getUnqualifiedType() << AddressSpace;
John McCall31168b02011-06-15 23:02:42 +00001201 else if (getLangOptions().ObjCAutoRefCount) {
1202 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1203 QualType BaseAllocType = Context.getBaseElementType(AT);
1204 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1205 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001206 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00001207 << BaseAllocType;
1208 }
1209 }
Douglas Gregor39d1a092011-04-15 19:46:20 +00001210
Sebastian Redlbd150f42008-11-21 19:14:01 +00001211 return false;
1212}
1213
Douglas Gregor6642ca22010-02-26 05:06:18 +00001214/// \brief Determine whether the given function is a non-placement
1215/// deallocation function.
1216static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1217 if (FD->isInvalidDecl())
1218 return false;
1219
1220 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1221 return Method->isUsualDeallocationFunction();
1222
1223 return ((FD->getOverloadedOperator() == OO_Delete ||
1224 FD->getOverloadedOperator() == OO_Array_Delete) &&
1225 FD->getNumParams() == 1);
1226}
1227
Sebastian Redlfaf68082008-12-03 20:26:15 +00001228/// FindAllocationFunctions - Finds the overloads of operator new and delete
1229/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001230bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1231 bool UseGlobal, QualType AllocType,
1232 bool IsArray, Expr **PlaceArgs,
1233 unsigned NumPlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00001234 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +00001235 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001236 // --- Choosing an allocation function ---
1237 // C++ 5.3.4p8 - 14 & 18
1238 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1239 // in the scope of the allocated class.
1240 // 2) If an array size is given, look for operator new[], else look for
1241 // operator new.
1242 // 3) The first argument is always size_t. Append the arguments from the
1243 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00001244
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001245 SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001246 // We don't care about the actual value of this argument.
1247 // FIXME: Should the Sema create the expression and embed it in the syntax
1248 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001249 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00001250 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00001251 Context.getSizeType(),
1252 SourceLocation());
1253 AllocArgs[0] = &Size;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001254 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1255
Douglas Gregor6642ca22010-02-26 05:06:18 +00001256 // C++ [expr.new]p8:
1257 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001258 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00001259 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001260 // type, the allocation function's name is operator new[] and the
1261 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00001262 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1263 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001264 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1265 IsArray ? OO_Array_Delete : OO_Delete);
1266
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001267 QualType AllocElemType = Context.getBaseElementType(AllocType);
1268
1269 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +00001270 CXXRecordDecl *Record
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001271 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001272 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +00001273 AllocArgs.size(), Record, /*AllowMissing=*/true,
1274 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00001275 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001276 }
1277 if (!OperatorNew) {
1278 // Didn't find a member overload. Look for a global one.
1279 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +00001280 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001281 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +00001282 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1283 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00001284 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001285 }
1286
John McCall0f55a032010-04-20 02:18:25 +00001287 // We don't need an operator delete if we're running under
1288 // -fno-exceptions.
1289 if (!getLangOptions().Exceptions) {
1290 OperatorDelete = 0;
1291 return false;
1292 }
1293
Anders Carlsson6f9dabf2009-05-31 20:26:12 +00001294 // FindAllocationOverload can change the passed in arguments, so we need to
1295 // copy them back.
1296 if (NumPlaceArgs > 0)
1297 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001298
Douglas Gregor6642ca22010-02-26 05:06:18 +00001299 // C++ [expr.new]p19:
1300 //
1301 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001302 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00001303 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001304 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00001305 // the scope of T. If this lookup fails to find the name, or if
1306 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001307 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00001308 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001309 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001310 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001311 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00001312 LookupQualifiedName(FoundDelete, RD);
1313 }
John McCallfb6f5262010-03-18 08:19:33 +00001314 if (FoundDelete.isAmbiguous())
1315 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00001316
1317 if (FoundDelete.empty()) {
1318 DeclareGlobalNewDelete();
1319 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1320 }
1321
1322 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00001323
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001324 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00001325
John McCalld3be2c82010-09-14 21:34:24 +00001326 // Whether we're looking for a placement operator delete is dictated
1327 // by whether we selected a placement operator new, not by whether
1328 // we had explicit placement arguments. This matters for things like
1329 // struct A { void *operator new(size_t, int = 0); ... };
1330 // A *a = new A()
1331 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1332
1333 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001334 // C++ [expr.new]p20:
1335 // A declaration of a placement deallocation function matches the
1336 // declaration of a placement allocation function if it has the
1337 // same number of parameters and, after parameter transformations
1338 // (8.3.5), all parameter types except the first are
1339 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001340 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00001341 // To perform this comparison, we compute the function type that
1342 // the deallocation function should have, and use that type both
1343 // for template argument deduction and for comparison purposes.
John McCalldb40c7f2010-12-14 08:05:40 +00001344 //
1345 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6642ca22010-02-26 05:06:18 +00001346 QualType ExpectedFunctionType;
1347 {
1348 const FunctionProtoType *Proto
1349 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00001350
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001351 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001352 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001353 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1354 ArgTypes.push_back(Proto->getArgType(I));
1355
John McCalldb40c7f2010-12-14 08:05:40 +00001356 FunctionProtoType::ExtProtoInfo EPI;
1357 EPI.Variadic = Proto->isVariadic();
1358
Douglas Gregor6642ca22010-02-26 05:06:18 +00001359 ExpectedFunctionType
1360 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalldb40c7f2010-12-14 08:05:40 +00001361 ArgTypes.size(), EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001362 }
1363
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001364 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001365 DEnd = FoundDelete.end();
1366 D != DEnd; ++D) {
1367 FunctionDecl *Fn = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001368 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6642ca22010-02-26 05:06:18 +00001369 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1370 // Perform template argument deduction to try to match the
1371 // expected function type.
1372 TemplateDeductionInfo Info(Context, StartLoc);
1373 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1374 continue;
1375 } else
1376 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1377
1378 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00001379 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001380 }
1381 } else {
1382 // C++ [expr.new]p20:
1383 // [...] Any non-placement deallocation function matches a
1384 // non-placement allocation function. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001385 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001386 DEnd = FoundDelete.end();
1387 D != DEnd; ++D) {
1388 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1389 if (isNonPlacementDeallocationFunction(Fn))
John McCalla0296f72010-03-19 07:35:19 +00001390 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001391 }
1392 }
1393
1394 // C++ [expr.new]p20:
1395 // [...] If the lookup finds a single matching deallocation
1396 // function, that function will be called; otherwise, no
1397 // deallocation function will be called.
1398 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00001399 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00001400
1401 // C++0x [expr.new]p20:
1402 // If the lookup finds the two-parameter form of a usual
1403 // deallocation function (3.7.4.2) and that function, considered
1404 // as a placement deallocation function, would have been
1405 // selected as a match for the allocation function, the program
1406 // is ill-formed.
1407 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1408 isNonPlacementDeallocationFunction(OperatorDelete)) {
1409 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001410 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001411 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1412 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1413 << DeleteName;
John McCallfb6f5262010-03-18 08:19:33 +00001414 } else {
1415 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCalla0296f72010-03-19 07:35:19 +00001416 Matches[0].first);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001417 }
1418 }
1419
Sebastian Redlfaf68082008-12-03 20:26:15 +00001420 return false;
1421}
1422
Sebastian Redl33a31012008-12-04 22:20:51 +00001423/// FindAllocationOverload - Find an fitting overload for the allocation
1424/// function in the specified scope.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001425bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1426 DeclarationName Name, Expr** Args,
1427 unsigned NumArgs, DeclContext *Ctx,
Alexis Hunt1f69a022011-05-12 22:46:29 +00001428 bool AllowMissing, FunctionDecl *&Operator,
1429 bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00001430 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1431 LookupQualifiedName(R, Ctx);
John McCall9f3059a2009-10-09 21:13:30 +00001432 if (R.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001433 if (AllowMissing || !Diagnose)
Sebastian Redl33a31012008-12-04 22:20:51 +00001434 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +00001435 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001436 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +00001437 }
1438
John McCallfb6f5262010-03-18 08:19:33 +00001439 if (R.isAmbiguous())
1440 return true;
1441
1442 R.suppressDiagnostics();
John McCall9f3059a2009-10-09 21:13:30 +00001443
John McCallbc077cf2010-02-08 23:07:23 +00001444 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001445 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor80a6cc52009-09-30 00:03:47 +00001446 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor55297ac2008-12-23 00:26:44 +00001447 // Even member operator new/delete are implicitly treated as
1448 // static, so don't use AddMemberCandidate.
John McCalla0296f72010-03-19 07:35:19 +00001449 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth93538422010-02-03 11:02:14 +00001450
John McCalla0296f72010-03-19 07:35:19 +00001451 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1452 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth93538422010-02-03 11:02:14 +00001453 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1454 Candidates,
1455 /*SuppressUserConversions=*/false);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001456 continue;
Chandler Carruth93538422010-02-03 11:02:14 +00001457 }
1458
John McCalla0296f72010-03-19 07:35:19 +00001459 FunctionDecl *Fn = cast<FunctionDecl>(D);
1460 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth93538422010-02-03 11:02:14 +00001461 /*SuppressUserConversions=*/false);
Sebastian Redl33a31012008-12-04 22:20:51 +00001462 }
1463
1464 // Do the resolution.
1465 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00001466 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001467 case OR_Success: {
1468 // Got one!
1469 FunctionDecl *FnDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00001470 MarkDeclarationReferenced(StartLoc, FnDecl);
Sebastian Redl33a31012008-12-04 22:20:51 +00001471 // The first argument is size_t, and the first parameter must be size_t,
1472 // too. This is checked on declaration and can be assumed. (It can't be
1473 // asserted on, though, since invalid decls are left in there.)
John McCallfb6f5262010-03-18 08:19:33 +00001474 // Watch out for variadic allocator function.
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001475 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1476 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001477 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1478 FnDecl->getParamDecl(i));
1479
1480 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1481 return true;
1482
John McCalldadc5752010-08-24 06:29:42 +00001483 ExprResult Result
Alexis Hunt1f69a022011-05-12 22:46:29 +00001484 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
Douglas Gregor34147272010-03-26 20:35:59 +00001485 if (Result.isInvalid())
Sebastian Redl33a31012008-12-04 22:20:51 +00001486 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001487
Douglas Gregor34147272010-03-26 20:35:59 +00001488 Args[i] = Result.takeAs<Expr>();
Sebastian Redl33a31012008-12-04 22:20:51 +00001489 }
1490 Operator = FnDecl;
Alexis Hunt1f69a022011-05-12 22:46:29 +00001491 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl,
1492 Diagnose);
Sebastian Redl33a31012008-12-04 22:20:51 +00001493 return false;
1494 }
1495
1496 case OR_No_Viable_Function:
Chandler Carruthe6c88182011-06-08 10:26:03 +00001497 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001498 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1499 << Name << Range;
Chandler Carruthe6c88182011-06-08 10:26:03 +00001500 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1501 }
Sebastian Redl33a31012008-12-04 22:20:51 +00001502 return true;
1503
1504 case OR_Ambiguous:
Chandler Carruthe6c88182011-06-08 10:26:03 +00001505 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001506 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1507 << Name << Range;
Chandler Carruthe6c88182011-06-08 10:26:03 +00001508 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
1509 }
Sebastian Redl33a31012008-12-04 22:20:51 +00001510 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001511
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001512 case OR_Deleted: {
Chandler Carruthe6c88182011-06-08 10:26:03 +00001513 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001514 Diag(StartLoc, diag::err_ovl_deleted_call)
1515 << Best->Function->isDeleted()
1516 << Name
1517 << getDeletedOrUnavailableSuffix(Best->Function)
1518 << Range;
Chandler Carruthe6c88182011-06-08 10:26:03 +00001519 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1520 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00001521 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +00001522 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001523 }
David Blaikie83d382b2011-09-23 05:06:16 +00001524 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Sebastian Redl33a31012008-12-04 22:20:51 +00001525}
1526
1527
Sebastian Redlfaf68082008-12-03 20:26:15 +00001528/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1529/// delete. These are:
1530/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00001531/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00001532/// void* operator new(std::size_t) throw(std::bad_alloc);
1533/// void* operator new[](std::size_t) throw(std::bad_alloc);
1534/// void operator delete(void *) throw();
1535/// void operator delete[](void *) throw();
Sebastian Redl37588092011-03-14 18:08:30 +00001536/// // C++0x:
1537/// void* operator new(std::size_t);
1538/// void* operator new[](std::size_t);
1539/// void operator delete(void *);
1540/// void operator delete[](void *);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001541/// @endcode
Sebastian Redl37588092011-03-14 18:08:30 +00001542/// C++0x operator delete is implicitly noexcept.
Sebastian Redlfaf68082008-12-03 20:26:15 +00001543/// Note that the placement and nothrow forms of new are *not* implicitly
1544/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00001545void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001546 if (GlobalNewDeleteDeclared)
1547 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001548
Douglas Gregor87f54062009-09-15 22:30:29 +00001549 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001550 // [...] The following allocation and deallocation functions (18.4) are
1551 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00001552 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001553 //
Sebastian Redl37588092011-03-14 18:08:30 +00001554 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00001555 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001556 // void* operator new[](std::size_t) throw(std::bad_alloc);
1557 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00001558 // void operator delete[](void*) throw();
Sebastian Redl37588092011-03-14 18:08:30 +00001559 // C++0x:
1560 // void* operator new(std::size_t);
1561 // void* operator new[](std::size_t);
1562 // void operator delete(void*);
1563 // void operator delete[](void*);
Douglas Gregor87f54062009-09-15 22:30:29 +00001564 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001565 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00001566 // new, operator new[], operator delete, operator delete[].
1567 //
1568 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1569 // "std" or "bad_alloc" as necessary to form the exception specification.
1570 // However, we do not make these implicit declarations visible to name
1571 // lookup.
Sebastian Redl37588092011-03-14 18:08:30 +00001572 // Note that the C++0x versions of operator delete are deallocation functions,
1573 // and thus are implicitly noexcept.
1574 if (!StdBadAlloc && !getLangOptions().CPlusPlus0x) {
Douglas Gregor87f54062009-09-15 22:30:29 +00001575 // The "std::bad_alloc" class has not yet been declared, so build it
1576 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001577 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1578 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001579 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001580 &PP.getIdentifierTable().get("bad_alloc"),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001581 0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001582 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00001583 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001584
Sebastian Redlfaf68082008-12-03 20:26:15 +00001585 GlobalNewDeleteDeclared = true;
1586
1587 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1588 QualType SizeT = Context.getSizeType();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001589 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001590
Sebastian Redlfaf68082008-12-03 20:26:15 +00001591 DeclareGlobalAllocationFunction(
1592 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001593 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001594 DeclareGlobalAllocationFunction(
1595 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001596 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001597 DeclareGlobalAllocationFunction(
1598 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1599 Context.VoidTy, VoidPtr);
1600 DeclareGlobalAllocationFunction(
1601 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1602 Context.VoidTy, VoidPtr);
1603}
1604
1605/// DeclareGlobalAllocationFunction - Declares a single implicit global
1606/// allocation function if it doesn't already exist.
1607void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopes13c88c72009-12-16 16:59:22 +00001608 QualType Return, QualType Argument,
1609 bool AddMallocAttr) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001610 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1611
1612 // Check if this function is already declared.
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001613 {
Douglas Gregor17eb26b2008-12-23 22:05:29 +00001614 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001615 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001616 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth93538422010-02-03 11:02:14 +00001617 // Only look at non-template functions, as it is the predefined,
1618 // non-templated allocation function we are trying to declare here.
1619 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1620 QualType InitialParamType =
Douglas Gregor684d7bd2009-12-22 23:42:49 +00001621 Context.getCanonicalType(
Chandler Carruth93538422010-02-03 11:02:14 +00001622 Func->getParamDecl(0)->getType().getUnqualifiedType());
1623 // FIXME: Do we need to check for default arguments here?
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00001624 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1625 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001626 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth93538422010-02-03 11:02:14 +00001627 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00001628 }
Chandler Carruth93538422010-02-03 11:02:14 +00001629 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00001630 }
1631 }
1632
Douglas Gregor87f54062009-09-15 22:30:29 +00001633 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001634 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00001635 = (Name.getCXXOverloadedOperator() == OO_New ||
1636 Name.getCXXOverloadedOperator() == OO_Array_New);
Sebastian Redl37588092011-03-14 18:08:30 +00001637 if (HasBadAllocExceptionSpec && !getLangOptions().CPlusPlus0x) {
Douglas Gregor87f54062009-09-15 22:30:29 +00001638 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001639 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +00001640 }
John McCalldb40c7f2010-12-14 08:05:40 +00001641
1642 FunctionProtoType::ExtProtoInfo EPI;
John McCalldb40c7f2010-12-14 08:05:40 +00001643 if (HasBadAllocExceptionSpec) {
Sebastian Redl37588092011-03-14 18:08:30 +00001644 if (!getLangOptions().CPlusPlus0x) {
1645 EPI.ExceptionSpecType = EST_Dynamic;
1646 EPI.NumExceptions = 1;
1647 EPI.Exceptions = &BadAllocType;
1648 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001649 } else {
Sebastian Redl37588092011-03-14 18:08:30 +00001650 EPI.ExceptionSpecType = getLangOptions().CPlusPlus0x ?
1651 EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00001652 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001653
John McCalldb40c7f2010-12-14 08:05:40 +00001654 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001655 FunctionDecl *Alloc =
Abramo Bagnaradff19302011-03-08 08:55:46 +00001656 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1657 SourceLocation(), Name,
John McCall8e7d6562010-08-26 03:08:43 +00001658 FnType, /*TInfo=*/0, SC_None,
1659 SC_None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001660 Alloc->setImplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001661
Nuno Lopes13c88c72009-12-16 16:59:22 +00001662 if (AddMallocAttr)
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001663 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001664
Sebastian Redlfaf68082008-12-03 20:26:15 +00001665 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001666 SourceLocation(), 0,
1667 Argument, /*TInfo=*/0,
1668 SC_None, SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00001669 Alloc->setParams(Param);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001670
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001671 // FIXME: Also add this declaration to the IdentifierResolver, but
1672 // make sure it is at the end of the chain to coincide with the
1673 // global scope.
John McCallcc14d1f2010-08-24 08:50:51 +00001674 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001675}
1676
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001677bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1678 DeclarationName Name,
Alexis Hunt1f69a022011-05-12 22:46:29 +00001679 FunctionDecl* &Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00001680 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001681 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00001682 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001683
John McCall27b18f82009-11-17 02:14:36 +00001684 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001685 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001686
Chandler Carruthb6f99172010-06-28 00:30:51 +00001687 Found.suppressDiagnostics();
1688
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001689 SmallVector<DeclAccessPair,4> Matches;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001690 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1691 F != FEnd; ++F) {
Chandler Carruth9b418232010-08-08 07:04:00 +00001692 NamedDecl *ND = (*F)->getUnderlyingDecl();
1693
1694 // Ignore template operator delete members from the check for a usual
1695 // deallocation function.
1696 if (isa<FunctionTemplateDecl>(ND))
1697 continue;
1698
1699 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall66a87592010-08-04 00:31:26 +00001700 Matches.push_back(F.getPair());
1701 }
1702
1703 // There's exactly one suitable operator; pick it.
1704 if (Matches.size() == 1) {
1705 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
Alexis Hunt1f69a022011-05-12 22:46:29 +00001706
1707 if (Operator->isDeleted()) {
1708 if (Diagnose) {
1709 Diag(StartLoc, diag::err_deleted_function_use);
1710 Diag(Operator->getLocation(), diag::note_unavailable_here) << true;
1711 }
1712 return true;
1713 }
1714
John McCall66a87592010-08-04 00:31:26 +00001715 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Alexis Hunt1f69a022011-05-12 22:46:29 +00001716 Matches[0], Diagnose);
John McCall66a87592010-08-04 00:31:26 +00001717 return false;
1718
1719 // We found multiple suitable operators; complain about the ambiguity.
1720 } else if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001721 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00001722 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1723 << Name << RD;
John McCall66a87592010-08-04 00:31:26 +00001724
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001725 for (SmallVectorImpl<DeclAccessPair>::iterator
Alexis Huntf91729462011-05-12 22:46:25 +00001726 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1727 Diag((*F)->getUnderlyingDecl()->getLocation(),
1728 diag::note_member_declared_here) << Name;
1729 }
John McCall66a87592010-08-04 00:31:26 +00001730 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001731 }
1732
1733 // We did find operator delete/operator delete[] declarations, but
1734 // none of them were suitable.
1735 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001736 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00001737 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1738 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001739
Alexis Huntf91729462011-05-12 22:46:25 +00001740 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1741 F != FEnd; ++F)
1742 Diag((*F)->getUnderlyingDecl()->getLocation(),
1743 diag::note_member_declared_here) << Name;
1744 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001745 return true;
1746 }
1747
1748 // Look for a global declaration.
1749 DeclareGlobalNewDelete();
1750 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001751
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001752 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1753 Expr* DeallocArgs[1];
1754 DeallocArgs[0] = &Null;
1755 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
Alexis Hunt1f69a022011-05-12 22:46:29 +00001756 DeallocArgs, 1, TUDecl, !Diagnose,
1757 Operator, Diagnose))
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001758 return true;
1759
1760 assert(Operator && "Did not find a deallocation function!");
1761 return false;
1762}
1763
Sebastian Redlbd150f42008-11-21 19:14:01 +00001764/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1765/// @code ::delete ptr; @endcode
1766/// or
1767/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00001768ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001769Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00001770 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001771 // C++ [expr.delete]p1:
1772 // The operand shall have a pointer type, or a class type having a single
1773 // conversion function to a pointer type. The result has type void.
1774 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00001775 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1776
John Wiegley01296292011-04-08 18:41:53 +00001777 ExprResult Ex = Owned(ExE);
Anders Carlssona471db02009-08-16 20:29:29 +00001778 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00001779 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00001780 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00001781
John Wiegley01296292011-04-08 18:41:53 +00001782 if (!Ex.get()->isTypeDependent()) {
1783 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001784
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001785 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001786 if (RequireCompleteType(StartLoc, Type,
Douglas Gregorf65f4902010-07-29 14:44:35 +00001787 PDiag(diag::err_delete_incomplete_class_type)))
1788 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001789
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001790 SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
John McCallda4458e2010-03-31 01:36:47 +00001791
Fariborz Jahanianb54ccb22009-09-11 21:44:33 +00001792 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001793 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001794 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001795 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00001796 NamedDecl *D = I.getDecl();
1797 if (isa<UsingShadowDecl>(D))
1798 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1799
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001800 // Skip over templated conversion functions; they aren't considered.
John McCallda4458e2010-03-31 01:36:47 +00001801 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001802 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001803
John McCallda4458e2010-03-31 01:36:47 +00001804 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001805
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001806 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1807 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00001808 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001809 ObjectPtrConversions.push_back(Conv);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001810 }
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001811 if (ObjectPtrConversions.size() == 1) {
1812 // We have a single conversion to a pointer-to-object type. Perform
1813 // that conversion.
John McCallda4458e2010-03-31 01:36:47 +00001814 // TODO: don't redo the conversion calculation.
John Wiegley01296292011-04-08 18:41:53 +00001815 ExprResult Res =
1816 PerformImplicitConversion(Ex.get(),
John McCallda4458e2010-03-31 01:36:47 +00001817 ObjectPtrConversions.front()->getConversionType(),
John Wiegley01296292011-04-08 18:41:53 +00001818 AA_Converting);
1819 if (Res.isUsable()) {
1820 Ex = move(Res);
1821 Type = Ex.get()->getType();
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001822 }
1823 }
1824 else if (ObjectPtrConversions.size() > 1) {
1825 Diag(StartLoc, diag::err_ambiguous_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00001826 << Type << Ex.get()->getSourceRange();
John McCallda4458e2010-03-31 01:36:47 +00001827 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1828 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001829 return ExprError();
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001830 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001831 }
1832
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001833 if (!Type->isPointerType())
1834 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00001835 << Type << Ex.get()->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001836
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001837 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00001838 QualType PointeeElem = Context.getBaseElementType(Pointee);
1839
1840 if (unsigned AddressSpace = Pointee.getAddressSpace())
1841 return Diag(Ex.get()->getLocStart(),
1842 diag::err_address_space_qualified_delete)
1843 << Pointee.getUnqualifiedType() << AddressSpace;
1844
1845 CXXRecordDecl *PointeeRD = 0;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00001846 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001847 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00001848 // effectively bans deletion of "void*". However, most compilers support
1849 // this, so we treat it as a warning unless we're in a SFINAE context.
1850 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00001851 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00001852 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001853 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00001854 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00001855 } else if (!Pointee->isDependentType()) {
1856 if (!RequireCompleteType(StartLoc, Pointee,
1857 PDiag(diag::warn_delete_incomplete)
1858 << Ex.get()->getSourceRange())) {
1859 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
1860 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
1861 }
1862 }
1863
Abramo Bagnarad4756b92011-11-16 15:42:13 +00001864 // Perform lvalue-to-rvalue cast, if needed.
1865 Ex = DefaultLvalueConversion(Ex.take());
1866
Douglas Gregor98496dc2009-09-29 21:38:53 +00001867 // C++ [expr.delete]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001868 // [Note: a pointer to a const type can be the operand of a
1869 // delete-expression; it is not necessary to cast away the constness
1870 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor98496dc2009-09-29 21:38:53 +00001871 // of the delete-expression. ]
John McCall31168b02011-06-15 23:02:42 +00001872 if (!Context.hasSameType(Ex.get()->getType(), Context.VoidPtrTy))
Abramo Bagnarad4756b92011-11-16 15:42:13 +00001873 Ex = Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy,
1874 CK_BitCast, Ex.take(), 0, VK_RValue));
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00001875
1876 if (Pointee->isArrayType() && !ArrayForm) {
1877 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00001878 << Type << Ex.get()->getSourceRange()
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00001879 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1880 ArrayForm = true;
1881 }
1882
Anders Carlssona471db02009-08-16 20:29:29 +00001883 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1884 ArrayForm ? OO_Array_Delete : OO_Delete);
1885
Eli Friedmanae4280f2011-07-26 22:25:31 +00001886 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001887 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00001888 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
1889 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00001890 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001891
John McCall284c48f2011-01-27 09:37:56 +00001892 // If we're allocating an array of records, check whether the
1893 // usual operator delete[] has a size_t parameter.
1894 if (ArrayForm) {
1895 // If the user specifically asked to use the global allocator,
1896 // we'll need to do the lookup into the class.
1897 if (UseGlobal)
1898 UsualArrayDeleteWantsSize =
1899 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1900
1901 // Otherwise, the usual operator delete[] should be the
1902 // function we just found.
1903 else if (isa<CXXMethodDecl>(OperatorDelete))
1904 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1905 }
1906
Eli Friedmanae4280f2011-07-26 22:25:31 +00001907 if (!PointeeRD->hasTrivialDestructor())
1908 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Mike Stump11289f42009-09-09 15:08:12 +00001909 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001910 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001911 DiagnoseUseOfDecl(Dtor, StartLoc);
1912 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00001913
1914 // C++ [expr.delete]p3:
1915 // In the first alternative (delete object), if the static type of the
1916 // object to be deleted is different from its dynamic type, the static
1917 // type shall be a base class of the dynamic type of the object to be
1918 // deleted and the static type shall have a virtual destructor or the
1919 // behavior is undefined.
1920 //
1921 // Note: a final class cannot be derived from, no issue there
Eli Friedman1b71a222011-07-26 23:27:24 +00001922 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00001923 CXXDestructorDecl *dtor = PointeeRD->getDestructor();
Eli Friedman1b71a222011-07-26 23:27:24 +00001924 if (dtor && !dtor->isVirtual()) {
1925 if (PointeeRD->isAbstract()) {
1926 // If the class is abstract, we warn by default, because we're
1927 // sure the code has undefined behavior.
1928 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
1929 << PointeeElem;
1930 } else if (!ArrayForm) {
1931 // Otherwise, if this is not an array delete, it's a bit suspect,
1932 // but not necessarily wrong.
1933 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
1934 }
1935 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00001936 }
John McCall31168b02011-06-15 23:02:42 +00001937
1938 } else if (getLangOptions().ObjCAutoRefCount &&
1939 PointeeElem->isObjCLifetimeType() &&
1940 (PointeeElem.getObjCLifetime() == Qualifiers::OCL_Strong ||
1941 PointeeElem.getObjCLifetime() == Qualifiers::OCL_Weak) &&
1942 ArrayForm) {
1943 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1944 << 1 << PointeeElem;
Anders Carlssona471db02009-08-16 20:29:29 +00001945 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001946
Anders Carlssona471db02009-08-16 20:29:29 +00001947 if (!OperatorDelete) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001948 // Look for a global declaration.
Anders Carlssona471db02009-08-16 20:29:29 +00001949 DeclareGlobalNewDelete();
1950 DeclContext *TUDecl = Context.getTranslationUnitDecl();
John Wiegley01296292011-04-08 18:41:53 +00001951 Expr *Arg = Ex.get();
Mike Stump11289f42009-09-09 15:08:12 +00001952 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
John Wiegley01296292011-04-08 18:41:53 +00001953 &Arg, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssona471db02009-08-16 20:29:29 +00001954 OperatorDelete))
1955 return ExprError();
1956 }
Mike Stump11289f42009-09-09 15:08:12 +00001957
John McCall0f55a032010-04-20 02:18:25 +00001958 MarkDeclarationReferenced(StartLoc, OperatorDelete);
John McCall284c48f2011-01-27 09:37:56 +00001959
Douglas Gregorfa778132011-02-01 15:50:11 +00001960 // Check access and ambiguity of operator delete and destructor.
Eli Friedmanae4280f2011-07-26 22:25:31 +00001961 if (PointeeRD) {
1962 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
John Wiegley01296292011-04-08 18:41:53 +00001963 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregorfa778132011-02-01 15:50:11 +00001964 PDiag(diag::err_access_dtor) << PointeeElem);
1965 }
1966 }
1967
Sebastian Redlbd150f42008-11-21 19:14:01 +00001968 }
1969
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001970 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall284c48f2011-01-27 09:37:56 +00001971 ArrayFormAsWritten,
1972 UsualArrayDeleteWantsSize,
John Wiegley01296292011-04-08 18:41:53 +00001973 OperatorDelete, Ex.take(), StartLoc));
Sebastian Redlbd150f42008-11-21 19:14:01 +00001974}
1975
Douglas Gregor633caca2009-11-23 23:44:04 +00001976/// \brief Check the use of the given variable as a C++ condition in an if,
1977/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00001978ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00001979 SourceLocation StmtLoc,
1980 bool ConvertToBoolean) {
Douglas Gregor633caca2009-11-23 23:44:04 +00001981 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001982
Douglas Gregor633caca2009-11-23 23:44:04 +00001983 // C++ [stmt.select]p2:
1984 // The declarator shall not specify a function or an array.
1985 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001986 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00001987 diag::err_invalid_use_of_function_type)
1988 << ConditionVar->getSourceRange());
1989 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001990 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00001991 diag::err_invalid_use_of_array_type)
1992 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00001993
John Wiegley01296292011-04-08 18:41:53 +00001994 ExprResult Condition =
1995 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
Douglas Gregorea972d32011-02-28 21:54:11 +00001996 ConditionVar,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001997 ConditionVar->getLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00001998 ConditionVar->getType().getNonReferenceType(),
John Wiegley01296292011-04-08 18:41:53 +00001999 VK_LValue));
2000 if (ConvertToBoolean) {
2001 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
2002 if (Condition.isInvalid())
2003 return ExprError();
2004 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002005
John Wiegley01296292011-04-08 18:41:53 +00002006 return move(Condition);
Douglas Gregor633caca2009-11-23 23:44:04 +00002007}
2008
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00002009/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley01296292011-04-08 18:41:53 +00002010ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00002011 // C++ 6.4p4:
2012 // The value of a condition that is an initialized declaration in a statement
2013 // other than a switch statement is the value of the declared variable
2014 // implicitly converted to type bool. If that conversion is ill-formed, the
2015 // program is ill-formed.
2016 // The value of a condition that is an expression is the value of the
2017 // expression, implicitly converted to bool.
2018 //
Douglas Gregor5fb53972009-01-14 15:45:31 +00002019 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00002020}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002021
2022/// Helper function to determine whether this is the (deprecated) C++
2023/// conversion from a string literal to a pointer to non-const char or
2024/// non-const wchar_t (for narrow and wide string literals,
2025/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00002026bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002027Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2028 // Look inside the implicit cast, if it exists.
2029 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2030 From = Cast->getSubExpr();
2031
2032 // A string literal (2.13.4) that is not a wide string literal can
2033 // be converted to an rvalue of type "pointer to char"; a wide
2034 // string literal can be converted to an rvalue of type "pointer
2035 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00002036 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002037 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00002038 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00002039 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002040 // This conversion is considered only when there is an
2041 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00002042 if (!ToPtrType->getPointeeType().hasQualifiers()) {
2043 switch (StrLit->getKind()) {
2044 case StringLiteral::UTF8:
2045 case StringLiteral::UTF16:
2046 case StringLiteral::UTF32:
2047 // We don't allow UTF literals to be implicitly converted
2048 break;
2049 case StringLiteral::Ascii:
2050 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2051 ToPointeeType->getKind() == BuiltinType::Char_S);
2052 case StringLiteral::Wide:
2053 return ToPointeeType->isWideCharType();
2054 }
2055 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002056 }
2057
2058 return false;
2059}
Douglas Gregor39c16d42008-10-24 04:54:22 +00002060
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002061static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00002062 SourceLocation CastLoc,
2063 QualType Ty,
2064 CastKind Kind,
2065 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00002066 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002067 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00002068 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00002069 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002070 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00002071 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00002072 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
John McCall37ad5512010-08-23 06:44:23 +00002073 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002074
Douglas Gregorc7a31072011-10-10 22:41:00 +00002075 if (S.CompleteConstructorCall(Constructor,
John McCallfaf5fb42010-08-26 23:41:50 +00002076 MultiExprArg(&From, 1),
Douglas Gregora4253922010-04-16 22:17:36 +00002077 CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00002078 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002079
Douglas Gregorc7a31072011-10-10 22:41:00 +00002080 S.CheckConstructorAccess(CastLoc, Constructor, Constructor->getAccess(),
2081 S.PDiag(diag::err_access_ctor));
2082
2083 ExprResult Result
2084 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2085 move_arg(ConstructorArgs),
2086 HadMultipleCandidates, /*ZeroInit*/ false,
2087 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00002088 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00002089 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002090
Douglas Gregora4253922010-04-16 22:17:36 +00002091 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2092 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002093
John McCalle3027922010-08-25 11:45:40 +00002094 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00002095 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002096
Douglas Gregora4253922010-04-16 22:17:36 +00002097 // Create an implicit call expr that calls it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002098 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method,
2099 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00002100 if (Result.isInvalid())
2101 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002102
John McCall30909032011-09-21 08:36:56 +00002103 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2104
Douglas Gregor668443e2011-01-20 00:18:04 +00002105 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00002106 }
2107 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002108}
Douglas Gregora4253922010-04-16 22:17:36 +00002109
Douglas Gregor5fb53972009-01-14 15:45:31 +00002110/// PerformImplicitConversion - Perform an implicit conversion of the
2111/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00002112/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002113/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002114/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00002115ExprResult
2116Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002117 const ImplicitConversionSequence &ICS,
John McCall31168b02011-06-15 23:02:42 +00002118 AssignmentAction Action,
2119 CheckedConversionKind CCK) {
John McCall0d1da222010-01-12 00:44:57 +00002120 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00002121 case ImplicitConversionSequence::StandardConversion: {
2122 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
John McCall31168b02011-06-15 23:02:42 +00002123 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00002124 if (Res.isInvalid())
2125 return ExprError();
2126 From = Res.take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002127 break;
John Wiegley01296292011-04-08 18:41:53 +00002128 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002129
Anders Carlsson110b07b2009-09-15 06:28:28 +00002130 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002131
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00002132 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00002133 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00002134 QualType BeforeToType;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002135 assert(FD && "FIXME: aggregate initialization from init list");
Anders Carlsson110b07b2009-09-15 06:28:28 +00002136 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00002137 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002138
Anders Carlsson110b07b2009-09-15 06:28:28 +00002139 // If the user-defined conversion is specified by a conversion function,
2140 // the initial standard conversion sequence converts the source type to
2141 // the implicit object parameter of the conversion function.
2142 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00002143 } else {
2144 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00002145 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002146 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00002147 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002148 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian55824512009-11-06 00:23:08 +00002149 // initial standard conversion sequence converts the source type to the
2150 // type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00002151 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2152 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002153 }
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00002154 // Watch out for elipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00002155 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00002156 ExprResult Res =
2157 PerformImplicitConversion(From, BeforeToType,
2158 ICS.UserDefined.Before, AA_Converting,
John McCall31168b02011-06-15 23:02:42 +00002159 CCK);
John Wiegley01296292011-04-08 18:41:53 +00002160 if (Res.isInvalid())
2161 return ExprError();
2162 From = Res.take();
Fariborz Jahanian55824512009-11-06 00:23:08 +00002163 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002164
2165 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00002166 = BuildCXXCastArgument(*this,
2167 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00002168 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002169 CastKind, cast<CXXMethodDecl>(FD),
2170 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002171 ICS.UserDefined.HadMultipleCandidates,
John McCallb268a282010-08-23 23:25:46 +00002172 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00002173
2174 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00002175 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00002176
John Wiegley01296292011-04-08 18:41:53 +00002177 From = CastArg.take();
Eli Friedmane96f1d32009-11-27 04:41:50 +00002178
Eli Friedmane96f1d32009-11-27 04:41:50 +00002179 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
John McCall31168b02011-06-15 23:02:42 +00002180 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00002181 }
John McCall0d1da222010-01-12 00:44:57 +00002182
2183 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00002184 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00002185 PDiag(diag::err_typecheck_ambiguous_condition)
2186 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00002187 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002188
Douglas Gregor39c16d42008-10-24 04:54:22 +00002189 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00002190 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002191
2192 case ImplicitConversionSequence::BadConversion:
John Wiegley01296292011-04-08 18:41:53 +00002193 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002194 }
2195
2196 // Everything went well.
John Wiegley01296292011-04-08 18:41:53 +00002197 return Owned(From);
Douglas Gregor39c16d42008-10-24 04:54:22 +00002198}
2199
2200/// PerformImplicitConversion - Perform an implicit conversion of the
2201/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00002202/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00002203/// expression. Flavor is the context in which we're performing this
2204/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00002205ExprResult
2206Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002207 const StandardConversionSequence& SCS,
John McCall31168b02011-06-15 23:02:42 +00002208 AssignmentAction Action,
2209 CheckedConversionKind CCK) {
2210 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2211
Mike Stump87c57ac2009-05-16 07:39:55 +00002212 // Overall FIXME: we are recomputing too many types here and doing far too
2213 // much extra work. What this means is that we need to keep track of more
2214 // information that is computed when we try the implicit conversion initially,
2215 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00002216 QualType FromType = From->getType();
John McCall31168b02011-06-15 23:02:42 +00002217
Douglas Gregor2fe98832008-11-03 19:09:14 +00002218 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00002219 // FIXME: When can ToType be a reference type?
2220 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002221 if (SCS.Second == ICK_Derived_To_Base) {
John McCall37ad5512010-08-23 06:44:23 +00002222 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002223 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCall37ad5512010-08-23 06:44:23 +00002224 MultiExprArg(*this, &From, 1),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002225 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002226 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00002227 return ExprError();
2228 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2229 ToType, SCS.CopyConstructor,
2230 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002231 /*HadMultipleCandidates*/ false,
John Wiegley01296292011-04-08 18:41:53 +00002232 /*ZeroInit*/ false,
2233 CXXConstructExpr::CK_Complete,
2234 SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002235 }
John Wiegley01296292011-04-08 18:41:53 +00002236 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2237 ToType, SCS.CopyConstructor,
2238 MultiExprArg(*this, &From, 1),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002239 /*HadMultipleCandidates*/ false,
John Wiegley01296292011-04-08 18:41:53 +00002240 /*ZeroInit*/ false,
2241 CXXConstructExpr::CK_Complete,
2242 SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00002243 }
2244
Douglas Gregor980fb162010-04-29 18:24:40 +00002245 // Resolve overloaded function references.
2246 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2247 DeclAccessPair Found;
2248 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2249 true, Found);
2250 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00002251 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00002252
2253 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
John Wiegley01296292011-04-08 18:41:53 +00002254 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002255
Douglas Gregor980fb162010-04-29 18:24:40 +00002256 From = FixOverloadedFunctionReference(From, Found, Fn);
2257 FromType = From->getType();
2258 }
2259
Douglas Gregor39c16d42008-10-24 04:54:22 +00002260 // Perform the first implicit conversion.
2261 switch (SCS.First) {
2262 case ICK_Identity:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002263 // Nothing to do.
2264 break;
2265
John McCall34376a62010-12-04 03:47:34 +00002266 case ICK_Lvalue_To_Rvalue:
John McCall526ab472011-10-25 17:37:35 +00002267 assert(From->getObjectKind() != OK_ObjCProperty);
John McCall34376a62010-12-04 03:47:34 +00002268 FromType = FromType.getUnqualifiedType();
2269 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2270 From, 0, VK_RValue);
2271 break;
2272
Douglas Gregor39c16d42008-10-24 04:54:22 +00002273 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00002274 FromType = Context.getArrayDecayedType(FromType);
John McCall31168b02011-06-15 23:02:42 +00002275 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2276 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor171c45a2009-02-18 21:56:37 +00002277 break;
2278
2279 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002280 FromType = Context.getPointerType(FromType);
John McCall31168b02011-06-15 23:02:42 +00002281 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2282 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002283 break;
2284
2285 default:
David Blaikie83d382b2011-09-23 05:06:16 +00002286 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002287 }
2288
2289 // Perform the second implicit conversion
2290 switch (SCS.Second) {
2291 case ICK_Identity:
Sebastian Redl5d431642009-10-10 12:04:10 +00002292 // If both sides are functions (or pointers/references to them), there could
2293 // be incompatible exception declarations.
2294 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00002295 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00002296 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00002297 break;
2298
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00002299 case ICK_NoReturn_Adjustment:
2300 // If both sides are functions (or pointers/references to them), there could
2301 // be incompatible exception declarations.
2302 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00002303 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002304
John McCall31168b02011-06-15 23:02:42 +00002305 From = ImpCastExprToType(From, ToType, CK_NoOp,
2306 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00002307 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002308
Douglas Gregor39c16d42008-10-24 04:54:22 +00002309 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002310 case ICK_Integral_Conversion:
John McCall31168b02011-06-15 23:02:42 +00002311 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2312 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002313 break;
2314
2315 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002316 case ICK_Floating_Conversion:
John McCall31168b02011-06-15 23:02:42 +00002317 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2318 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002319 break;
2320
2321 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00002322 case ICK_Complex_Conversion: {
2323 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2324 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2325 CastKind CK;
2326 if (FromEl->isRealFloatingType()) {
2327 if (ToEl->isRealFloatingType())
2328 CK = CK_FloatingComplexCast;
2329 else
2330 CK = CK_FloatingComplexToIntegralComplex;
2331 } else if (ToEl->isRealFloatingType()) {
2332 CK = CK_IntegralComplexToFloatingComplex;
2333 } else {
2334 CK = CK_IntegralComplexCast;
2335 }
John McCall31168b02011-06-15 23:02:42 +00002336 From = ImpCastExprToType(From, ToType, CK,
2337 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002338 break;
John McCall8cb679e2010-11-15 09:13:47 +00002339 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00002340
Douglas Gregor39c16d42008-10-24 04:54:22 +00002341 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00002342 if (ToType->isRealFloatingType())
John McCall31168b02011-06-15 23:02:42 +00002343 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2344 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002345 else
John McCall31168b02011-06-15 23:02:42 +00002346 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2347 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002348 break;
2349
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002350 case ICK_Compatible_Conversion:
John McCall31168b02011-06-15 23:02:42 +00002351 From = ImpCastExprToType(From, ToType, CK_NoOp,
2352 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002353 break;
2354
John McCall31168b02011-06-15 23:02:42 +00002355 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002356 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00002357 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002358 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00002359 if (Action == AA_Initializing || Action == AA_Assigning)
Fariborz Jahanian413e0642011-03-21 19:08:42 +00002360 Diag(From->getSourceRange().getBegin(),
2361 diag::ext_typecheck_convert_incompatible_pointer)
2362 << ToType << From->getType() << Action
Anna Zaks3b402712011-07-28 19:51:27 +00002363 << From->getSourceRange() << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00002364 else
2365 Diag(From->getSourceRange().getBegin(),
2366 diag::ext_typecheck_convert_incompatible_pointer)
2367 << From->getType() << ToType << Action
Anna Zaks3b402712011-07-28 19:51:27 +00002368 << From->getSourceRange() << 0;
John McCall31168b02011-06-15 23:02:42 +00002369
Douglas Gregor33823722011-06-11 01:09:30 +00002370 if (From->getType()->isObjCObjectPointerType() &&
2371 ToType->isObjCObjectPointerType())
2372 EmitRelatedResultTypeNote(From);
Fariborz Jahanianf2913402011-07-08 17:41:42 +00002373 }
2374 else if (getLangOptions().ObjCAutoRefCount &&
2375 !CheckObjCARCUnavailableWeakConversion(ToType,
2376 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00002377 if (Action == AA_Initializing)
2378 Diag(From->getSourceRange().getBegin(),
2379 diag::err_arc_weak_unavailable_assign);
2380 else
2381 Diag(From->getSourceRange().getBegin(),
2382 diag::err_arc_convesion_of_weak_unavailable)
2383 << (Action == AA_Casting) << From->getType() << ToType
2384 << From->getSourceRange();
2385 }
Fariborz Jahanianf2913402011-07-08 17:41:42 +00002386
John McCall8cb679e2010-11-15 09:13:47 +00002387 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00002388 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00002389 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00002390 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00002391
2392 // Make sure we extend blocks if necessary.
2393 // FIXME: doing this here is really ugly.
2394 if (Kind == CK_BlockPointerToObjCPointerCast) {
2395 ExprResult E = From;
2396 (void) PrepareCastToObjCObjectPointer(E);
2397 From = E.take();
2398 }
2399
John McCall31168b02011-06-15 23:02:42 +00002400 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2401 .take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002402 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002403 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002404
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002405 case ICK_Pointer_Member: {
John McCall8cb679e2010-11-15 09:13:47 +00002406 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00002407 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00002408 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00002409 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00002410 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00002411 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00002412 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2413 .take();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002414 break;
2415 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002416
Abramo Bagnara7ccce982011-04-07 09:26:19 +00002417 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002418 // Perform half-to-boolean conversion via float.
2419 if (From->getType()->isHalfType()) {
2420 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take();
2421 FromType = Context.FloatTy;
2422 }
2423
John Wiegley01296292011-04-08 18:41:53 +00002424 From = ImpCastExprToType(From, Context.BoolTy,
John McCall31168b02011-06-15 23:02:42 +00002425 ScalarTypeToBooleanCastKind(FromType),
2426 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002427 break;
2428
Douglas Gregor88d292c2010-05-13 16:44:06 +00002429 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00002430 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002431 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00002432 ToType.getNonReferenceType(),
2433 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002434 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00002435 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00002436 CStyle))
John Wiegley01296292011-04-08 18:41:53 +00002437 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00002438
John Wiegley01296292011-04-08 18:41:53 +00002439 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedmanbe4b3632011-09-27 21:58:52 +00002440 CK_DerivedToBase, From->getValueKind(),
John McCall31168b02011-06-15 23:02:42 +00002441 &BasePath, CCK).take();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00002442 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00002443 }
2444
Douglas Gregor46188682010-05-18 22:42:18 +00002445 case ICK_Vector_Conversion:
John McCall31168b02011-06-15 23:02:42 +00002446 From = ImpCastExprToType(From, ToType, CK_BitCast,
2447 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor46188682010-05-18 22:42:18 +00002448 break;
2449
2450 case ICK_Vector_Splat:
John McCall31168b02011-06-15 23:02:42 +00002451 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2452 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor46188682010-05-18 22:42:18 +00002453 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002454
Douglas Gregor46188682010-05-18 22:42:18 +00002455 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00002456 // Case 1. x -> _Complex y
2457 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2458 QualType ElType = ToComplex->getElementType();
2459 bool isFloatingComplex = ElType->isRealFloatingType();
2460
2461 // x -> y
2462 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2463 // do nothing
2464 } else if (From->getType()->isRealFloatingType()) {
John Wiegley01296292011-04-08 18:41:53 +00002465 From = ImpCastExprToType(From, ElType,
2466 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
John McCall8cb679e2010-11-15 09:13:47 +00002467 } else {
2468 assert(From->getType()->isIntegerType());
John Wiegley01296292011-04-08 18:41:53 +00002469 From = ImpCastExprToType(From, ElType,
2470 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
John McCall8cb679e2010-11-15 09:13:47 +00002471 }
2472 // y -> _Complex y
John Wiegley01296292011-04-08 18:41:53 +00002473 From = ImpCastExprToType(From, ToType,
John McCall8cb679e2010-11-15 09:13:47 +00002474 isFloatingComplex ? CK_FloatingRealToComplex
John Wiegley01296292011-04-08 18:41:53 +00002475 : CK_IntegralRealToComplex).take();
John McCall8cb679e2010-11-15 09:13:47 +00002476
2477 // Case 2. _Complex x -> y
2478 } else {
2479 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2480 assert(FromComplex);
2481
2482 QualType ElType = FromComplex->getElementType();
2483 bool isFloatingComplex = ElType->isRealFloatingType();
2484
2485 // _Complex x -> x
John Wiegley01296292011-04-08 18:41:53 +00002486 From = ImpCastExprToType(From, ElType,
John McCall8cb679e2010-11-15 09:13:47 +00002487 isFloatingComplex ? CK_FloatingComplexToReal
John McCall31168b02011-06-15 23:02:42 +00002488 : CK_IntegralComplexToReal,
2489 VK_RValue, /*BasePath=*/0, CCK).take();
John McCall8cb679e2010-11-15 09:13:47 +00002490
2491 // x -> y
2492 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2493 // do nothing
2494 } else if (ToType->isRealFloatingType()) {
John Wiegley01296292011-04-08 18:41:53 +00002495 From = ImpCastExprToType(From, ToType,
John McCall31168b02011-06-15 23:02:42 +00002496 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2497 VK_RValue, /*BasePath=*/0, CCK).take();
John McCall8cb679e2010-11-15 09:13:47 +00002498 } else {
2499 assert(ToType->isIntegerType());
John Wiegley01296292011-04-08 18:41:53 +00002500 From = ImpCastExprToType(From, ToType,
John McCall31168b02011-06-15 23:02:42 +00002501 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2502 VK_RValue, /*BasePath=*/0, CCK).take();
John McCall8cb679e2010-11-15 09:13:47 +00002503 }
2504 }
Douglas Gregor46188682010-05-18 22:42:18 +00002505 break;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002506
2507 case ICK_Block_Pointer_Conversion: {
John McCall31168b02011-06-15 23:02:42 +00002508 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2509 VK_RValue, /*BasePath=*/0, CCK).take();
2510 break;
2511 }
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002512
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00002513 case ICK_TransparentUnionConversion: {
John Wiegley01296292011-04-08 18:41:53 +00002514 ExprResult FromRes = Owned(From);
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00002515 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002516 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2517 if (FromRes.isInvalid())
2518 return ExprError();
2519 From = FromRes.take();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00002520 assert ((ConvTy == Sema::Compatible) &&
2521 "Improper transparent union conversion");
2522 (void)ConvTy;
2523 break;
2524 }
2525
Douglas Gregor46188682010-05-18 22:42:18 +00002526 case ICK_Lvalue_To_Rvalue:
2527 case ICK_Array_To_Pointer:
2528 case ICK_Function_To_Pointer:
2529 case ICK_Qualification:
2530 case ICK_Num_Conversion_Kinds:
David Blaikie83d382b2011-09-23 05:06:16 +00002531 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002532 }
2533
2534 switch (SCS.Third) {
2535 case ICK_Identity:
2536 // Nothing to do.
2537 break;
2538
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002539 case ICK_Qualification: {
2540 // The qualification keeps the category of the inner expression, unless the
2541 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00002542 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanbe4b3632011-09-27 21:58:52 +00002543 From->getValueKind() : VK_RValue;
John Wiegley01296292011-04-08 18:41:53 +00002544 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
John McCall31168b02011-06-15 23:02:42 +00002545 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
Douglas Gregore489a7d2010-02-28 18:30:25 +00002546
Douglas Gregore981bb02011-03-14 16:13:32 +00002547 if (SCS.DeprecatedStringLiteralToCharPtr &&
2548 !getLangOptions().WritableStrings)
Douglas Gregore489a7d2010-02-28 18:30:25 +00002549 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2550 << ToType.getNonReferenceType();
2551
Douglas Gregor39c16d42008-10-24 04:54:22 +00002552 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002553 }
2554
Douglas Gregor39c16d42008-10-24 04:54:22 +00002555 default:
David Blaikie83d382b2011-09-23 05:06:16 +00002556 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002557 }
2558
John Wiegley01296292011-04-08 18:41:53 +00002559 return Owned(From);
Douglas Gregor39c16d42008-10-24 04:54:22 +00002560}
2561
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002562ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor54e5b132010-09-09 16:14:44 +00002563 SourceLocation KWLoc,
2564 ParsedType Ty,
2565 SourceLocation RParen) {
2566 TypeSourceInfo *TSInfo;
2567 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump11289f42009-09-09 15:08:12 +00002568
Douglas Gregor54e5b132010-09-09 16:14:44 +00002569 if (!TSInfo)
2570 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002571 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor54e5b132010-09-09 16:14:44 +00002572}
2573
Chandler Carruth8e172c62011-05-01 06:51:22 +00002574/// \brief Check the completeness of a type in a unary type trait.
2575///
2576/// If the particular type trait requires a complete type, tries to complete
2577/// it. If completing the type fails, a diagnostic is emitted and false
2578/// returned. If completing the type succeeds or no completion was required,
2579/// returns true.
2580static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2581 UnaryTypeTrait UTT,
2582 SourceLocation Loc,
2583 QualType ArgTy) {
2584 // C++0x [meta.unary.prop]p3:
2585 // For all of the class templates X declared in this Clause, instantiating
2586 // that template with a template argument that is a class template
2587 // specialization may result in the implicit instantiation of the template
2588 // argument if and only if the semantics of X require that the argument
2589 // must be a complete type.
2590 // We apply this rule to all the type trait expressions used to implement
2591 // these class templates. We also try to follow any GCC documented behavior
2592 // in these expressions to ensure portability of standard libraries.
2593 switch (UTT) {
Chandler Carruth8e172c62011-05-01 06:51:22 +00002594 // is_complete_type somewhat obviously cannot require a complete type.
2595 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002596 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00002597
2598 // These traits are modeled on the type predicates in C++0x
2599 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2600 // requiring a complete type, as whether or not they return true cannot be
2601 // impacted by the completeness of the type.
2602 case UTT_IsVoid:
2603 case UTT_IsIntegral:
2604 case UTT_IsFloatingPoint:
2605 case UTT_IsArray:
2606 case UTT_IsPointer:
2607 case UTT_IsLvalueReference:
2608 case UTT_IsRvalueReference:
2609 case UTT_IsMemberFunctionPointer:
2610 case UTT_IsMemberObjectPointer:
2611 case UTT_IsEnum:
2612 case UTT_IsUnion:
2613 case UTT_IsClass:
2614 case UTT_IsFunction:
2615 case UTT_IsReference:
2616 case UTT_IsArithmetic:
2617 case UTT_IsFundamental:
2618 case UTT_IsObject:
2619 case UTT_IsScalar:
2620 case UTT_IsCompound:
2621 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002622 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00002623
2624 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2625 // which requires some of its traits to have the complete type. However,
2626 // the completeness of the type cannot impact these traits' semantics, and
2627 // so they don't require it. This matches the comments on these traits in
2628 // Table 49.
2629 case UTT_IsConst:
2630 case UTT_IsVolatile:
2631 case UTT_IsSigned:
2632 case UTT_IsUnsigned:
2633 return true;
2634
2635 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002636 // applied to a complete type.
Chandler Carruth8e172c62011-05-01 06:51:22 +00002637 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00002638 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00002639 case UTT_IsStandardLayout:
2640 case UTT_IsPOD:
2641 case UTT_IsLiteral:
2642 case UTT_IsEmpty:
2643 case UTT_IsPolymorphic:
2644 case UTT_IsAbstract:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002645 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00002646
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002647 // These trait expressions are designed to help implement predicates in
Chandler Carruth8e172c62011-05-01 06:51:22 +00002648 // [meta.unary.prop] despite not being named the same. They are specified
2649 // by both GCC and the Embarcadero C++ compiler, and require the complete
2650 // type due to the overarching C++0x type predicates being implemented
2651 // requiring the complete type.
2652 case UTT_HasNothrowAssign:
2653 case UTT_HasNothrowConstructor:
2654 case UTT_HasNothrowCopy:
2655 case UTT_HasTrivialAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00002656 case UTT_HasTrivialDefaultConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00002657 case UTT_HasTrivialCopy:
2658 case UTT_HasTrivialDestructor:
2659 case UTT_HasVirtualDestructor:
2660 // Arrays of unknown bound are expressly allowed.
2661 QualType ElTy = ArgTy;
2662 if (ArgTy->isIncompleteArrayType())
2663 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2664
2665 // The void type is expressly allowed.
2666 if (ElTy->isVoidType())
2667 return true;
2668
2669 return !S.RequireCompleteType(
2670 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00002671 }
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +00002672 llvm_unreachable("Type trait not handled by switch");
Chandler Carruth8e172c62011-05-01 06:51:22 +00002673}
2674
2675static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2676 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00002677 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00002678
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002679 ASTContext &C = Self.Context;
2680 switch(UTT) {
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002681 // Type trait expressions corresponding to the primary type category
2682 // predicates in C++0x [meta.unary.cat].
2683 case UTT_IsVoid:
2684 return T->isVoidType();
2685 case UTT_IsIntegral:
2686 return T->isIntegralType(C);
2687 case UTT_IsFloatingPoint:
2688 return T->isFloatingType();
2689 case UTT_IsArray:
2690 return T->isArrayType();
2691 case UTT_IsPointer:
2692 return T->isPointerType();
2693 case UTT_IsLvalueReference:
2694 return T->isLValueReferenceType();
2695 case UTT_IsRvalueReference:
2696 return T->isRValueReferenceType();
2697 case UTT_IsMemberFunctionPointer:
2698 return T->isMemberFunctionPointerType();
2699 case UTT_IsMemberObjectPointer:
2700 return T->isMemberDataPointerType();
2701 case UTT_IsEnum:
2702 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00002703 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00002704 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002705 case UTT_IsClass:
Chandler Carruthaf858862011-05-01 09:29:58 +00002706 return T->isClassType() || T->isStructureType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002707 case UTT_IsFunction:
2708 return T->isFunctionType();
2709
2710 // Type trait expressions which correspond to the convenient composition
2711 // predicates in C++0x [meta.unary.comp].
2712 case UTT_IsReference:
2713 return T->isReferenceType();
2714 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00002715 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002716 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00002717 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002718 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00002719 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002720 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00002721 // Note: semantic analysis depends on Objective-C lifetime types to be
2722 // considered scalar types. However, such types do not actually behave
2723 // like scalar types at run time (since they may require retain/release
2724 // operations), so we report them as non-scalar.
2725 if (T->isObjCLifetimeType()) {
2726 switch (T.getObjCLifetime()) {
2727 case Qualifiers::OCL_None:
2728 case Qualifiers::OCL_ExplicitNone:
2729 return true;
2730
2731 case Qualifiers::OCL_Strong:
2732 case Qualifiers::OCL_Weak:
2733 case Qualifiers::OCL_Autoreleasing:
2734 return false;
2735 }
2736 }
2737
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00002738 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002739 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00002740 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002741 case UTT_IsMemberPointer:
2742 return T->isMemberPointerType();
2743
2744 // Type trait expressions which correspond to the type property predicates
2745 // in C++0x [meta.unary.prop].
2746 case UTT_IsConst:
2747 return T.isConstQualified();
2748 case UTT_IsVolatile:
2749 return T.isVolatileQualified();
2750 case UTT_IsTrivial:
John McCall31168b02011-06-15 23:02:42 +00002751 return T.isTrivialType(Self.Context);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00002752 case UTT_IsTriviallyCopyable:
John McCall31168b02011-06-15 23:02:42 +00002753 return T.isTriviallyCopyableType(Self.Context);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002754 case UTT_IsStandardLayout:
2755 return T->isStandardLayoutType();
2756 case UTT_IsPOD:
John McCall31168b02011-06-15 23:02:42 +00002757 return T.isPODType(Self.Context);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002758 case UTT_IsLiteral:
2759 return T->isLiteralType();
2760 case UTT_IsEmpty:
2761 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2762 return !RD->isUnion() && RD->isEmpty();
2763 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002764 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00002765 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2766 return RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002767 return false;
2768 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00002769 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2770 return RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002771 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00002772 case UTT_IsSigned:
2773 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00002774 case UTT_IsUnsigned:
2775 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002776
2777 // Type trait expressions which query classes regarding their construction,
2778 // destruction, and copying. Rather than being based directly on the
2779 // related type predicates in the standard, they are specified by both
2780 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
2781 // specifications.
2782 //
2783 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
2784 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Alexis Huntf479f1b2011-05-09 18:22:59 +00002785 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002786 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2787 // If __is_pod (type) is true then the trait is true, else if type is
2788 // a cv class or union type (or array thereof) with a trivial default
2789 // constructor ([class.ctor]) then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00002790 if (T.isPODType(Self.Context))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002791 return true;
2792 if (const RecordType *RT =
2793 C.getBaseElementType(T)->getAs<RecordType>())
Alexis Huntf479f1b2011-05-09 18:22:59 +00002794 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002795 return false;
2796 case UTT_HasTrivialCopy:
2797 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2798 // If __is_pod (type) is true or type is a reference type then
2799 // the trait is true, else if type is a cv class or union type
2800 // with a trivial copy constructor ([class.copy]) then the trait
2801 // is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00002802 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002803 return true;
2804 if (const RecordType *RT = T->getAs<RecordType>())
2805 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2806 return false;
2807 case UTT_HasTrivialAssign:
2808 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2809 // If type is const qualified or is a reference type then the
2810 // trait is false. Otherwise if __is_pod (type) is true then the
2811 // trait is true, else if type is a cv class or union type with
2812 // a trivial copy assignment ([class.copy]) then the trait is
2813 // true, else it is false.
2814 // Note: the const and reference restrictions are interesting,
2815 // given that const and reference members don't prevent a class
2816 // from having a trivial copy assignment operator (but do cause
2817 // errors if the copy assignment operator is actually used, q.v.
2818 // [class.copy]p12).
2819
2820 if (C.getBaseElementType(T).isConstQualified())
2821 return false;
John McCall31168b02011-06-15 23:02:42 +00002822 if (T.isPODType(Self.Context))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002823 return true;
2824 if (const RecordType *RT = T->getAs<RecordType>())
2825 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2826 return false;
2827 case UTT_HasTrivialDestructor:
2828 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2829 // If __is_pod (type) is true or type is a reference type
2830 // then the trait is true, else if type is a cv class or union
2831 // type (or array thereof) with a trivial destructor
2832 // ([class.dtor]) then the trait is true, else it is
2833 // false.
John McCall31168b02011-06-15 23:02:42 +00002834 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002835 return true;
John McCall31168b02011-06-15 23:02:42 +00002836
2837 // Objective-C++ ARC: autorelease types don't require destruction.
2838 if (T->isObjCLifetimeType() &&
2839 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
2840 return true;
2841
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002842 if (const RecordType *RT =
2843 C.getBaseElementType(T)->getAs<RecordType>())
2844 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2845 return false;
2846 // TODO: Propagate nothrowness for implicitly declared special members.
2847 case UTT_HasNothrowAssign:
2848 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2849 // If type is const qualified or is a reference type then the
2850 // trait is false. Otherwise if __has_trivial_assign (type)
2851 // is true then the trait is true, else if type is a cv class
2852 // or union type with copy assignment operators that are known
2853 // not to throw an exception then the trait is true, else it is
2854 // false.
2855 if (C.getBaseElementType(T).isConstQualified())
2856 return false;
2857 if (T->isReferenceType())
2858 return false;
John McCall31168b02011-06-15 23:02:42 +00002859 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
2860 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002861 if (const RecordType *RT = T->getAs<RecordType>()) {
2862 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2863 if (RD->hasTrivialCopyAssignment())
2864 return true;
2865
2866 bool FoundAssign = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002867 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redl058fc822010-09-14 23:40:14 +00002868 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2869 Sema::LookupOrdinaryName);
2870 if (Self.LookupQualifiedName(Res, RD)) {
Douglas Gregor6a0e23f2011-10-12 15:40:49 +00002871 Res.suppressDiagnostics();
Sebastian Redl058fc822010-09-14 23:40:14 +00002872 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2873 Op != OpEnd; ++Op) {
Douglas Gregor6a0e23f2011-10-12 15:40:49 +00002874 if (isa<FunctionTemplateDecl>(*Op))
2875 continue;
2876
Sebastian Redl058fc822010-09-14 23:40:14 +00002877 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2878 if (Operator->isCopyAssignmentOperator()) {
2879 FoundAssign = true;
2880 const FunctionProtoType *CPT
2881 = Operator->getType()->getAs<FunctionProtoType>();
Richard Smith938f40b2011-06-11 17:19:42 +00002882 if (CPT->getExceptionSpecType() == EST_Delayed)
2883 return false;
2884 if (!CPT->isNothrow(Self.Context))
2885 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002886 }
2887 }
2888 }
Douglas Gregor6a0e23f2011-10-12 15:40:49 +00002889
Richard Smith938f40b2011-06-11 17:19:42 +00002890 return FoundAssign;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002891 }
2892 return false;
2893 case UTT_HasNothrowCopy:
2894 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2895 // If __has_trivial_copy (type) is true then the trait is true, else
2896 // if type is a cv class or union type with copy constructors that are
2897 // known not to throw an exception then the trait is true, else it is
2898 // false.
John McCall31168b02011-06-15 23:02:42 +00002899 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002900 return true;
2901 if (const RecordType *RT = T->getAs<RecordType>()) {
2902 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2903 if (RD->hasTrivialCopyConstructor())
2904 return true;
2905
2906 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002907 unsigned FoundTQs;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002908 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl951006f2010-09-13 21:10:20 +00002909 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002910 Con != ConEnd; ++Con) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00002911 // A template constructor is never a copy constructor.
2912 // FIXME: However, it may actually be selected at the actual overload
2913 // resolution point.
2914 if (isa<FunctionTemplateDecl>(*Con))
2915 continue;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002916 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2917 if (Constructor->isCopyConstructor(FoundTQs)) {
2918 FoundConstructor = true;
2919 const FunctionProtoType *CPT
2920 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith938f40b2011-06-11 17:19:42 +00002921 if (CPT->getExceptionSpecType() == EST_Delayed)
2922 return false;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002923 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00002924 // For now, we'll be conservative and assume that they can throw.
Richard Smith938f40b2011-06-11 17:19:42 +00002925 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
2926 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002927 }
2928 }
2929
Richard Smith938f40b2011-06-11 17:19:42 +00002930 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002931 }
2932 return false;
2933 case UTT_HasNothrowConstructor:
2934 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2935 // If __has_trivial_constructor (type) is true then the trait is
2936 // true, else if type is a cv class or union type (or array
2937 // thereof) with a default constructor that is known not to
2938 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00002939 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002940 return true;
2941 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2942 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntf479f1b2011-05-09 18:22:59 +00002943 if (RD->hasTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002944 return true;
2945
Sebastian Redlc15c3262010-09-13 22:02:47 +00002946 DeclContext::lookup_const_iterator Con, ConEnd;
2947 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2948 Con != ConEnd; ++Con) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00002949 // FIXME: In C++0x, a constructor template can be a default constructor.
2950 if (isa<FunctionTemplateDecl>(*Con))
2951 continue;
Sebastian Redlc15c3262010-09-13 22:02:47 +00002952 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2953 if (Constructor->isDefaultConstructor()) {
2954 const FunctionProtoType *CPT
2955 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith938f40b2011-06-11 17:19:42 +00002956 if (CPT->getExceptionSpecType() == EST_Delayed)
2957 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00002958 // TODO: check whether evaluating default arguments can throw.
2959 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl31ad7542011-03-13 17:09:40 +00002960 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
Sebastian Redlc15c3262010-09-13 22:02:47 +00002961 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002962 }
2963 }
2964 return false;
2965 case UTT_HasVirtualDestructor:
2966 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2967 // If type is a class type with a virtual destructor ([class.dtor])
2968 // then the trait is true, else it is false.
2969 if (const RecordType *Record = T->getAs<RecordType>()) {
2970 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redl058fc822010-09-14 23:40:14 +00002971 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002972 return Destructor->isVirtual();
2973 }
2974 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002975
2976 // These type trait expressions are modeled on the specifications for the
2977 // Embarcadero C++0x type trait functions:
2978 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
2979 case UTT_IsCompleteType:
2980 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
2981 // Returns True if and only if T is a complete type at the point of the
2982 // function call.
2983 return !T->isIncompleteType();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002984 }
Chandler Carruthb42fb192011-05-01 07:44:17 +00002985 llvm_unreachable("Type trait not covered by switch");
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002986}
2987
2988ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor54e5b132010-09-09 16:14:44 +00002989 SourceLocation KWLoc,
2990 TypeSourceInfo *TSInfo,
2991 SourceLocation RParen) {
2992 QualType T = TSInfo->getType();
Chandler Carruthb0776202011-04-30 10:07:32 +00002993 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
2994 return ExprError();
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002995
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002996 bool Value = false;
2997 if (!T->isDependentType())
Chandler Carruth8e172c62011-05-01 06:51:22 +00002998 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002999
3000 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson1f9648d2009-07-07 19:06:02 +00003001 RParen, Context.BoolTy));
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003002}
Sebastian Redl5822f082009-02-07 20:10:22 +00003003
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003004ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
3005 SourceLocation KWLoc,
3006 ParsedType LhsTy,
3007 ParsedType RhsTy,
3008 SourceLocation RParen) {
3009 TypeSourceInfo *LhsTSInfo;
3010 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3011 if (!LhsTSInfo)
3012 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3013
3014 TypeSourceInfo *RhsTSInfo;
3015 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3016 if (!RhsTSInfo)
3017 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3018
3019 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3020}
3021
3022static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3023 QualType LhsT, QualType RhsT,
3024 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00003025 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3026 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003027
3028 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00003029 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003030 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00003031 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003032 // Base and Derived are not unions and name the same class type without
3033 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003034
John McCall388ef532011-01-28 22:02:36 +00003035 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3036 if (!lhsRecord) return false;
3037
3038 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3039 if (!rhsRecord) return false;
3040
3041 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3042 == (lhsRecord == rhsRecord));
3043
3044 if (lhsRecord == rhsRecord)
3045 return !lhsRecord->getDecl()->isUnion();
3046
3047 // C++0x [meta.rel]p2:
3048 // If Base and Derived are class types and are different types
3049 // (ignoring possible cv-qualifiers) then Derived shall be a
3050 // complete type.
3051 if (Self.RequireCompleteType(KeyLoc, RhsT,
3052 diag::err_incomplete_type_used_in_type_trait_expr))
3053 return false;
3054
3055 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3056 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3057 }
John Wiegley65497cc2011-04-27 23:09:49 +00003058 case BTT_IsSame:
3059 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichet34b21132010-12-08 22:35:30 +00003060 case BTT_TypeCompatible:
3061 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3062 RhsT.getUnqualifiedType());
John Wiegley65497cc2011-04-27 23:09:49 +00003063 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00003064 case BTT_IsConvertibleTo: {
3065 // C++0x [meta.rel]p4:
3066 // Given the following function prototype:
3067 //
3068 // template <class T>
3069 // typename add_rvalue_reference<T>::type create();
3070 //
3071 // the predicate condition for a template specialization
3072 // is_convertible<From, To> shall be satisfied if and only if
3073 // the return expression in the following code would be
3074 // well-formed, including any implicit conversions to the return
3075 // type of the function:
3076 //
3077 // To test() {
3078 // return create<From>();
3079 // }
3080 //
3081 // Access checking is performed as if in a context unrelated to To and
3082 // From. Only the validity of the immediate context of the expression
3083 // of the return-statement (including conversions to the return type)
3084 // is considered.
3085 //
3086 // We model the initialization as a copy-initialization of a temporary
3087 // of the appropriate type, which for this expression is identical to the
3088 // return statement (since NRVO doesn't apply).
3089 if (LhsT->isObjectType() || LhsT->isFunctionType())
3090 LhsT = Self.Context.getRValueReferenceType(LhsT);
3091
3092 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00003093 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00003094 Expr::getValueKindForType(LhsT));
3095 Expr *FromPtr = &From;
3096 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3097 SourceLocation()));
3098
Douglas Gregoredb76852011-01-27 22:31:44 +00003099 // Perform the initialization within a SFINAE trap at translation unit
3100 // scope.
3101 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3102 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor8006e762011-01-27 20:28:01 +00003103 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00003104 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00003105 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00003106
Douglas Gregor8006e762011-01-27 20:28:01 +00003107 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
3108 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3109 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003110 }
3111 llvm_unreachable("Unknown type trait or not implemented");
3112}
3113
3114ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3115 SourceLocation KWLoc,
3116 TypeSourceInfo *LhsTSInfo,
3117 TypeSourceInfo *RhsTSInfo,
3118 SourceLocation RParen) {
3119 QualType LhsT = LhsTSInfo->getType();
3120 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003121
John McCall388ef532011-01-28 22:02:36 +00003122 if (BTT == BTT_TypeCompatible) {
Francois Pichet34b21132010-12-08 22:35:30 +00003123 if (getLangOptions().CPlusPlus) {
3124 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3125 << SourceRange(KWLoc, RParen);
3126 return ExprError();
3127 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003128 }
3129
3130 bool Value = false;
3131 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3132 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3133
Francois Pichet34b21132010-12-08 22:35:30 +00003134 // Select trait result type.
3135 QualType ResultType;
3136 switch (BTT) {
Francois Pichet34b21132010-12-08 22:35:30 +00003137 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
John Wiegley65497cc2011-04-27 23:09:49 +00003138 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3139 case BTT_IsSame: ResultType = Context.BoolTy; break;
Francois Pichet34b21132010-12-08 22:35:30 +00003140 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor8006e762011-01-27 20:28:01 +00003141 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Francois Pichet34b21132010-12-08 22:35:30 +00003142 }
3143
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003144 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3145 RhsTSInfo, Value, RParen,
Francois Pichet34b21132010-12-08 22:35:30 +00003146 ResultType));
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003147}
3148
John Wiegley6242b6a2011-04-28 00:16:57 +00003149ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3150 SourceLocation KWLoc,
3151 ParsedType Ty,
3152 Expr* DimExpr,
3153 SourceLocation RParen) {
3154 TypeSourceInfo *TSInfo;
3155 QualType T = GetTypeFromParser(Ty, &TSInfo);
3156 if (!TSInfo)
3157 TSInfo = Context.getTrivialTypeSourceInfo(T);
3158
3159 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3160}
3161
3162static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3163 QualType T, Expr *DimExpr,
3164 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00003165 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00003166
3167 switch(ATT) {
3168 case ATT_ArrayRank:
3169 if (T->isArrayType()) {
3170 unsigned Dim = 0;
3171 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3172 ++Dim;
3173 T = AT->getElementType();
3174 }
3175 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00003176 }
John Wiegleyd3522222011-04-28 02:06:46 +00003177 return 0;
3178
John Wiegley6242b6a2011-04-28 00:16:57 +00003179 case ATT_ArrayExtent: {
3180 llvm::APSInt Value;
3181 uint64_t Dim;
John Wiegleyd3522222011-04-28 02:06:46 +00003182 if (DimExpr->isIntegerConstantExpr(Value, Self.Context, 0, false)) {
3183 if (Value < llvm::APSInt(Value.getBitWidth(), Value.isUnsigned())) {
3184 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3185 DimExpr->getSourceRange();
3186 return false;
3187 }
John Wiegley6242b6a2011-04-28 00:16:57 +00003188 Dim = Value.getLimitedValue();
John Wiegleyd3522222011-04-28 02:06:46 +00003189 } else {
3190 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
3191 DimExpr->getSourceRange();
3192 return false;
3193 }
John Wiegley6242b6a2011-04-28 00:16:57 +00003194
3195 if (T->isArrayType()) {
3196 unsigned D = 0;
3197 bool Matched = false;
3198 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3199 if (Dim == D) {
3200 Matched = true;
3201 break;
3202 }
3203 ++D;
3204 T = AT->getElementType();
3205 }
3206
John Wiegleyd3522222011-04-28 02:06:46 +00003207 if (Matched && T->isArrayType()) {
3208 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3209 return CAT->getSize().getLimitedValue();
3210 }
John Wiegley6242b6a2011-04-28 00:16:57 +00003211 }
John Wiegleyd3522222011-04-28 02:06:46 +00003212 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00003213 }
3214 }
3215 llvm_unreachable("Unknown type trait or not implemented");
3216}
3217
3218ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3219 SourceLocation KWLoc,
3220 TypeSourceInfo *TSInfo,
3221 Expr* DimExpr,
3222 SourceLocation RParen) {
3223 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00003224
Chandler Carruthc5276e52011-05-01 08:48:21 +00003225 // FIXME: This should likely be tracked as an APInt to remove any host
3226 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00003227 uint64_t Value = 0;
3228 if (!T->isDependentType())
3229 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3230
Chandler Carruthc5276e52011-05-01 08:48:21 +00003231 // While the specification for these traits from the Embarcadero C++
3232 // compiler's documentation says the return type is 'unsigned int', Clang
3233 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3234 // compiler, there is no difference. On several other platforms this is an
3235 // important distinction.
John Wiegley6242b6a2011-04-28 00:16:57 +00003236 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
Chandler Carruth9cf632c2011-05-01 07:49:26 +00003237 DimExpr, RParen,
Chandler Carruthc5276e52011-05-01 08:48:21 +00003238 Context.getSizeType()));
John Wiegley6242b6a2011-04-28 00:16:57 +00003239}
3240
John Wiegleyf9f65842011-04-25 06:54:41 +00003241ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003242 SourceLocation KWLoc,
3243 Expr *Queried,
3244 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00003245 // If error parsing the expression, ignore.
3246 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003247 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00003248
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003249 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00003250
3251 return move(Result);
3252}
3253
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003254static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3255 switch (ET) {
3256 case ET_IsLValueExpr: return E->isLValue();
3257 case ET_IsRValueExpr: return E->isRValue();
3258 }
3259 llvm_unreachable("Expression trait not covered by switch");
3260}
3261
John Wiegleyf9f65842011-04-25 06:54:41 +00003262ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003263 SourceLocation KWLoc,
3264 Expr *Queried,
3265 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00003266 if (Queried->isTypeDependent()) {
3267 // Delay type-checking for type-dependent expressions.
3268 } else if (Queried->getType()->isPlaceholderType()) {
3269 ExprResult PE = CheckPlaceholderExpr(Queried);
3270 if (PE.isInvalid()) return ExprError();
3271 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3272 }
3273
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003274 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00003275
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003276 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3277 RParen, Context.BoolTy));
John Wiegleyf9f65842011-04-25 06:54:41 +00003278}
3279
Richard Trieu82402a02011-09-15 21:56:47 +00003280QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00003281 ExprValueKind &VK,
3282 SourceLocation Loc,
3283 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00003284 assert(!LHS.get()->getType()->isPlaceholderType() &&
3285 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00003286 "placeholders should have been weeded out by now");
3287
3288 // The LHS undergoes lvalue conversions if this is ->*.
3289 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00003290 LHS = DefaultLvalueConversion(LHS.take());
3291 if (LHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00003292 }
3293
3294 // The RHS always undergoes lvalue conversions.
Richard Trieu82402a02011-09-15 21:56:47 +00003295 RHS = DefaultLvalueConversion(RHS.take());
3296 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00003297
Sebastian Redl5822f082009-02-07 20:10:22 +00003298 const char *OpSpelling = isIndirect ? "->*" : ".*";
3299 // C++ 5.5p2
3300 // The binary operator .* [p3: ->*] binds its second operand, which shall
3301 // be of type "pointer to member of T" (where T is a completely-defined
3302 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00003303 QualType RHSType = RHS.get()->getType();
3304 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00003305 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00003306 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00003307 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00003308 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00003309 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00003310
Sebastian Redl5822f082009-02-07 20:10:22 +00003311 QualType Class(MemPtr->getClass(), 0);
3312
Douglas Gregord07ba342010-10-13 20:41:14 +00003313 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3314 // member pointer points must be completely-defined. However, there is no
3315 // reason for this semantic distinction, and the rule is not enforced by
3316 // other compilers. Therefore, we do not check this property, as it is
3317 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00003318
Sebastian Redl5822f082009-02-07 20:10:22 +00003319 // C++ 5.5p2
3320 // [...] to its first operand, which shall be of class T or of a class of
3321 // which T is an unambiguous and accessible base class. [p3: a pointer to
3322 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00003323 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00003324 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00003325 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
3326 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00003327 else {
3328 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00003329 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00003330 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00003331 return QualType();
3332 }
3333 }
3334
Richard Trieu82402a02011-09-15 21:56:47 +00003335 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00003336 // If we want to check the hierarchy, we need a complete type.
Richard Trieu82402a02011-09-15 21:56:47 +00003337 if (RequireCompleteType(Loc, LHSType, PDiag(diag::err_bad_memptr_lhs)
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00003338 << OpSpelling << (int)isIndirect)) {
3339 return QualType();
3340 }
Anders Carlssona70cff62010-04-24 19:06:50 +00003341 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00003342 /*DetectVirtual=*/false);
Mike Stump87c57ac2009-05-16 07:39:55 +00003343 // FIXME: Would it be useful to print full ambiguity paths, or is that
3344 // overkill?
Richard Trieu82402a02011-09-15 21:56:47 +00003345 if (!IsDerivedFrom(LHSType, Class, Paths) ||
Sebastian Redl5822f082009-02-07 20:10:22 +00003346 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3347 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00003348 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00003349 return QualType();
3350 }
Eli Friedman1fcf66b2010-01-16 00:00:48 +00003351 // Cast LHS to type of use.
3352 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanbe4b3632011-09-27 21:58:52 +00003353 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003354
John McCallcf142162010-08-07 06:22:56 +00003355 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00003356 BuildBasePathArray(Paths, BasePath);
Richard Trieu82402a02011-09-15 21:56:47 +00003357 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
3358 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00003359 }
3360
Richard Trieu82402a02011-09-15 21:56:47 +00003361 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00003362 // Diagnose use of pointer-to-member type which when used as
3363 // the functional cast in a pointer-to-member expression.
3364 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3365 return QualType();
3366 }
John McCall7decc9e2010-11-18 06:31:45 +00003367
Sebastian Redl5822f082009-02-07 20:10:22 +00003368 // C++ 5.5p2
3369 // The result is an object or a function of the type specified by the
3370 // second operand.
3371 // The cv qualifiers are the union of those in the pointer and the left side,
3372 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00003373 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00003374 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00003375
Douglas Gregor1d042092011-01-26 16:40:18 +00003376 // C++0x [expr.mptr.oper]p6:
3377 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003378 // ill-formed if the second operand is a pointer to member function with
3379 // ref-qualifier &. In a ->* expression or in a .* expression whose object
3380 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00003381 // is a pointer to member function with ref-qualifier &&.
3382 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3383 switch (Proto->getRefQualifier()) {
3384 case RQ_None:
3385 // Do nothing
3386 break;
3387
3388 case RQ_LValue:
Richard Trieu82402a02011-09-15 21:56:47 +00003389 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00003390 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00003391 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00003392 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003393
Douglas Gregor1d042092011-01-26 16:40:18 +00003394 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00003395 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00003396 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00003397 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00003398 break;
3399 }
3400 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003401
John McCall7decc9e2010-11-18 06:31:45 +00003402 // C++ [expr.mptr.oper]p6:
3403 // The result of a .* expression whose second operand is a pointer
3404 // to a data member is of the same value category as its
3405 // first operand. The result of a .* expression whose second
3406 // operand is a pointer to a member function is a prvalue. The
3407 // result of an ->* expression is an lvalue if its second operand
3408 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00003409 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00003410 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00003411 return Context.BoundMemberTy;
3412 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00003413 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00003414 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00003415 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00003416 }
John McCall7decc9e2010-11-18 06:31:45 +00003417
Sebastian Redl5822f082009-02-07 20:10:22 +00003418 return Result;
3419}
Sebastian Redl1a99f442009-04-16 17:51:27 +00003420
Sebastian Redl1a99f442009-04-16 17:51:27 +00003421/// \brief Try to convert a type to another according to C++0x 5.16p3.
3422///
3423/// This is part of the parameter validation for the ? operator. If either
3424/// value operand is a class type, the two operands are attempted to be
3425/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00003426/// It returns true if the program is ill-formed and has already been diagnosed
3427/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003428static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3429 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00003430 bool &HaveConversion,
3431 QualType &ToType) {
3432 HaveConversion = false;
3433 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003434
3435 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00003436 SourceLocation());
Sebastian Redl1a99f442009-04-16 17:51:27 +00003437 // C++0x 5.16p3
3438 // The process for determining whether an operand expression E1 of type T1
3439 // can be converted to match an operand expression E2 of type T2 is defined
3440 // as follows:
3441 // -- If E2 is an lvalue:
John McCall086a4642010-11-24 05:12:34 +00003442 bool ToIsLvalue = To->isLValue();
Douglas Gregorf9edf802010-03-26 20:59:55 +00003443 if (ToIsLvalue) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003444 // E1 can be converted to match E2 if E1 can be implicitly converted to
3445 // type "lvalue reference to T2", subject to the constraint that in the
3446 // conversion the reference must bind directly to E1.
Douglas Gregor838fcc32010-03-26 20:14:36 +00003447 QualType T = Self.Context.getLValueReferenceType(ToType);
3448 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003449
Douglas Gregor838fcc32010-03-26 20:14:36 +00003450 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3451 if (InitSeq.isDirectReferenceBinding()) {
3452 ToType = T;
3453 HaveConversion = true;
3454 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003455 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003456
Douglas Gregor838fcc32010-03-26 20:14:36 +00003457 if (InitSeq.isAmbiguous())
3458 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003459 }
John McCall65eb8792010-02-25 01:37:24 +00003460
Sebastian Redl1a99f442009-04-16 17:51:27 +00003461 // -- If E2 is an rvalue, or if the conversion above cannot be done:
3462 // -- if E1 and E2 have class type, and the underlying class types are
3463 // the same or one is a base class of the other:
3464 QualType FTy = From->getType();
3465 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003466 const RecordType *FRec = FTy->getAs<RecordType>();
3467 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003468 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregor838fcc32010-03-26 20:14:36 +00003469 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003470 if (FRec && TRec &&
Douglas Gregor838fcc32010-03-26 20:14:36 +00003471 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003472 // E1 can be converted to match E2 if the class of T2 is the
3473 // same type as, or a base class of, the class of T1, and
3474 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00003475 if (FRec == TRec || FDerivedFromT) {
3476 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00003477 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3478 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00003479 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00003480 HaveConversion = true;
3481 return false;
3482 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003483
Douglas Gregor838fcc32010-03-26 20:14:36 +00003484 if (InitSeq.isAmbiguous())
3485 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003486 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003487 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003488
Douglas Gregor838fcc32010-03-26 20:14:36 +00003489 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003490 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003491
Douglas Gregor838fcc32010-03-26 20:14:36 +00003492 // -- Otherwise: E1 can be converted to match E2 if E1 can be
3493 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003494 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00003495 // an rvalue).
3496 //
3497 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3498 // to the array-to-pointer or function-to-pointer conversions.
3499 if (!TTy->getAs<TagType>())
3500 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003501
Douglas Gregor838fcc32010-03-26 20:14:36 +00003502 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3503 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00003504 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00003505 ToType = TTy;
3506 if (InitSeq.isAmbiguous())
3507 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3508
Sebastian Redl1a99f442009-04-16 17:51:27 +00003509 return false;
3510}
3511
3512/// \brief Try to find a common type for two according to C++0x 5.16p5.
3513///
3514/// This is part of the parameter validation for the ? operator. If either
3515/// value operand is a class type, overload resolution is used to find a
3516/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00003517static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003518 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00003519 Expr *Args[2] = { LHS.get(), RHS.get() };
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003520 OverloadCandidateSet CandidateSet(QuestionLoc);
3521 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3522 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003523
3524 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003525 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00003526 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003527 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley01296292011-04-08 18:41:53 +00003528 ExprResult LHSRes =
3529 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3530 Best->Conversions[0], Sema::AA_Converting);
3531 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00003532 break;
John Wiegley01296292011-04-08 18:41:53 +00003533 LHS = move(LHSRes);
3534
3535 ExprResult RHSRes =
3536 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3537 Best->Conversions[1], Sema::AA_Converting);
3538 if (RHSRes.isInvalid())
3539 break;
3540 RHS = move(RHSRes);
Chandler Carruth30141632011-02-25 19:41:05 +00003541 if (Best->Function)
3542 Self.MarkDeclarationReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003543 return false;
John Wiegley01296292011-04-08 18:41:53 +00003544 }
3545
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003546 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003547
3548 // Emit a better diagnostic if one of the expressions is a null pointer
3549 // constant and the other is a pointer type. In this case, the user most
3550 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00003551 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003552 return true;
3553
3554 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00003555 << LHS.get()->getType() << RHS.get()->getType()
3556 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003557 return true;
3558
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003559 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003560 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00003561 << LHS.get()->getType() << RHS.get()->getType()
3562 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00003563 // FIXME: Print the possible common types by printing the return types of
3564 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003565 break;
3566
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003567 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00003568 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003569 }
3570 return true;
3571}
3572
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003573/// \brief Perform an "extended" implicit conversion as returned by
3574/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00003575static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00003576 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley01296292011-04-08 18:41:53 +00003577 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00003578 SourceLocation());
John Wiegley01296292011-04-08 18:41:53 +00003579 Expr *Arg = E.take();
3580 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
3581 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
Douglas Gregor838fcc32010-03-26 20:14:36 +00003582 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003583 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003584
John Wiegley01296292011-04-08 18:41:53 +00003585 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003586 return false;
3587}
3588
Sebastian Redl1a99f442009-04-16 17:51:27 +00003589/// \brief Check the operands of ?: under C++ semantics.
3590///
3591/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
3592/// extension. In this case, LHS == Cond. (But they're not aliases.)
John Wiegley01296292011-04-08 18:41:53 +00003593QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCallc07a0c72011-02-17 10:25:35 +00003594 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00003595 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00003596 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
3597 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003598
3599 // C++0x 5.16p1
3600 // The first expression is contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00003601 if (!Cond.get()->isTypeDependent()) {
3602 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
3603 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00003604 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003605 Cond = move(CondRes);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003606 }
3607
John McCall7decc9e2010-11-18 06:31:45 +00003608 // Assume r-value.
3609 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00003610 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00003611
Sebastian Redl1a99f442009-04-16 17:51:27 +00003612 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00003613 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00003614 return Context.DependentTy;
3615
3616 // C++0x 5.16p2
3617 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00003618 QualType LTy = LHS.get()->getType();
3619 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003620 bool LVoid = LTy->isVoidType();
3621 bool RVoid = RTy->isVoidType();
3622 if (LVoid || RVoid) {
3623 // ... then the [l2r] conversions are performed on the second and third
3624 // operands ...
John Wiegley01296292011-04-08 18:41:53 +00003625 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3626 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3627 if (LHS.isInvalid() || RHS.isInvalid())
3628 return QualType();
3629 LTy = LHS.get()->getType();
3630 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003631
3632 // ... and one of the following shall hold:
3633 // -- The second or the third operand (but not both) is a throw-
3634 // expression; the result is of the type of the other and is an rvalue.
John Wiegley01296292011-04-08 18:41:53 +00003635 bool LThrow = isa<CXXThrowExpr>(LHS.get());
3636 bool RThrow = isa<CXXThrowExpr>(RHS.get());
Sebastian Redl1a99f442009-04-16 17:51:27 +00003637 if (LThrow && !RThrow)
3638 return RTy;
3639 if (RThrow && !LThrow)
3640 return LTy;
3641
3642 // -- Both the second and third operands have type void; the result is of
3643 // type void and is an rvalue.
3644 if (LVoid && RVoid)
3645 return Context.VoidTy;
3646
3647 // Neither holds, error.
3648 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3649 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00003650 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003651 return QualType();
3652 }
3653
3654 // Neither is void.
3655
3656 // C++0x 5.16p3
3657 // Otherwise, if the second and third operand have different types, and
3658 // either has (cv) class type, and attempt is made to convert each of those
3659 // operands to the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003660 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00003661 (LTy->isRecordType() || RTy->isRecordType())) {
3662 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3663 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00003664 QualType L2RType, R2LType;
3665 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00003666 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00003667 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003668 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00003669 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003670
Sebastian Redl1a99f442009-04-16 17:51:27 +00003671 // If both can be converted, [...] the program is ill-formed.
3672 if (HaveL2R && HaveR2L) {
3673 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00003674 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003675 return QualType();
3676 }
3677
3678 // If exactly one conversion is possible, that conversion is applied to
3679 // the chosen operand and the converted operands are used in place of the
3680 // original operands for the remainder of this section.
3681 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00003682 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00003683 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003684 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003685 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00003686 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00003687 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003688 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003689 }
3690 }
3691
3692 // C++0x 5.16p4
John McCall7decc9e2010-11-18 06:31:45 +00003693 // If the second and third operands are glvalues of the same value
3694 // category and have the same type, the result is of that type and
3695 // value category and it is a bit-field if the second or the third
3696 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00003697 // We only extend this to bitfields, not to the crazy other kinds of
3698 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00003699 bool Same = Context.hasSameType(LTy, RTy);
John McCall7decc9e2010-11-18 06:31:45 +00003700 if (Same &&
John Wiegley01296292011-04-08 18:41:53 +00003701 LHS.get()->isGLValue() &&
3702 LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
3703 LHS.get()->isOrdinaryOrBitFieldObject() &&
3704 RHS.get()->isOrdinaryOrBitFieldObject()) {
3705 VK = LHS.get()->getValueKind();
3706 if (LHS.get()->getObjectKind() == OK_BitField ||
3707 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00003708 OK = OK_BitField;
John McCall7decc9e2010-11-18 06:31:45 +00003709 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00003710 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003711
3712 // C++0x 5.16p5
3713 // Otherwise, the result is an rvalue. If the second and third operands
3714 // do not have the same type, and either has (cv) class type, ...
3715 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3716 // ... overload resolution is used to determine the conversions (if any)
3717 // to be applied to the operands. If the overload resolution fails, the
3718 // program is ill-formed.
3719 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3720 return QualType();
3721 }
3722
3723 // C++0x 5.16p6
3724 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3725 // conversions are performed on the second and third operands.
John Wiegley01296292011-04-08 18:41:53 +00003726 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3727 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3728 if (LHS.isInvalid() || RHS.isInvalid())
3729 return QualType();
3730 LTy = LHS.get()->getType();
3731 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003732
3733 // After those conversions, one of the following shall hold:
3734 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003735 // is of that type. If the operands have class type, the result
3736 // is a prvalue temporary of the result type, which is
3737 // copy-initialized from either the second operand or the third
3738 // operand depending on the value of the first operand.
3739 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3740 if (LTy->isRecordType()) {
3741 // The operands have class type. Make a temporary copy.
3742 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003743 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3744 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00003745 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003746 if (LHSCopy.isInvalid())
3747 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003748
3749 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3750 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00003751 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003752 if (RHSCopy.isInvalid())
3753 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003754
John Wiegley01296292011-04-08 18:41:53 +00003755 LHS = LHSCopy;
3756 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003757 }
3758
Sebastian Redl1a99f442009-04-16 17:51:27 +00003759 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00003760 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003761
Douglas Gregor46188682010-05-18 22:42:18 +00003762 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003763 if (LTy->isVectorType() || RTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00003764 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00003765
Sebastian Redl1a99f442009-04-16 17:51:27 +00003766 // -- The second and third operands have arithmetic or enumeration type;
3767 // the usual arithmetic conversions are performed to bring them to a
3768 // common type, and the result is of that type.
3769 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3770 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00003771 if (LHS.isInvalid() || RHS.isInvalid())
3772 return QualType();
3773 return LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003774 }
3775
3776 // -- The second and third operands have pointer type, or one has pointer
3777 // type and the other is a null pointer constant; pointer conversions
3778 // and qualification conversions are performed to bring them to their
3779 // composite pointer type. The result is of the composite pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00003780 // -- The second and third operands have pointer to member type, or one has
3781 // pointer to member type and the other is a null pointer constant;
3782 // pointer to member conversions and qualification conversions are
3783 // performed to bring them to a common type, whose cv-qualification
3784 // shall match the cv-qualification of either the second or the third
3785 // operand. The result is of the common type.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003786 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00003787 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003788 isSFINAEContext()? 0 : &NonStandardCompositeType);
3789 if (!Composite.isNull()) {
3790 if (NonStandardCompositeType)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003791 Diag(QuestionLoc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003792 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3793 << LTy << RTy << Composite
John Wiegley01296292011-04-08 18:41:53 +00003794 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003795
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003796 return Composite;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003797 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003798
Douglas Gregor697a3912010-04-01 22:47:07 +00003799 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00003800 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3801 if (!Composite.isNull())
3802 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003803
Chandler Carruth9c9127e2011-02-19 00:13:59 +00003804 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00003805 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00003806 return QualType();
3807
Sebastian Redl1a99f442009-04-16 17:51:27 +00003808 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00003809 << LHS.get()->getType() << RHS.get()->getType()
3810 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003811 return QualType();
3812}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003813
3814/// \brief Find a merged pointer type and convert the two expressions to it.
3815///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003816/// This finds the composite pointer type (or member pointer type) for @p E1
3817/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3818/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003819/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003820///
Douglas Gregor19175ff2010-04-16 23:20:25 +00003821/// \param Loc The location of the operator requiring these two expressions to
3822/// be converted to the composite pointer type.
3823///
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003824/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3825/// a non-standard (but still sane) composite type to which both expressions
3826/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3827/// will be set true.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003828QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00003829 Expr *&E1, Expr *&E2,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003830 bool *NonStandardCompositeType) {
3831 if (NonStandardCompositeType)
3832 *NonStandardCompositeType = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003833
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003834 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3835 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003836
Fariborz Jahanian33e148f2009-12-08 20:04:24 +00003837 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3838 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003839 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003840
3841 // C++0x 5.9p2
3842 // Pointer conversions and qualification conversions are performed on
3843 // pointer operands to bring them to their composite pointer type. If
3844 // one operand is a null pointer constant, the composite pointer type is
3845 // the type of the other operand.
Douglas Gregor56751b52009-09-25 04:25:58 +00003846 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003847 if (T2->isMemberPointerType())
John Wiegley01296292011-04-08 18:41:53 +00003848 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003849 else
John Wiegley01296292011-04-08 18:41:53 +00003850 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003851 return T2;
3852 }
Douglas Gregor56751b52009-09-25 04:25:58 +00003853 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003854 if (T1->isMemberPointerType())
John Wiegley01296292011-04-08 18:41:53 +00003855 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003856 else
John Wiegley01296292011-04-08 18:41:53 +00003857 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003858 return T1;
3859 }
Mike Stump11289f42009-09-09 15:08:12 +00003860
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003861 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00003862 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3863 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003864 return QualType();
3865
3866 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3867 // the other has type "pointer to cv2 T" and the composite pointer type is
3868 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3869 // Otherwise, the composite pointer type is a pointer type similar to the
3870 // type of one of the operands, with a cv-qualification signature that is
3871 // the union of the cv-qualification signatures of the operand types.
3872 // In practice, the first part here is redundant; it's subsumed by the second.
3873 // What we do here is, we build the two possible composite types, and try the
3874 // conversions in both directions. If only one works, or if the two composite
3875 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00003876 // FIXME: extended qualifiers?
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003877 typedef SmallVector<unsigned, 4> QualifierVector;
Sebastian Redl658262f2009-11-16 21:03:45 +00003878 QualifierVector QualifierUnion;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003879 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
Sebastian Redl658262f2009-11-16 21:03:45 +00003880 ContainingClassVector;
3881 ContainingClassVector MemberOfClass;
3882 QualType Composite1 = Context.getCanonicalType(T1),
3883 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003884 unsigned NeedConstBefore = 0;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003885 do {
3886 const PointerType *Ptr1, *Ptr2;
3887 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3888 (Ptr2 = Composite2->getAs<PointerType>())) {
3889 Composite1 = Ptr1->getPointeeType();
3890 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003891
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003892 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003893 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003894 if (NonStandardCompositeType &&
3895 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3896 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003897
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003898 QualifierUnion.push_back(
3899 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3900 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3901 continue;
3902 }
Mike Stump11289f42009-09-09 15:08:12 +00003903
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003904 const MemberPointerType *MemPtr1, *MemPtr2;
3905 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3906 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3907 Composite1 = MemPtr1->getPointeeType();
3908 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003909
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003910 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003911 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003912 if (NonStandardCompositeType &&
3913 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3914 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003915
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003916 QualifierUnion.push_back(
3917 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3918 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3919 MemPtr2->getClass()));
3920 continue;
3921 }
Mike Stump11289f42009-09-09 15:08:12 +00003922
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003923 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00003924
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003925 // Cannot unwrap any more types.
3926 break;
3927 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00003928
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003929 if (NeedConstBefore && NonStandardCompositeType) {
3930 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003931 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003932 // requirements of C++ [conv.qual]p4 bullet 3.
3933 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3934 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3935 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3936 *NonStandardCompositeType = true;
3937 }
3938 }
3939 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003940
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003941 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-11-16 21:03:45 +00003942 ContainingClassVector::reverse_iterator MOC
3943 = MemberOfClass.rbegin();
3944 for (QualifierVector::reverse_iterator
3945 I = QualifierUnion.rbegin(),
3946 E = QualifierUnion.rend();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003947 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00003948 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003949 if (MOC->first && MOC->second) {
3950 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00003951 Composite1 = Context.getMemberPointerType(
3952 Context.getQualifiedType(Composite1, Quals),
3953 MOC->first);
3954 Composite2 = Context.getMemberPointerType(
3955 Context.getQualifiedType(Composite2, Quals),
3956 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003957 } else {
3958 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00003959 Composite1
3960 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3961 Composite2
3962 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003963 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003964 }
3965
Douglas Gregor19175ff2010-04-16 23:20:25 +00003966 // Try to convert to the first composite pointer type.
3967 InitializedEntity Entity1
3968 = InitializedEntity::InitializeTemporary(Composite1);
3969 InitializationKind Kind
3970 = InitializationKind::CreateCopy(Loc, SourceLocation());
3971 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3972 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump11289f42009-09-09 15:08:12 +00003973
Douglas Gregor19175ff2010-04-16 23:20:25 +00003974 if (E1ToC1 && E2ToC1) {
3975 // Conversion to Composite1 is viable.
3976 if (!Context.hasSameType(Composite1, Composite2)) {
3977 // Composite2 is a different type from Composite1. Check whether
3978 // Composite2 is also viable.
3979 InitializedEntity Entity2
3980 = InitializedEntity::InitializeTemporary(Composite2);
3981 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3982 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3983 if (E1ToC2 && E2ToC2) {
3984 // Both Composite1 and Composite2 are viable and are different;
3985 // this is an ambiguity.
3986 return QualType();
3987 }
3988 }
3989
3990 // Convert E1 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00003991 ExprResult E1Result
John McCall37ad5512010-08-23 06:44:23 +00003992 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00003993 if (E1Result.isInvalid())
3994 return QualType();
3995 E1 = E1Result.takeAs<Expr>();
3996
3997 // Convert E2 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00003998 ExprResult E2Result
John McCall37ad5512010-08-23 06:44:23 +00003999 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00004000 if (E2Result.isInvalid())
4001 return QualType();
4002 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004003
Douglas Gregor19175ff2010-04-16 23:20:25 +00004004 return Composite1;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004005 }
4006
Douglas Gregor19175ff2010-04-16 23:20:25 +00004007 // Check whether Composite2 is viable.
4008 InitializedEntity Entity2
4009 = InitializedEntity::InitializeTemporary(Composite2);
4010 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4011 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4012 if (!E1ToC2 || !E2ToC2)
4013 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004014
Douglas Gregor19175ff2010-04-16 23:20:25 +00004015 // Convert E1 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00004016 ExprResult E1Result
John McCall37ad5512010-08-23 06:44:23 +00004017 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00004018 if (E1Result.isInvalid())
4019 return QualType();
4020 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004021
Douglas Gregor19175ff2010-04-16 23:20:25 +00004022 // Convert E2 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00004023 ExprResult E2Result
John McCall37ad5512010-08-23 06:44:23 +00004024 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00004025 if (E2Result.isInvalid())
4026 return QualType();
4027 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004028
Douglas Gregor19175ff2010-04-16 23:20:25 +00004029 return Composite2;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004030}
Anders Carlsson85a307d2009-05-17 18:41:29 +00004031
John McCalldadc5752010-08-24 06:29:42 +00004032ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00004033 if (!E)
4034 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004035
John McCall31168b02011-06-15 23:02:42 +00004036 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4037
4038 // If the result is a glvalue, we shouldn't bind it.
4039 if (!E->isRValue())
Anders Carlssonf86a8d12009-08-15 23:41:35 +00004040 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00004041
John McCall31168b02011-06-15 23:02:42 +00004042 // In ARC, calls that return a retainable type can return retained,
4043 // in which case we have to insert a consuming cast.
4044 if (getLangOptions().ObjCAutoRefCount &&
4045 E->getType()->isObjCRetainableType()) {
4046
4047 bool ReturnsRetained;
4048
4049 // For actual calls, we compute this by examining the type of the
4050 // called value.
4051 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4052 Expr *Callee = Call->getCallee()->IgnoreParens();
4053 QualType T = Callee->getType();
4054
4055 if (T == Context.BoundMemberTy) {
4056 // Handle pointer-to-members.
4057 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4058 T = BinOp->getRHS()->getType();
4059 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4060 T = Mem->getMemberDecl()->getType();
4061 }
4062
4063 if (const PointerType *Ptr = T->getAs<PointerType>())
4064 T = Ptr->getPointeeType();
4065 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4066 T = Ptr->getPointeeType();
4067 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4068 T = MemPtr->getPointeeType();
4069
4070 const FunctionType *FTy = T->getAs<FunctionType>();
4071 assert(FTy && "call to value not of function type?");
4072 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4073
4074 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4075 // type always produce a +1 object.
4076 } else if (isa<StmtExpr>(E)) {
4077 ReturnsRetained = true;
4078
4079 // For message sends and property references, we try to find an
4080 // actual method. FIXME: we should infer retention by selector in
4081 // cases where we don't have an actual method.
4082 } else {
John McCall32a4da02011-08-03 07:02:44 +00004083 ObjCMethodDecl *D = 0;
John McCall31168b02011-06-15 23:02:42 +00004084 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4085 D = Send->getMethodDecl();
John McCall31168b02011-06-15 23:02:42 +00004086 }
4087
4088 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00004089
4090 // Don't do reclaims on performSelector calls; despite their
4091 // return type, the invoked method doesn't necessarily actually
4092 // return an object.
4093 if (!ReturnsRetained &&
4094 D && D->getMethodFamily() == OMF_performSelector)
4095 return Owned(E);
John McCall31168b02011-06-15 23:02:42 +00004096 }
4097
John McCall16de4d22011-11-14 19:53:16 +00004098 // Don't reclaim an object of Class type.
4099 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4100 return Owned(E);
4101
John McCall4db5c3c2011-07-07 06:58:02 +00004102 ExprNeedsCleanups = true;
4103
John McCall2d637d22011-09-10 06:18:15 +00004104 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4105 : CK_ARCReclaimReturnedObject);
John McCall4db5c3c2011-07-07 06:58:02 +00004106 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4107 VK_RValue));
John McCall31168b02011-06-15 23:02:42 +00004108 }
4109
4110 if (!getLangOptions().CPlusPlus)
4111 return Owned(E);
Douglas Gregor363b1512009-12-24 18:51:59 +00004112
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004113 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlsson2d4cada2009-05-30 20:36:53 +00004114 if (!RT)
4115 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00004116
John McCall67da35c2010-02-04 22:26:26 +00004117 // That should be enough to guarantee that this type is complete.
4118 // If it has a trivial destructor, we can avoid the extra copy.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00004119 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCallbdb989e2010-08-12 02:40:37 +00004120 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall67da35c2010-02-04 22:26:26 +00004121 return Owned(E);
4122
John McCall31168b02011-06-15 23:02:42 +00004123 CXXDestructorDecl *Destructor = LookupDestructor(RD);
4124
4125 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
4126 if (Destructor) {
Fariborz Jahanian67828442009-08-03 19:13:25 +00004127 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00004128 CheckDestructorAccess(E->getExprLoc(), Destructor,
4129 PDiag(diag::err_access_dtor_temp)
4130 << E->getType());
John McCall31168b02011-06-15 23:02:42 +00004131
John McCall28fc7092011-11-10 05:35:25 +00004132 // We need a cleanup, but we don't need to remember the temporary.
John McCall31168b02011-06-15 23:02:42 +00004133 ExprNeedsCleanups = true;
John McCall8e36d532010-04-07 00:41:46 +00004134 }
Anders Carlsson2d4cada2009-05-30 20:36:53 +00004135 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
4136}
4137
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004138ExprResult
John McCall5d413782010-12-06 08:20:24 +00004139Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004140 if (SubExpr.isInvalid())
4141 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004142
John McCall5d413782010-12-06 08:20:24 +00004143 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004144}
4145
John McCall28fc7092011-11-10 05:35:25 +00004146Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
4147 assert(SubExpr && "sub expression can't be null!");
4148
4149 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
4150 assert(ExprCleanupObjects.size() >= FirstCleanup);
4151 assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
4152 if (!ExprNeedsCleanups)
4153 return SubExpr;
4154
4155 ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
4156 = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
4157 ExprCleanupObjects.size() - FirstCleanup);
4158
4159 Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
4160 DiscardCleanupsInEvaluationContext();
4161
4162 return E;
4163}
4164
John McCall5d413782010-12-06 08:20:24 +00004165Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004166 assert(SubStmt && "sub statement can't be null!");
4167
John McCall31168b02011-06-15 23:02:42 +00004168 if (!ExprNeedsCleanups)
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004169 return SubStmt;
4170
4171 // FIXME: In order to attach the temporaries, wrap the statement into
4172 // a StmtExpr; currently this is only used for asm statements.
4173 // This is hacky, either create a new CXXStmtWithTemporaries statement or
4174 // a new AsmStmtWithTemporaries.
4175 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
4176 SourceLocation(),
4177 SourceLocation());
4178 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
4179 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00004180 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004181}
4182
John McCalldadc5752010-08-24 06:29:42 +00004183ExprResult
John McCallb268a282010-08-23 23:25:46 +00004184Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallba7bf592010-08-24 05:47:05 +00004185 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00004186 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004187 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004188 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00004189 if (Result.isInvalid()) return ExprError();
4190 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00004191
John McCall526ab472011-10-25 17:37:35 +00004192 Result = CheckPlaceholderExpr(Base);
4193 if (Result.isInvalid()) return ExprError();
4194 Base = Result.take();
4195
John McCallb268a282010-08-23 23:25:46 +00004196 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00004197 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004198 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00004199 // If we have a pointer to a dependent type and are using the -> operator,
4200 // the object type is the type that the pointer points to. We might still
4201 // have enough information about that type to do something useful.
4202 if (OpKind == tok::arrow)
4203 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4204 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004205
John McCallba7bf592010-08-24 05:47:05 +00004206 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00004207 MayBePseudoDestructor = true;
John McCallb268a282010-08-23 23:25:46 +00004208 return Owned(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004209 }
Mike Stump11289f42009-09-09 15:08:12 +00004210
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004211 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00004212 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004213 // returned, with the original second operand.
4214 if (OpKind == tok::arrow) {
John McCallc1538c02009-09-30 01:01:30 +00004215 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00004216 llvm::SmallPtrSet<CanQualType,8> CTypes;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004217 SmallVector<SourceLocation, 8> Locations;
John McCallbd0465b2009-09-30 01:30:54 +00004218 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004219
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004220 while (BaseType->isRecordType()) {
John McCallb268a282010-08-23 23:25:46 +00004221 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
4222 if (Result.isInvalid())
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004223 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00004224 Base = Result.get();
4225 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonfbd2d492009-10-13 22:55:59 +00004226 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallb268a282010-08-23 23:25:46 +00004227 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00004228 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCallbd0465b2009-09-30 01:30:54 +00004229 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00004230 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00004231 for (unsigned i = 0; i < Locations.size(); i++)
4232 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00004233 return ExprError();
4234 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004235 }
Mike Stump11289f42009-09-09 15:08:12 +00004236
Douglas Gregore4f764f2009-11-20 19:58:21 +00004237 if (BaseType->isPointerType())
4238 BaseType = BaseType->getPointeeType();
4239 }
Mike Stump11289f42009-09-09 15:08:12 +00004240
4241 // We could end up with various non-record types here, such as extended
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004242 // vector types or Objective-C interfaces. Just return early and let
4243 // ActOnMemberReferenceExpr do the work.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00004244 if (!BaseType->isRecordType()) {
4245 // C++ [basic.lookup.classref]p2:
4246 // [...] If the type of the object expression is of pointer to scalar
4247 // type, the unqualified-id is looked up in the context of the complete
4248 // postfix-expression.
Douglas Gregore610ada2010-02-24 18:44:31 +00004249 //
4250 // This also indicates that we should be parsing a
4251 // pseudo-destructor-name.
John McCallba7bf592010-08-24 05:47:05 +00004252 ObjectType = ParsedType();
Douglas Gregore610ada2010-02-24 18:44:31 +00004253 MayBePseudoDestructor = true;
John McCallb268a282010-08-23 23:25:46 +00004254 return Owned(Base);
Douglas Gregor2b6ca462009-09-03 21:38:09 +00004255 }
Mike Stump11289f42009-09-09 15:08:12 +00004256
Douglas Gregor3fad6172009-11-17 05:17:33 +00004257 // The object type must be complete (or dependent).
4258 if (!BaseType->isDependentType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004259 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor3fad6172009-11-17 05:17:33 +00004260 PDiag(diag::err_incomplete_member_access)))
4261 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004262
Douglas Gregor2b6ca462009-09-03 21:38:09 +00004263 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004264 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00004265 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00004266 // type C (or of pointer to a class type C), the unqualified-id is looked
4267 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00004268 ObjectType = ParsedType::make(BaseType);
Mike Stump11289f42009-09-09 15:08:12 +00004269 return move(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004270}
4271
John McCalldadc5752010-08-24 06:29:42 +00004272ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCallb268a282010-08-23 23:25:46 +00004273 Expr *MemExpr) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004274 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCallb268a282010-08-23 23:25:46 +00004275 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
4276 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregora771f462010-03-31 17:46:05 +00004277 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004278
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004279 return ActOnCallExpr(/*Scope*/ 0,
John McCallb268a282010-08-23 23:25:46 +00004280 MemExpr,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004281 /*LPLoc*/ ExpectedLParenLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00004282 MultiExprArg(),
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004283 /*RPLoc*/ ExpectedLParenLoc);
4284}
Douglas Gregore610ada2010-02-24 18:44:31 +00004285
John McCalldadc5752010-08-24 06:29:42 +00004286ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00004287 SourceLocation OpLoc,
4288 tok::TokenKind OpKind,
4289 const CXXScopeSpec &SS,
4290 TypeSourceInfo *ScopeTypeInfo,
4291 SourceLocation CCLoc,
4292 SourceLocation TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00004293 PseudoDestructorTypeStorage Destructed,
John McCalla2c4e722011-02-25 05:21:17 +00004294 bool HasTrailingLParen) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00004295 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004296
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004297 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004298 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004299 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004300 // This scalar type is the object type.
John McCallb268a282010-08-23 23:25:46 +00004301 QualType ObjectType = Base->getType();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004302 if (OpKind == tok::arrow) {
4303 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4304 ObjectType = Ptr->getPointeeType();
John McCallb268a282010-08-23 23:25:46 +00004305 } else if (!Base->isTypeDependent()) {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004306 // The user wrote "p->" when she probably meant "p."; fix it.
4307 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4308 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00004309 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004310 if (isSFINAEContext())
4311 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004312
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004313 OpKind = tok::period;
4314 }
4315 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004316
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004317 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
4318 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCallb268a282010-08-23 23:25:46 +00004319 << ObjectType << Base->getSourceRange();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004320 return ExprError();
4321 }
4322
4323 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004324 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004325 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00004326 if (DestructedTypeInfo) {
4327 QualType DestructedType = DestructedTypeInfo->getType();
4328 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004329 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00004330 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
4331 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
4332 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
4333 << ObjectType << DestructedType << Base->getSourceRange()
4334 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004335
John McCall31168b02011-06-15 23:02:42 +00004336 // Recover by setting the destructed type to the object type.
4337 DestructedType = ObjectType;
4338 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregor678f90d2010-02-25 01:56:36 +00004339 DestructedTypeStart);
John McCall31168b02011-06-15 23:02:42 +00004340 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4341 } else if (DestructedType.getObjCLifetime() !=
4342 ObjectType.getObjCLifetime()) {
4343
4344 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
4345 // Okay: just pretend that the user provided the correctly-qualified
4346 // type.
4347 } else {
4348 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
4349 << ObjectType << DestructedType << Base->getSourceRange()
4350 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4351 }
4352
4353 // Recover by setting the destructed type to the object type.
4354 DestructedType = ObjectType;
4355 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4356 DestructedTypeStart);
4357 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4358 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00004359 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004360 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004361
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004362 // C++ [expr.pseudo]p2:
4363 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4364 // form
4365 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004366 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004367 //
4368 // shall designate the same scalar type.
4369 if (ScopeTypeInfo) {
4370 QualType ScopeType = ScopeTypeInfo->getType();
4371 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00004372 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004373
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004374 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004375 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00004376 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004377 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004378
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004379 ScopeType = QualType();
4380 ScopeTypeInfo = 0;
4381 }
4382 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004383
John McCallb268a282010-08-23 23:25:46 +00004384 Expr *Result
4385 = new (Context) CXXPseudoDestructorExpr(Context, Base,
4386 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00004387 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00004388 ScopeTypeInfo,
4389 CCLoc,
4390 TildeLoc,
4391 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004392
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004393 if (HasTrailingLParen)
John McCallb268a282010-08-23 23:25:46 +00004394 return Owned(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004395
John McCallb268a282010-08-23 23:25:46 +00004396 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004397}
4398
John McCalldadc5752010-08-24 06:29:42 +00004399ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00004400 SourceLocation OpLoc,
4401 tok::TokenKind OpKind,
4402 CXXScopeSpec &SS,
4403 UnqualifiedId &FirstTypeName,
4404 SourceLocation CCLoc,
4405 SourceLocation TildeLoc,
4406 UnqualifiedId &SecondTypeName,
4407 bool HasTrailingLParen) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004408 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4409 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4410 "Invalid first type name in pseudo-destructor");
4411 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4412 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4413 "Invalid second type name in pseudo-destructor");
4414
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004415 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004416 // The left-hand side of the dot operator shall be of scalar type. The
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004417 // left-hand side of the arrow operator shall be of pointer to scalar type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004418 // This scalar type is the object type.
John McCallb268a282010-08-23 23:25:46 +00004419 QualType ObjectType = Base->getType();
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004420 if (OpKind == tok::arrow) {
4421 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4422 ObjectType = Ptr->getPointeeType();
Douglas Gregor678f90d2010-02-25 01:56:36 +00004423 } else if (!ObjectType->isDependentType()) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004424 // The user wrote "p->" when she probably meant "p."; fix it.
4425 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregor678f90d2010-02-25 01:56:36 +00004426 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00004427 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004428 if (isSFINAEContext())
4429 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004430
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004431 OpKind = tok::period;
4432 }
4433 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00004434
4435 // Compute the object type that we should use for name lookup purposes. Only
4436 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00004437 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00004438 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00004439 if (ObjectType->isRecordType())
4440 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00004441 else if (ObjectType->isDependentType())
4442 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00004443 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004444
4445 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004446 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004447 QualType DestructedType;
4448 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregor678f90d2010-02-25 01:56:36 +00004449 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004450 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004451 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00004452 SecondTypeName.StartLocation,
Fariborz Jahanian87967422011-02-08 18:05:59 +00004453 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004454 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00004455 ((SS.isSet() && !computeDeclContext(SS, false)) ||
4456 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004457 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00004458 // couldn't find anything useful in scope. Just store the identifier and
4459 // it's location, and we'll perform (qualified) name lookup again at
4460 // template instantiation time.
4461 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
4462 SecondTypeName.StartLocation);
4463 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004464 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004465 diag::err_pseudo_dtor_destructor_non_type)
4466 << SecondTypeName.Identifier << ObjectType;
4467 if (isSFINAEContext())
4468 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004469
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004470 // Recover by assuming we had the right type all along.
4471 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004472 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004473 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004474 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004475 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004476 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004477 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4478 TemplateId->getTemplateArgs(),
4479 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00004480 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4481 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004482 TemplateId->TemplateNameLoc,
4483 TemplateId->LAngleLoc,
4484 TemplateArgsPtr,
4485 TemplateId->RAngleLoc);
4486 if (T.isInvalid() || !T.get()) {
4487 // Recover by assuming we had the right type all along.
4488 DestructedType = ObjectType;
4489 } else
4490 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004491 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004492
4493 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004494 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00004495 if (!DestructedType.isNull()) {
4496 if (!DestructedTypeInfo)
4497 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004498 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00004499 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4500 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004501
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004502 // Convert the name of the scope type (the type prior to '::') into a type.
4503 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004504 QualType ScopeType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004505 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004506 FirstTypeName.Identifier) {
4507 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004508 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00004509 FirstTypeName.StartLocation,
Douglas Gregora6ce6082011-02-25 18:19:59 +00004510 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004511 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004512 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004513 diag::err_pseudo_dtor_destructor_non_type)
4514 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004515
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004516 if (isSFINAEContext())
4517 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004518
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004519 // Just drop this type. It's unnecessary anyway.
4520 ScopeType = QualType();
4521 } else
4522 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004523 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004524 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004525 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004526 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4527 TemplateId->getTemplateArgs(),
4528 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00004529 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4530 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004531 TemplateId->TemplateNameLoc,
4532 TemplateId->LAngleLoc,
4533 TemplateArgsPtr,
4534 TemplateId->RAngleLoc);
4535 if (T.isInvalid() || !T.get()) {
4536 // Recover by dropping this type.
4537 ScopeType = QualType();
4538 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004539 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004540 }
4541 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004542
Douglas Gregor90ad9222010-02-24 23:02:30 +00004543 if (!ScopeType.isNull() && !ScopeTypeInfo)
4544 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
4545 FirstTypeName.StartLocation);
4546
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004547
John McCallb268a282010-08-23 23:25:46 +00004548 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00004549 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00004550 Destructed, HasTrailingLParen);
Douglas Gregore610ada2010-02-24 18:44:31 +00004551}
4552
John Wiegley01296292011-04-08 18:41:53 +00004553ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004554 CXXMethodDecl *Method,
4555 bool HadMultipleCandidates) {
John Wiegley01296292011-04-08 18:41:53 +00004556 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
4557 FoundDecl, Method);
4558 if (Exp.isInvalid())
Douglas Gregor668443e2011-01-20 00:18:04 +00004559 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00004560
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004561 MemberExpr *ME =
John Wiegley01296292011-04-08 18:41:53 +00004562 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
John McCall7decc9e2010-11-18 06:31:45 +00004563 SourceLocation(), Method->getType(),
4564 VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004565 if (HadMultipleCandidates)
4566 ME->setHadMultipleCandidates(true);
4567
John McCall7decc9e2010-11-18 06:31:45 +00004568 QualType ResultType = Method->getResultType();
4569 ExprValueKind VK = Expr::getValueKindForType(ResultType);
4570 ResultType = ResultType.getNonLValueExprType(Context);
4571
John Wiegley01296292011-04-08 18:41:53 +00004572 MarkDeclarationReferenced(Exp.get()->getLocStart(), Method);
Douglas Gregor27381f32009-11-23 12:27:39 +00004573 CXXMemberCallExpr *CE =
John McCall7decc9e2010-11-18 06:31:45 +00004574 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
John Wiegley01296292011-04-08 18:41:53 +00004575 Exp.get()->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00004576 return CE;
4577}
4578
Sebastian Redl4202c0f2010-09-10 20:55:43 +00004579ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4580 SourceLocation RParen) {
Sebastian Redl4202c0f2010-09-10 20:55:43 +00004581 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
4582 Operand->CanThrow(Context),
4583 KeyLoc, RParen));
4584}
4585
4586ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
4587 Expr *Operand, SourceLocation RParen) {
4588 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00004589}
4590
John McCall34376a62010-12-04 03:47:34 +00004591/// Perform the conversions required for an expression used in a
4592/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00004593ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00004594 if (E->hasPlaceholderType()) {
4595 ExprResult result = CheckPlaceholderExpr(E);
4596 if (result.isInvalid()) return Owned(E);
4597 E = result.take();
4598 }
4599
John McCallfee942d2010-12-02 02:07:15 +00004600 // C99 6.3.2.1:
4601 // [Except in specific positions,] an lvalue that does not have
4602 // array type is converted to the value stored in the
4603 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00004604 if (E->isRValue()) {
4605 // In C, function designators (i.e. expressions of function type)
4606 // are r-values, but we still want to do function-to-pointer decay
4607 // on them. This is both technically correct and convenient for
4608 // some clients.
4609 if (!getLangOptions().CPlusPlus && E->getType()->isFunctionType())
4610 return DefaultFunctionArrayConversion(E);
4611
4612 return Owned(E);
4613 }
John McCallfee942d2010-12-02 02:07:15 +00004614
John McCall34376a62010-12-04 03:47:34 +00004615 // Otherwise, this rule does not apply in C++, at least not for the moment.
John Wiegley01296292011-04-08 18:41:53 +00004616 if (getLangOptions().CPlusPlus) return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00004617
4618 // GCC seems to also exclude expressions of incomplete enum type.
4619 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
4620 if (!T->getDecl()->isComplete()) {
4621 // FIXME: stupid workaround for a codegen bug!
John Wiegley01296292011-04-08 18:41:53 +00004622 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
4623 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00004624 }
4625 }
4626
John Wiegley01296292011-04-08 18:41:53 +00004627 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
4628 if (Res.isInvalid())
4629 return Owned(E);
4630 E = Res.take();
4631
John McCallca61b652010-12-04 12:29:11 +00004632 if (!E->getType()->isVoidType())
4633 RequireCompleteType(E->getExprLoc(), E->getType(),
4634 diag::err_incomplete_type);
John Wiegley01296292011-04-08 18:41:53 +00004635 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00004636}
4637
John Wiegley01296292011-04-08 18:41:53 +00004638ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
4639 ExprResult FullExpr = Owned(FE);
4640
4641 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004642 return ExprError();
John McCall34376a62010-12-04 03:47:34 +00004643
John Wiegley01296292011-04-08 18:41:53 +00004644 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00004645 return ExprError();
4646
John McCall3aef3d82011-04-10 19:13:55 +00004647 FullExpr = CheckPlaceholderExpr(FullExpr.take());
4648 if (FullExpr.isInvalid())
4649 return ExprError();
Douglas Gregor0ec210b2011-03-07 02:05:23 +00004650
John Wiegley01296292011-04-08 18:41:53 +00004651 FullExpr = IgnoredValueConversions(FullExpr.take());
4652 if (FullExpr.isInvalid())
4653 return ExprError();
4654
Richard Trieu021baa32011-09-23 20:10:00 +00004655 CheckImplicitConversions(FullExpr.get(), FullExpr.get()->getExprLoc());
John McCall5d413782010-12-06 08:20:24 +00004656 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00004657}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004658
4659StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
4660 if (!FullStmt) return StmtError();
4661
John McCall5d413782010-12-06 08:20:24 +00004662 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004663}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00004664
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004665Sema::IfExistsResult
4666Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
4667 CXXScopeSpec &SS,
4668 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00004669 DeclarationName TargetName = TargetNameInfo.getName();
4670 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00004671 return IER_DoesNotExist;
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004672
Douglas Gregor43edb322011-10-24 22:31:10 +00004673 // If the name itself is dependent, then the result is dependent.
4674 if (TargetName.isDependentName())
4675 return IER_Dependent;
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004676
Francois Pichet4a7de3e2011-05-06 20:48:22 +00004677 // Do the redeclaration lookup in the current scope.
4678 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
4679 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00004680 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00004681 R.suppressDiagnostics();
Douglas Gregor43edb322011-10-24 22:31:10 +00004682
4683 switch (R.getResultKind()) {
4684 case LookupResult::Found:
4685 case LookupResult::FoundOverloaded:
4686 case LookupResult::FoundUnresolvedValue:
4687 case LookupResult::Ambiguous:
4688 return IER_Exists;
4689
4690 case LookupResult::NotFound:
4691 return IER_DoesNotExist;
4692
4693 case LookupResult::NotFoundInCurrentInstantiation:
4694 return IER_Dependent;
4695 }
4696
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004697 return IER_DoesNotExist;
Francois Pichet4a7de3e2011-05-06 20:48:22 +00004698}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004699
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00004700Sema::IfExistsResult
4701Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4702 bool IsIfExists, CXXScopeSpec &SS,
4703 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004704 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00004705
4706 // Check for unexpanded parameter packs.
4707 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
4708 collectUnexpandedParameterPacks(SS, Unexpanded);
4709 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
4710 if (!Unexpanded.empty()) {
4711 DiagnoseUnexpandedParameterPacks(KeywordLoc,
4712 IsIfExists? UPPC_IfExists
4713 : UPPC_IfNotExists,
4714 Unexpanded);
4715 return IER_Error;
4716 }
4717
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00004718 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
4719}
4720