blob: f7342b433e19323ad6f7e3d9e4e8577ff2513ff0 [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"
19#include "clang/Sema/TemplateDeduction.h"
Steve Naroffaac94152007-08-25 14:02:58 +000020#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000021#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000023#include "clang/AST/ExprCXX.h"
Fariborz Jahanian1d446082010-06-16 18:56:04 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000025#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000026#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000027#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000028#include "clang/Lex/Preprocessor.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000029#include "llvm/ADT/STLExtras.h"
Chris Lattner29375652006-12-04 18:06:35 +000030using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000031using namespace sema;
Chris Lattner29375652006-12-04 18:06:35 +000032
John McCallba7bf592010-08-24 05:47:05 +000033ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
34 IdentifierInfo &II,
35 SourceLocation NameLoc,
36 Scope *S, CXXScopeSpec &SS,
37 ParsedType ObjectTypePtr,
38 bool EnteringContext) {
Douglas Gregorfe17d252010-02-16 19:09:40 +000039 // Determine where to perform name lookup.
40
41 // FIXME: This area of the standard is very messy, and the current
42 // wording is rather unclear about which scopes we search for the
43 // destructor name; see core issues 399 and 555. Issue 399 in
44 // particular shows where the current description of destructor name
45 // lookup is completely out of line with existing practice, e.g.,
46 // this appears to be ill-formed:
47 //
48 // namespace N {
49 // template <typename T> struct S {
50 // ~S();
51 // };
52 // }
53 //
54 // void f(N::S<int>* s) {
55 // s->N::S<int>::~S();
56 // }
57 //
Douglas Gregor46841e12010-02-23 00:15:22 +000058 // See also PR6358 and PR6359.
Sebastian Redla771d222010-07-07 23:17:38 +000059 // For this reason, we're currently only doing the C++03 version of this
60 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregorfe17d252010-02-16 19:09:40 +000061 QualType SearchType;
62 DeclContext *LookupCtx = 0;
63 bool isDependent = false;
64 bool LookInScope = false;
65
66 // If we have an object type, it's because we are in a
67 // pseudo-destructor-expression or a member access expression, and
68 // we know what type we're looking for.
69 if (ObjectTypePtr)
70 SearchType = GetTypeFromParser(ObjectTypePtr);
71
72 if (SS.isSet()) {
Douglas Gregor46841e12010-02-23 00:15:22 +000073 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
74
75 bool AlreadySearched = false;
76 bool LookAtPrefix = true;
Sebastian Redla771d222010-07-07 23:17:38 +000077 // C++ [basic.lookup.qual]p6:
78 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
79 // the type-names are looked up as types in the scope designated by the
80 // nested-name-specifier. In a qualified-id of the form:
81 //
82 // ::[opt] nested-name-specifier ̃ class-name
83 //
84 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth8f254812010-02-21 10:19:54 +000085 // a qualified-id of the form:
Douglas Gregorfe17d252010-02-16 19:09:40 +000086 //
Sebastian Redla771d222010-07-07 23:17:38 +000087 // ::opt nested-name-specifier class-name :: ̃ class-name
Douglas Gregorfe17d252010-02-16 19:09:40 +000088 //
Sebastian Redla771d222010-07-07 23:17:38 +000089 // the class-names are looked up as types in the scope designated by
90 // the nested-name-specifier.
Douglas Gregorfe17d252010-02-16 19:09:40 +000091 //
Sebastian Redla771d222010-07-07 23:17:38 +000092 // Here, we check the first case (completely) and determine whether the
93 // code below is permitted to look at the prefix of the
94 // nested-name-specifier.
95 DeclContext *DC = computeDeclContext(SS, EnteringContext);
96 if (DC && DC->isFileContext()) {
97 AlreadySearched = true;
98 LookupCtx = DC;
99 isDependent = false;
100 } else if (DC && isa<CXXRecordDecl>(DC))
101 LookAtPrefix = false;
102
103 // The second case from the C++03 rules quoted further above.
Douglas Gregor46841e12010-02-23 00:15:22 +0000104 NestedNameSpecifier *Prefix = 0;
105 if (AlreadySearched) {
106 // Nothing left to do.
107 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
108 CXXScopeSpec PrefixSS;
109 PrefixSS.setScopeRep(Prefix);
110 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
111 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor46841e12010-02-23 00:15:22 +0000112 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000113 LookupCtx = computeDeclContext(SearchType);
114 isDependent = SearchType->isDependentType();
115 } else {
116 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000117 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000118 }
Douglas Gregor46841e12010-02-23 00:15:22 +0000119
Douglas Gregorcd3f49f2010-02-25 04:46:04 +0000120 LookInScope = false;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000121 } else if (ObjectTypePtr) {
122 // C++ [basic.lookup.classref]p3:
123 // If the unqualified-id is ~type-name, the type-name is looked up
124 // in the context of the entire postfix-expression. If the type T
125 // of the object expression is of a class type C, the type-name is
126 // also looked up in the scope of class C. At least one of the
127 // lookups shall find a name that refers to (possibly
128 // cv-qualified) T.
129 LookupCtx = computeDeclContext(SearchType);
130 isDependent = SearchType->isDependentType();
131 assert((isDependent || !SearchType->isIncompleteType()) &&
132 "Caller should have completed object type");
133
134 LookInScope = true;
135 } else {
136 // Perform lookup into the current scope (only).
137 LookInScope = true;
138 }
139
140 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
141 for (unsigned Step = 0; Step != 2; ++Step) {
142 // Look for the name first in the computed lookup context (if we
143 // have one) and, if that fails to find a match, in the sope (if
144 // we're allowed to look there).
145 Found.clear();
146 if (Step == 0 && LookupCtx)
147 LookupQualifiedName(Found, LookupCtx);
Douglas Gregor678f90d2010-02-25 01:56:36 +0000148 else if (Step == 1 && LookInScope && S)
Douglas Gregorfe17d252010-02-16 19:09:40 +0000149 LookupName(Found, S);
150 else
151 continue;
152
153 // FIXME: Should we be suppressing ambiguities here?
154 if (Found.isAmbiguous())
John McCallba7bf592010-08-24 05:47:05 +0000155 return ParsedType();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000156
157 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
158 QualType T = Context.getTypeDeclType(Type);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000159
160 if (SearchType.isNull() || SearchType->isDependentType() ||
161 Context.hasSameUnqualifiedType(T, SearchType)) {
162 // We found our type!
163
John McCallba7bf592010-08-24 05:47:05 +0000164 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000165 }
166 }
167
168 // If the name that we found is a class template name, and it is
169 // the same name as the template name in the last part of the
170 // nested-name-specifier (if present) or the object type, then
171 // this is the destructor for that class.
172 // FIXME: This is a workaround until we get real drafting for core
173 // issue 399, for which there isn't even an obvious direction.
174 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
175 QualType MemberOfType;
176 if (SS.isSet()) {
177 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
178 // Figure out the type of the context, if it has one.
John McCalle78aac42010-03-10 03:28:59 +0000179 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
180 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000181 }
182 }
183 if (MemberOfType.isNull())
184 MemberOfType = SearchType;
185
186 if (MemberOfType.isNull())
187 continue;
188
189 // We're referring into a class template specialization. If the
190 // class template we found is the same as the template being
191 // specialized, we found what we are looking for.
192 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
193 if (ClassTemplateSpecializationDecl *Spec
194 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
195 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
196 Template->getCanonicalDecl())
John McCallba7bf592010-08-24 05:47:05 +0000197 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000198 }
199
200 continue;
201 }
202
203 // We're referring to an unresolved class template
204 // specialization. Determine whether we class template we found
205 // is the same as the template being specialized or, if we don't
206 // know which template is being specialized, that it at least
207 // has the same name.
208 if (const TemplateSpecializationType *SpecType
209 = MemberOfType->getAs<TemplateSpecializationType>()) {
210 TemplateName SpecName = SpecType->getTemplateName();
211
212 // The class template we found is the same template being
213 // specialized.
214 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
215 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallba7bf592010-08-24 05:47:05 +0000216 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000217
218 continue;
219 }
220
221 // The class template we found has the same name as the
222 // (dependent) template name being specialized.
223 if (DependentTemplateName *DepTemplate
224 = SpecName.getAsDependentTemplateName()) {
225 if (DepTemplate->isIdentifier() &&
226 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallba7bf592010-08-24 05:47:05 +0000227 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000228
229 continue;
230 }
231 }
232 }
233 }
234
235 if (isDependent) {
236 // We didn't find our type, but that's okay: it's dependent
237 // anyway.
238 NestedNameSpecifier *NNS = 0;
239 SourceRange Range;
240 if (SS.isSet()) {
241 NNS = (NestedNameSpecifier *)SS.getScopeRep();
242 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
243 } else {
244 NNS = NestedNameSpecifier::Create(Context, &II);
245 Range = SourceRange(NameLoc);
246 }
247
John McCallba7bf592010-08-24 05:47:05 +0000248 QualType T = CheckTypenameType(ETK_None, NNS, II,
249 SourceLocation(),
250 Range, NameLoc);
251 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000252 }
253
254 if (ObjectTypePtr)
255 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
256 << &II;
257 else
258 Diag(NameLoc, diag::err_destructor_class_name);
259
John McCallba7bf592010-08-24 05:47:05 +0000260 return ParsedType();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000261}
262
Douglas Gregor9da64192010-04-26 22:37:10 +0000263/// \brief Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000264ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000265 SourceLocation TypeidLoc,
266 TypeSourceInfo *Operand,
267 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000268 // C++ [expr.typeid]p4:
269 // The top-level cv-qualifiers of the lvalue expression or the type-id
270 // that is the operand of typeid are always ignored.
271 // If the type of the type-id is a class type or a reference to a class
272 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000273 Qualifiers Quals;
274 QualType T
275 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
276 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000277 if (T->getAs<RecordType>() &&
278 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
279 return ExprError();
Daniel Dunbar0547ad32010-05-11 21:32:35 +0000280
Douglas Gregor9da64192010-04-26 22:37:10 +0000281 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
282 Operand,
283 SourceRange(TypeidLoc, RParenLoc)));
284}
285
286/// \brief Build a C++ typeid expression with an expression operand.
John McCalldadc5752010-08-24 06:29:42 +0000287ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000288 SourceLocation TypeidLoc,
289 Expr *E,
290 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000291 bool isUnevaluatedOperand = true;
Douglas Gregor9da64192010-04-26 22:37:10 +0000292 if (E && !E->isTypeDependent()) {
293 QualType T = E->getType();
294 if (const RecordType *RecordT = T->getAs<RecordType>()) {
295 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
296 // C++ [expr.typeid]p3:
297 // [...] If the type of the expression is a class type, the class
298 // shall be completely-defined.
299 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
300 return ExprError();
301
302 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000303 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000304 // polymorphic class type [...] [the] expression is an unevaluated
305 // operand. [...]
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000306 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000307 isUnevaluatedOperand = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000308
309 // We require a vtable to query the type at run time.
310 MarkVTableUsed(TypeidLoc, RecordD);
311 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000312 }
313
314 // C++ [expr.typeid]p4:
315 // [...] If the type of the type-id is a reference to a possibly
316 // cv-qualified type, the result of the typeid expression refers to a
317 // std::type_info object representing the cv-unqualified referenced
318 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000319 Qualifiers Quals;
320 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
321 if (!Context.hasSameType(T, UnqualT)) {
322 T = UnqualT;
John McCalle3027922010-08-25 11:45:40 +0000323 ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E));
Douglas Gregor9da64192010-04-26 22:37:10 +0000324 }
325 }
326
327 // If this is an unevaluated operand, clear out the set of
328 // declaration references we have been computing and eliminate any
329 // temporaries introduced in its computation.
330 if (isUnevaluatedOperand)
331 ExprEvalContexts.back().Context = Unevaluated;
332
333 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCallb268a282010-08-23 23:25:46 +0000334 E,
Douglas Gregor9da64192010-04-26 22:37:10 +0000335 SourceRange(TypeidLoc, RParenLoc)));
336}
337
338/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000339ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000340Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
341 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000342 // Find the std::type_info type.
Douglas Gregor87f54062009-09-15 22:30:29 +0000343 if (!StdNamespace)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000344 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000345
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000346 if (!CXXTypeInfoDecl) {
347 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
348 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
349 LookupQualifiedName(R, getStdNamespace());
350 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
351 if (!CXXTypeInfoDecl)
352 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
353 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000354
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000355 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
Douglas Gregor9da64192010-04-26 22:37:10 +0000356
357 if (isType) {
358 // The operand is a type; handle it as such.
359 TypeSourceInfo *TInfo = 0;
John McCallba7bf592010-08-24 05:47:05 +0000360 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
361 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000362 if (T.isNull())
363 return ExprError();
364
365 if (!TInfo)
366 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000367
Douglas Gregor9da64192010-04-26 22:37:10 +0000368 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000369 }
Mike Stump11289f42009-09-09 15:08:12 +0000370
Douglas Gregor9da64192010-04-26 22:37:10 +0000371 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000372 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000373}
374
Francois Pichetb7577652010-12-27 01:32:00 +0000375/// Retrieve the UuidAttr associated with QT.
376static UuidAttr *GetUuidAttrOfType(QualType QT) {
377 // Optionally remove one level of pointer, reference or array indirection.
John McCall424cec92011-01-19 06:33:43 +0000378 const Type *Ty = QT.getTypePtr();;
Francois Pichet9dddd402010-12-20 03:51:03 +0000379 if (QT->isPointerType() || QT->isReferenceType())
380 Ty = QT->getPointeeType().getTypePtr();
381 else if (QT->isArrayType())
382 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
383
Francois Pichetb7577652010-12-27 01:32:00 +0000384 // Loop all class definition and declaration looking for an uuid attribute.
385 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
386 while (RD) {
387 if (UuidAttr *Uuid = RD->getAttr<UuidAttr>())
388 return Uuid;
389 RD = RD->getPreviousDeclaration();
390 }
391 return 0;
Francois Pichet9dddd402010-12-20 03:51:03 +0000392}
393
Francois Pichet9f4f2072010-09-08 12:20:18 +0000394/// \brief Build a Microsoft __uuidof expression with a type operand.
395ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
396 SourceLocation TypeidLoc,
397 TypeSourceInfo *Operand,
398 SourceLocation RParenLoc) {
Francois Pichetb7577652010-12-27 01:32:00 +0000399 if (!Operand->getType()->isDependentType()) {
400 if (!GetUuidAttrOfType(Operand->getType()))
401 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
402 }
403
Francois Pichet9f4f2072010-09-08 12:20:18 +0000404 // FIXME: add __uuidof semantic analysis for type operand.
405 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
406 Operand,
407 SourceRange(TypeidLoc, RParenLoc)));
408}
409
410/// \brief Build a Microsoft __uuidof expression with an expression operand.
411ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
412 SourceLocation TypeidLoc,
413 Expr *E,
414 SourceLocation RParenLoc) {
Francois Pichetb7577652010-12-27 01:32:00 +0000415 if (!E->getType()->isDependentType()) {
416 if (!GetUuidAttrOfType(E->getType()) &&
417 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
418 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
419 }
420 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000421 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
422 E,
423 SourceRange(TypeidLoc, RParenLoc)));
424}
425
426/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
427ExprResult
428Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
429 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
430 // If MSVCGuidDecl has not been cached, do the lookup.
431 if (!MSVCGuidDecl) {
432 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
433 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
434 LookupQualifiedName(R, Context.getTranslationUnitDecl());
435 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
436 if (!MSVCGuidDecl)
437 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
438 }
439
440 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
441
442 if (isType) {
443 // The operand is a type; handle it as such.
444 TypeSourceInfo *TInfo = 0;
445 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
446 &TInfo);
447 if (T.isNull())
448 return ExprError();
449
450 if (!TInfo)
451 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
452
453 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
454 }
455
456 // The operand is an expression.
457 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
458}
459
Steve Naroff66356bd2007-09-16 14:56:35 +0000460/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000461ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000462Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000463 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000464 "Unknown C++ Boolean value!");
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000465 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
466 Context.BoolTy, OpLoc));
Bill Wendling4073ed52007-02-13 01:51:42 +0000467}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000468
Sebastian Redl576fd422009-05-10 18:38:11 +0000469/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000470ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000471Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
472 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
473}
474
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000475/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000476ExprResult
John McCallb268a282010-08-23 23:25:46 +0000477Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000478 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
479 return ExprError();
480 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
481}
482
483/// CheckCXXThrowOperand - Validate the operand of a throw.
484bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
485 // C++ [except.throw]p3:
Douglas Gregor247894b2009-12-23 22:04:40 +0000486 // A throw-expression initializes a temporary object, called the exception
487 // object, the type of which is determined by removing any top-level
488 // cv-qualifiers from the static type of the operand of throw and adjusting
489 // the type from "array of T" or "function returning T" to "pointer to T"
490 // or "pointer to function returning T", [...]
491 if (E->getType().hasQualifiers())
John McCalle3027922010-08-25 11:45:40 +0000492 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000493 CastCategory(E));
Douglas Gregor247894b2009-12-23 22:04:40 +0000494
Sebastian Redl4de47b42009-04-27 20:27:31 +0000495 DefaultFunctionArrayConversion(E);
496
497 // If the type of the exception would be an incomplete type or a pointer
498 // to an incomplete type other than (cv) void the program is ill-formed.
499 QualType Ty = E->getType();
John McCall2e6567a2010-04-22 01:10:34 +0000500 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000501 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000502 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000503 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000504 }
505 if (!isPointer || !Ty->isVoidType()) {
506 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlsson029fc692009-08-26 22:59:12 +0000507 PDiag(isPointer ? diag::err_throw_incomplete_ptr
508 : diag::err_throw_incomplete)
509 << E->getSourceRange()))
Sebastian Redl4de47b42009-04-27 20:27:31 +0000510 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000511
Douglas Gregore8154332010-04-15 18:05:39 +0000512 if (RequireNonAbstractType(ThrowLoc, E->getType(),
513 PDiag(diag::err_throw_abstract_type)
514 << E->getSourceRange()))
515 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000516 }
517
John McCall2e6567a2010-04-22 01:10:34 +0000518 // Initialize the exception result. This implicitly weeds out
519 // abstract types or types with inaccessible copy constructors.
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000520 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p34.
John McCall2e6567a2010-04-22 01:10:34 +0000521 InitializedEntity Entity =
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000522 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
523 /*NRVO=*/false);
John McCalldadc5752010-08-24 06:29:42 +0000524 ExprResult Res = PerformCopyInitialization(Entity,
John McCall2e6567a2010-04-22 01:10:34 +0000525 SourceLocation(),
526 Owned(E));
527 if (Res.isInvalid())
528 return true;
529 E = Res.takeAs<Expr>();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000530
Eli Friedman91a3d272010-06-03 20:39:03 +0000531 // If the exception has class type, we need additional handling.
532 const RecordType *RecordTy = Ty->getAs<RecordType>();
533 if (!RecordTy)
534 return false;
535 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
536
Douglas Gregor88d292c2010-05-13 16:44:06 +0000537 // If we are throwing a polymorphic class type or pointer thereof,
538 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000539 MarkVTableUsed(ThrowLoc, RD);
540
Eli Friedman36ebbec2010-10-12 20:32:36 +0000541 // If a pointer is thrown, the referenced object will not be destroyed.
542 if (isPointer)
543 return false;
544
Eli Friedman91a3d272010-06-03 20:39:03 +0000545 // If the class has a non-trivial destructor, we must be able to call it.
546 if (RD->hasTrivialDestructor())
547 return false;
548
Douglas Gregorbac74902010-07-01 14:13:13 +0000549 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +0000550 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman91a3d272010-06-03 20:39:03 +0000551 if (!Destructor)
552 return false;
553
554 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
555 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregor747eb782010-07-08 06:14:04 +0000556 PDiag(diag::err_access_dtor_exception) << Ty);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000557 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000558}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000559
John McCalldadc5752010-08-24 06:29:42 +0000560ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000561 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
562 /// is a non-lvalue expression whose value is the address of the object for
563 /// which the function is called.
564
John McCall87fe5d52010-05-20 01:18:31 +0000565 DeclContext *DC = getFunctionLevelDeclContext();
566 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000567 if (MD->isInstance())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000568 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000569 MD->getThisType(Context),
570 /*isImplicit=*/false));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000571
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000572 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000573}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000574
John McCalldadc5752010-08-24 06:29:42 +0000575ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +0000576Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000577 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000578 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000579 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +0000580 if (!TypeRep)
581 return ExprError();
Douglas Gregor2b88c112010-09-08 00:15:04 +0000582
John McCall97513962010-01-15 18:39:57 +0000583 TypeSourceInfo *TInfo;
584 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
585 if (!TInfo)
586 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +0000587
588 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
589}
590
591/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
592/// Can be interpreted either as function-style casting ("int(x)")
593/// or class type construction ("ClassType(x,y,z)")
594/// or creation of a value-initialized type ("int()").
595ExprResult
596Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
597 SourceLocation LParenLoc,
598 MultiExprArg exprs,
599 SourceLocation RParenLoc) {
600 QualType Ty = TInfo->getType();
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000601 unsigned NumExprs = exprs.size();
602 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregor2b88c112010-09-08 00:15:04 +0000603 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000604 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
605
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000606 if (Ty->isDependentType() ||
Douglas Gregor0950e412009-03-13 21:01:28 +0000607 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000608 exprs.release();
Mike Stump11289f42009-09-09 15:08:12 +0000609
Douglas Gregor2b88c112010-09-08 00:15:04 +0000610 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregorce934142009-05-20 18:46:25 +0000611 LParenLoc,
612 Exprs, NumExprs,
613 RParenLoc));
Douglas Gregor0950e412009-03-13 21:01:28 +0000614 }
615
Anders Carlsson55243162009-08-27 03:53:50 +0000616 if (Ty->isArrayType())
617 return ExprError(Diag(TyBeginLoc,
618 diag::err_value_init_for_array_type) << FullRange);
619 if (!Ty->isVoidType() &&
620 RequireCompleteType(TyBeginLoc, Ty,
621 PDiag(diag::err_invalid_incomplete_type_use)
622 << FullRange))
623 return ExprError();
Fariborz Jahanian9a14b842009-10-23 21:01:39 +0000624
Anders Carlsson55243162009-08-27 03:53:50 +0000625 if (RequireNonAbstractType(TyBeginLoc, Ty,
626 diag::err_allocation_of_abstract_type))
627 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000628
629
Douglas Gregordd04d332009-01-16 18:33:17 +0000630 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000631 // If the expression list is a single expression, the type conversion
632 // expression is equivalent (in definedness, and if defined in meaning) to the
633 // corresponding cast expression.
634 //
635 if (NumExprs == 1) {
John McCall8cb679e2010-11-15 09:13:47 +0000636 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +0000637 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +0000638 CXXCastPath BasePath;
Douglas Gregor2b88c112010-09-08 00:15:04 +0000639 if (CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
John McCall7decc9e2010-11-18 06:31:45 +0000640 Kind, VK, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +0000641 /*FunctionalStyle=*/true))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000642 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +0000643
644 exprs.release();
Anders Carlssone9766d52009-09-09 21:33:21 +0000645
John McCallcf142162010-08-07 06:22:56 +0000646 return Owned(CXXFunctionalCastExpr::Create(Context,
Douglas Gregor2b88c112010-09-08 00:15:04 +0000647 Ty.getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +0000648 VK, TInfo, TyBeginLoc, Kind,
John McCallcf142162010-08-07 06:22:56 +0000649 Exprs[0], &BasePath,
650 RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000651 }
652
Douglas Gregor8ec51732010-09-08 21:40:08 +0000653 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
654 InitializationKind Kind
655 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
656 LParenLoc, RParenLoc)
657 : InitializationKind::CreateValue(TyBeginLoc,
658 LParenLoc, RParenLoc);
659 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
660 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000661
Douglas Gregor8ec51732010-09-08 21:40:08 +0000662 // FIXME: Improve AST representation?
663 return move(Result);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000664}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000665
666
Sebastian Redlbd150f42008-11-21 19:14:01 +0000667/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
668/// @code new (memory) int[size][4] @endcode
669/// or
670/// @code ::new Foo(23, "hello") @endcode
671/// For the interpretation of this heap of arguments, consult the base version.
John McCalldadc5752010-08-24 06:29:42 +0000672ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000673Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000674 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000675 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl351bb782008-12-02 14:43:59 +0000676 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000677 MultiExprArg ConstructorArgs,
Mike Stump11289f42009-09-09 15:08:12 +0000678 SourceLocation ConstructorRParen) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000679 Expr *ArraySize = 0;
Sebastian Redl351bb782008-12-02 14:43:59 +0000680 // If the specified type is an array, unwrap it and save the expression.
681 if (D.getNumTypeObjects() > 0 &&
682 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
683 DeclaratorChunk &Chunk = D.getTypeObject(0);
684 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000685 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
686 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000687 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000688 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
689 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000690
Sebastian Redl351bb782008-12-02 14:43:59 +0000691 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000692 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +0000693 }
694
Douglas Gregor73341c42009-09-11 00:18:58 +0000695 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000696 if (ArraySize) {
697 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +0000698 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
699 break;
700
701 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
702 if (Expr *NumElts = (Expr *)Array.NumElts) {
703 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
704 !NumElts->isIntegerConstantExpr(Context)) {
705 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
706 << NumElts->getSourceRange();
707 return ExprError();
708 }
709 }
710 }
711 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000712
John McCall8cb7bdf2010-06-04 23:28:52 +0000713 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
714 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000715 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000716 return ExprError();
Ted Kremenekabb1f912010-06-25 22:48:49 +0000717
Douglas Gregor0744ef62010-09-07 21:49:58 +0000718 if (!TInfo)
719 TInfo = Context.getTrivialTypeSourceInfo(AllocType);
720
Mike Stump11289f42009-09-09 15:08:12 +0000721 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000722 PlacementLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000723 move(PlacementArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +0000724 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000725 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +0000726 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +0000727 TInfo,
John McCallb268a282010-08-23 23:25:46 +0000728 ArraySize,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000729 ConstructorLParen,
730 move(ConstructorArgs),
731 ConstructorRParen);
732}
733
John McCalldadc5752010-08-24 06:29:42 +0000734ExprResult
Douglas Gregord0fefba2009-05-21 00:00:09 +0000735Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
736 SourceLocation PlacementLParen,
737 MultiExprArg PlacementArgs,
738 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000739 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000740 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +0000741 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +0000742 Expr *ArraySize,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000743 SourceLocation ConstructorLParen,
744 MultiExprArg ConstructorArgs,
745 SourceLocation ConstructorRParen) {
Douglas Gregor0744ef62010-09-07 21:49:58 +0000746 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redl351bb782008-12-02 14:43:59 +0000747
Douglas Gregorcda95f42010-05-16 16:01:03 +0000748 // Per C++0x [expr.new]p5, the type being constructed may be a
749 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +0000750 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +0000751 if (const ConstantArrayType *Array
752 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000753 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
754 Context.getSizeType(),
755 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +0000756 AllocType = Array->getElementType();
757 }
758 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000759
Douglas Gregor3999e152010-10-06 16:00:31 +0000760 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
761 return ExprError();
762
Douglas Gregorcda95f42010-05-16 16:01:03 +0000763 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl351bb782008-12-02 14:43:59 +0000764
Sebastian Redlbd150f42008-11-21 19:14:01 +0000765 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
766 // or enumeration type with a non-negative value."
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000767 if (ArraySize && !ArraySize->isTypeDependent()) {
Douglas Gregor4799d032010-06-30 00:20:43 +0000768
Sebastian Redl351bb782008-12-02 14:43:59 +0000769 QualType SizeType = ArraySize->getType();
Douglas Gregorf4ea7252010-06-29 23:17:37 +0000770
John McCalldadc5752010-08-24 06:29:42 +0000771 ExprResult ConvertedSize
John McCallb268a282010-08-23 23:25:46 +0000772 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
Douglas Gregor4799d032010-06-30 00:20:43 +0000773 PDiag(diag::err_array_size_not_integral),
774 PDiag(diag::err_array_size_incomplete_type)
775 << ArraySize->getSourceRange(),
776 PDiag(diag::err_array_size_explicit_conversion),
777 PDiag(diag::note_array_size_conversion),
778 PDiag(diag::err_array_size_ambiguous_conversion),
779 PDiag(diag::note_array_size_conversion),
780 PDiag(getLangOptions().CPlusPlus0x? 0
781 : diag::ext_array_size_conversion));
782 if (ConvertedSize.isInvalid())
783 return ExprError();
784
John McCallb268a282010-08-23 23:25:46 +0000785 ArraySize = ConvertedSize.take();
Douglas Gregor4799d032010-06-30 00:20:43 +0000786 SizeType = ArraySize->getType();
Douglas Gregor0bf31402010-10-08 23:50:27 +0000787 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +0000788 return ExprError();
789
Sebastian Redl351bb782008-12-02 14:43:59 +0000790 // Let's see if this is a constant < 0. If so, we reject it out of hand.
791 // We don't care about special rules, so we tell the machinery it's not
792 // evaluated - it gives us a result in more cases.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000793 if (!ArraySize->isValueDependent()) {
794 llvm::APSInt Value;
795 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
796 if (Value < llvm::APSInt(
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000797 llvm::APInt::getNullValue(Value.getBitWidth()),
798 Value.isUnsigned()))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000799 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
Douglas Gregorcaa1bf42010-08-18 00:39:00 +0000800 diag::err_typecheck_negative_array_size)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000801 << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +0000802
803 if (!AllocType->isDependentType()) {
804 unsigned ActiveSizeBits
805 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
806 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
807 Diag(ArraySize->getSourceRange().getBegin(),
808 diag::err_array_too_large)
809 << Value.toString(10)
810 << ArraySize->getSourceRange();
811 return ExprError();
812 }
813 }
Douglas Gregorf2753b32010-07-13 15:54:32 +0000814 } else if (TypeIdParens.isValid()) {
815 // Can't have dynamic array size when the type-id is in parentheses.
816 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
817 << ArraySize->getSourceRange()
818 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
819 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
820
821 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000822 }
Sebastian Redl351bb782008-12-02 14:43:59 +0000823 }
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000824
Eli Friedman06ed2a52009-10-20 08:27:19 +0000825 ImpCastExprToType(ArraySize, Context.getSizeType(),
John McCalle3027922010-08-25 11:45:40 +0000826 CK_IntegralCast);
Sebastian Redl351bb782008-12-02 14:43:59 +0000827 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000828
Sebastian Redlbd150f42008-11-21 19:14:01 +0000829 FunctionDecl *OperatorNew = 0;
830 FunctionDecl *OperatorDelete = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000831 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
832 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000833
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000834 if (!AllocType->isDependentType() &&
835 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
836 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000837 SourceRange(PlacementLParen, PlacementRParen),
838 UseGlobal, AllocType, ArraySize, PlaceArgs,
839 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000840 return ExprError();
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000841 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000842 if (OperatorNew) {
843 // Add default arguments, if any.
844 const FunctionProtoType *Proto =
845 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +0000846 VariadicCallType CallType =
847 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Anders Carlssonc144bc22010-05-03 02:07:56 +0000848
849 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
850 Proto, 1, PlaceArgs, NumPlaceArgs,
851 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000852 return ExprError();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000853
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000854 NumPlaceArgs = AllPlaceArgs.size();
855 if (NumPlaceArgs > 0)
856 PlaceArgs = &AllPlaceArgs[0];
857 }
858
Sebastian Redlbd150f42008-11-21 19:14:01 +0000859 bool Init = ConstructorLParen.isValid();
860 // --- Choosing a constructor ---
Sebastian Redlbd150f42008-11-21 19:14:01 +0000861 CXXConstructorDecl *Constructor = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000862 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
863 unsigned NumConsArgs = ConstructorArgs.size();
John McCall37ad5512010-08-23 06:44:23 +0000864 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmanfd8d4e12009-11-08 22:15:39 +0000865
Anders Carlssonc6bb0e12010-05-03 15:45:23 +0000866 // Array 'new' can't have any initializers.
Anders Carlssone6ae81b2010-05-16 16:24:20 +0000867 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlssonc6bb0e12010-05-03 15:45:23 +0000868 SourceRange InitRange(ConsArgs[0]->getLocStart(),
869 ConsArgs[NumConsArgs - 1]->getLocEnd());
870
871 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
872 return ExprError();
873 }
874
Douglas Gregor85dabae2009-12-16 01:38:02 +0000875 if (!AllocType->isDependentType() &&
876 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
877 // C++0x [expr.new]p15:
878 // A new-expression that creates an object of type T initializes that
879 // object as follows:
880 InitializationKind Kind
881 // - If the new-initializer is omitted, the object is default-
882 // initialized (8.5); if no initialization is performed,
883 // the object has indeterminate value
Douglas Gregor0744ef62010-09-07 21:49:58 +0000884 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
Douglas Gregor85dabae2009-12-16 01:38:02 +0000885 // - Otherwise, the new-initializer is interpreted according to the
886 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor0744ef62010-09-07 21:49:58 +0000887 : InitializationKind::CreateDirect(TypeRange.getBegin(),
Douglas Gregor85dabae2009-12-16 01:38:02 +0000888 ConstructorLParen,
889 ConstructorRParen);
890
Douglas Gregor85dabae2009-12-16 01:38:02 +0000891 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +0000892 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000893 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
John McCalldadc5752010-08-24 06:29:42 +0000894 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor85dabae2009-12-16 01:38:02 +0000895 move(ConstructorArgs));
896 if (FullInit.isInvalid())
897 return ExprError();
898
899 // FullInit is our initializer; walk through it to determine if it's a
900 // constructor call, which CXXNewExpr handles directly.
901 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
902 if (CXXBindTemporaryExpr *Binder
903 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
904 FullInitExpr = Binder->getSubExpr();
905 if (CXXConstructExpr *Construct
906 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
907 Constructor = Construct->getConstructor();
908 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
909 AEnd = Construct->arg_end();
910 A != AEnd; ++A)
John McCallc3007a22010-10-26 07:05:15 +0000911 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000912 } else {
913 // Take the converted initializer.
914 ConvertedConstructorArgs.push_back(FullInit.release());
915 }
916 } else {
917 // No initialization required.
918 }
919
920 // Take the converted arguments and use them for the new expression.
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000921 NumConsArgs = ConvertedConstructorArgs.size();
922 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000923 }
Douglas Gregor85dabae2009-12-16 01:38:02 +0000924
Douglas Gregor6642ca22010-02-26 05:06:18 +0000925 // Mark the new and delete operators as referenced.
926 if (OperatorNew)
927 MarkDeclarationReferenced(StartLoc, OperatorNew);
928 if (OperatorDelete)
929 MarkDeclarationReferenced(StartLoc, OperatorDelete);
930
Sebastian Redlbd150f42008-11-21 19:14:01 +0000931 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor4bbd1ac2009-10-17 21:40:42 +0000932
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000933 PlacementArgs.release();
934 ConstructorArgs.release();
Ted Kremenekabb1f912010-06-25 22:48:49 +0000935
Ted Kremenek9d6eb402010-02-11 22:51:03 +0000936 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregorf2753b32010-07-13 15:54:32 +0000937 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenek9d6eb402010-02-11 22:51:03 +0000938 ArraySize, Constructor, Init,
939 ConsArgs, NumConsArgs, OperatorDelete,
Douglas Gregor0744ef62010-09-07 21:49:58 +0000940 ResultType, AllocTypeInfo,
941 StartLoc,
Ted Kremenek9d6eb402010-02-11 22:51:03 +0000942 Init ? ConstructorRParen :
Chandler Carruth01718152010-10-25 08:47:36 +0000943 TypeRange.getEnd(),
944 ConstructorLParen, ConstructorRParen));
Sebastian Redlbd150f42008-11-21 19:14:01 +0000945}
946
947/// CheckAllocatedType - Checks that a type is suitable as the allocated type
948/// in a new-expression.
949/// dimension off and stores the size expression in ArraySize.
Douglas Gregord0fefba2009-05-21 00:00:09 +0000950bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000951 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +0000952 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
953 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +0000954 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000955 return Diag(Loc, diag::err_bad_new_type)
956 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000957 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000958 return Diag(Loc, diag::err_bad_new_type)
959 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000960 else if (!AllocType->isDependentType() &&
Douglas Gregord0fefba2009-05-21 00:00:09 +0000961 RequireCompleteType(Loc, AllocType,
Anders Carlssond624e162009-08-26 23:45:07 +0000962 PDiag(diag::err_new_incomplete_type)
963 << R))
Sebastian Redlbd150f42008-11-21 19:14:01 +0000964 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +0000965 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +0000966 diag::err_allocation_of_abstract_type))
967 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +0000968 else if (AllocType->isVariablyModifiedType())
969 return Diag(Loc, diag::err_variably_modified_new_type)
970 << AllocType;
971
Sebastian Redlbd150f42008-11-21 19:14:01 +0000972 return false;
973}
974
Douglas Gregor6642ca22010-02-26 05:06:18 +0000975/// \brief Determine whether the given function is a non-placement
976/// deallocation function.
977static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
978 if (FD->isInvalidDecl())
979 return false;
980
981 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
982 return Method->isUsualDeallocationFunction();
983
984 return ((FD->getOverloadedOperator() == OO_Delete ||
985 FD->getOverloadedOperator() == OO_Array_Delete) &&
986 FD->getNumParams() == 1);
987}
988
Sebastian Redlfaf68082008-12-03 20:26:15 +0000989/// FindAllocationFunctions - Finds the overloads of operator new and delete
990/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000991bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
992 bool UseGlobal, QualType AllocType,
993 bool IsArray, Expr **PlaceArgs,
994 unsigned NumPlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +0000995 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +0000996 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +0000997 // --- Choosing an allocation function ---
998 // C++ 5.3.4p8 - 14 & 18
999 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1000 // in the scope of the allocated class.
1001 // 2) If an array size is given, look for operator new[], else look for
1002 // operator new.
1003 // 3) The first argument is always size_t. Append the arguments from the
1004 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00001005
1006 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
1007 // We don't care about the actual value of this argument.
1008 // FIXME: Should the Sema create the expression and embed it in the syntax
1009 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001010 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Anders Carlssona471db02009-08-16 20:29:29 +00001011 Context.Target.getPointerWidth(0)),
1012 Context.getSizeType(),
1013 SourceLocation());
1014 AllocArgs[0] = &Size;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001015 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1016
Douglas Gregor6642ca22010-02-26 05:06:18 +00001017 // C++ [expr.new]p8:
1018 // If the allocated type is a non-array type, the allocation
1019 // function’s name is operator new and the deallocation function’s
1020 // name is operator delete. If the allocated type is an array
1021 // type, the allocation function’s name is operator new[] and the
1022 // deallocation function’s name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00001023 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1024 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001025 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1026 IsArray ? OO_Array_Delete : OO_Delete);
1027
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001028 QualType AllocElemType = Context.getBaseElementType(AllocType);
1029
1030 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +00001031 CXXRecordDecl *Record
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001032 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001033 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +00001034 AllocArgs.size(), Record, /*AllowMissing=*/true,
1035 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00001036 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001037 }
1038 if (!OperatorNew) {
1039 // Didn't find a member overload. Look for a global one.
1040 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +00001041 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001042 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +00001043 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1044 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00001045 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001046 }
1047
John McCall0f55a032010-04-20 02:18:25 +00001048 // We don't need an operator delete if we're running under
1049 // -fno-exceptions.
1050 if (!getLangOptions().Exceptions) {
1051 OperatorDelete = 0;
1052 return false;
1053 }
1054
Anders Carlsson6f9dabf2009-05-31 20:26:12 +00001055 // FindAllocationOverload can change the passed in arguments, so we need to
1056 // copy them back.
1057 if (NumPlaceArgs > 0)
1058 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001059
Douglas Gregor6642ca22010-02-26 05:06:18 +00001060 // C++ [expr.new]p19:
1061 //
1062 // If the new-expression begins with a unary :: operator, the
1063 // deallocation function’s name is looked up in the global
1064 // scope. Otherwise, if the allocated type is a class type T or an
1065 // array thereof, the deallocation function’s name is looked up in
1066 // the scope of T. If this lookup fails to find the name, or if
1067 // the allocated type is not a class type or array thereof, the
1068 // deallocation function’s name is looked up in the global scope.
1069 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001070 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001071 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001072 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00001073 LookupQualifiedName(FoundDelete, RD);
1074 }
John McCallfb6f5262010-03-18 08:19:33 +00001075 if (FoundDelete.isAmbiguous())
1076 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00001077
1078 if (FoundDelete.empty()) {
1079 DeclareGlobalNewDelete();
1080 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1081 }
1082
1083 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00001084
1085 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1086
John McCalld3be2c82010-09-14 21:34:24 +00001087 // Whether we're looking for a placement operator delete is dictated
1088 // by whether we selected a placement operator new, not by whether
1089 // we had explicit placement arguments. This matters for things like
1090 // struct A { void *operator new(size_t, int = 0); ... };
1091 // A *a = new A()
1092 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1093
1094 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001095 // C++ [expr.new]p20:
1096 // A declaration of a placement deallocation function matches the
1097 // declaration of a placement allocation function if it has the
1098 // same number of parameters and, after parameter transformations
1099 // (8.3.5), all parameter types except the first are
1100 // identical. [...]
1101 //
1102 // To perform this comparison, we compute the function type that
1103 // the deallocation function should have, and use that type both
1104 // for template argument deduction and for comparison purposes.
John McCalldb40c7f2010-12-14 08:05:40 +00001105 //
1106 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6642ca22010-02-26 05:06:18 +00001107 QualType ExpectedFunctionType;
1108 {
1109 const FunctionProtoType *Proto
1110 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00001111
Douglas Gregor6642ca22010-02-26 05:06:18 +00001112 llvm::SmallVector<QualType, 4> ArgTypes;
1113 ArgTypes.push_back(Context.VoidPtrTy);
1114 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1115 ArgTypes.push_back(Proto->getArgType(I));
1116
John McCalldb40c7f2010-12-14 08:05:40 +00001117 FunctionProtoType::ExtProtoInfo EPI;
1118 EPI.Variadic = Proto->isVariadic();
1119
Douglas Gregor6642ca22010-02-26 05:06:18 +00001120 ExpectedFunctionType
1121 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalldb40c7f2010-12-14 08:05:40 +00001122 ArgTypes.size(), EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001123 }
1124
1125 for (LookupResult::iterator D = FoundDelete.begin(),
1126 DEnd = FoundDelete.end();
1127 D != DEnd; ++D) {
1128 FunctionDecl *Fn = 0;
1129 if (FunctionTemplateDecl *FnTmpl
1130 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1131 // Perform template argument deduction to try to match the
1132 // expected function type.
1133 TemplateDeductionInfo Info(Context, StartLoc);
1134 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1135 continue;
1136 } else
1137 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1138
1139 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00001140 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001141 }
1142 } else {
1143 // C++ [expr.new]p20:
1144 // [...] Any non-placement deallocation function matches a
1145 // non-placement allocation function. [...]
1146 for (LookupResult::iterator D = FoundDelete.begin(),
1147 DEnd = FoundDelete.end();
1148 D != DEnd; ++D) {
1149 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1150 if (isNonPlacementDeallocationFunction(Fn))
John McCalla0296f72010-03-19 07:35:19 +00001151 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001152 }
1153 }
1154
1155 // C++ [expr.new]p20:
1156 // [...] If the lookup finds a single matching deallocation
1157 // function, that function will be called; otherwise, no
1158 // deallocation function will be called.
1159 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00001160 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00001161
1162 // C++0x [expr.new]p20:
1163 // If the lookup finds the two-parameter form of a usual
1164 // deallocation function (3.7.4.2) and that function, considered
1165 // as a placement deallocation function, would have been
1166 // selected as a match for the allocation function, the program
1167 // is ill-formed.
1168 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1169 isNonPlacementDeallocationFunction(OperatorDelete)) {
1170 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1171 << SourceRange(PlaceArgs[0]->getLocStart(),
1172 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1173 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1174 << DeleteName;
John McCallfb6f5262010-03-18 08:19:33 +00001175 } else {
1176 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCalla0296f72010-03-19 07:35:19 +00001177 Matches[0].first);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001178 }
1179 }
1180
Sebastian Redlfaf68082008-12-03 20:26:15 +00001181 return false;
1182}
1183
Sebastian Redl33a31012008-12-04 22:20:51 +00001184/// FindAllocationOverload - Find an fitting overload for the allocation
1185/// function in the specified scope.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001186bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1187 DeclarationName Name, Expr** Args,
1188 unsigned NumArgs, DeclContext *Ctx,
Mike Stump11289f42009-09-09 15:08:12 +00001189 bool AllowMissing, FunctionDecl *&Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001190 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1191 LookupQualifiedName(R, Ctx);
John McCall9f3059a2009-10-09 21:13:30 +00001192 if (R.empty()) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001193 if (AllowMissing)
1194 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +00001195 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001196 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +00001197 }
1198
John McCallfb6f5262010-03-18 08:19:33 +00001199 if (R.isAmbiguous())
1200 return true;
1201
1202 R.suppressDiagnostics();
John McCall9f3059a2009-10-09 21:13:30 +00001203
John McCallbc077cf2010-02-08 23:07:23 +00001204 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor80a6cc52009-09-30 00:03:47 +00001205 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1206 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor55297ac2008-12-23 00:26:44 +00001207 // Even member operator new/delete are implicitly treated as
1208 // static, so don't use AddMemberCandidate.
John McCalla0296f72010-03-19 07:35:19 +00001209 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth93538422010-02-03 11:02:14 +00001210
John McCalla0296f72010-03-19 07:35:19 +00001211 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1212 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth93538422010-02-03 11:02:14 +00001213 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1214 Candidates,
1215 /*SuppressUserConversions=*/false);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001216 continue;
Chandler Carruth93538422010-02-03 11:02:14 +00001217 }
1218
John McCalla0296f72010-03-19 07:35:19 +00001219 FunctionDecl *Fn = cast<FunctionDecl>(D);
1220 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth93538422010-02-03 11:02:14 +00001221 /*SuppressUserConversions=*/false);
Sebastian Redl33a31012008-12-04 22:20:51 +00001222 }
1223
1224 // Do the resolution.
1225 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00001226 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001227 case OR_Success: {
1228 // Got one!
1229 FunctionDecl *FnDecl = Best->Function;
1230 // The first argument is size_t, and the first parameter must be size_t,
1231 // too. This is checked on declaration and can be assumed. (It can't be
1232 // asserted on, though, since invalid decls are left in there.)
John McCallfb6f5262010-03-18 08:19:33 +00001233 // Watch out for variadic allocator function.
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001234 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1235 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
John McCalldadc5752010-08-24 06:29:42 +00001236 ExprResult Result
Douglas Gregor34147272010-03-26 20:35:59 +00001237 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001238 Context,
Douglas Gregor34147272010-03-26 20:35:59 +00001239 FnDecl->getParamDecl(i)),
1240 SourceLocation(),
John McCallc3007a22010-10-26 07:05:15 +00001241 Owned(Args[i]));
Douglas Gregor34147272010-03-26 20:35:59 +00001242 if (Result.isInvalid())
Sebastian Redl33a31012008-12-04 22:20:51 +00001243 return true;
Douglas Gregor34147272010-03-26 20:35:59 +00001244
1245 Args[i] = Result.takeAs<Expr>();
Sebastian Redl33a31012008-12-04 22:20:51 +00001246 }
1247 Operator = FnDecl;
John McCalla0296f72010-03-19 07:35:19 +00001248 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl33a31012008-12-04 22:20:51 +00001249 return false;
1250 }
1251
1252 case OR_No_Viable_Function:
Sebastian Redl33a31012008-12-04 22:20:51 +00001253 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001254 << Name << Range;
John McCall5c32be02010-08-24 20:38:10 +00001255 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001256 return true;
1257
1258 case OR_Ambiguous:
Sebastian Redl33a31012008-12-04 22:20:51 +00001259 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001260 << Name << Range;
John McCall5c32be02010-08-24 20:38:10 +00001261 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001262 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001263
1264 case OR_Deleted:
1265 Diag(StartLoc, diag::err_ovl_deleted_call)
1266 << Best->Function->isDeleted()
1267 << Name << Range;
John McCall5c32be02010-08-24 20:38:10 +00001268 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001269 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +00001270 }
1271 assert(false && "Unreachable, bad result from BestViableFunction");
1272 return true;
1273}
1274
1275
Sebastian Redlfaf68082008-12-03 20:26:15 +00001276/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1277/// delete. These are:
1278/// @code
1279/// void* operator new(std::size_t) throw(std::bad_alloc);
1280/// void* operator new[](std::size_t) throw(std::bad_alloc);
1281/// void operator delete(void *) throw();
1282/// void operator delete[](void *) throw();
1283/// @endcode
1284/// Note that the placement and nothrow forms of new are *not* implicitly
1285/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00001286void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001287 if (GlobalNewDeleteDeclared)
1288 return;
Douglas Gregor87f54062009-09-15 22:30:29 +00001289
1290 // C++ [basic.std.dynamic]p2:
1291 // [...] The following allocation and deallocation functions (18.4) are
1292 // implicitly declared in global scope in each translation unit of a
1293 // program
1294 //
1295 // void* operator new(std::size_t) throw(std::bad_alloc);
1296 // void* operator new[](std::size_t) throw(std::bad_alloc);
1297 // void operator delete(void*) throw();
1298 // void operator delete[](void*) throw();
1299 //
1300 // These implicit declarations introduce only the function names operator
1301 // new, operator new[], operator delete, operator delete[].
1302 //
1303 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1304 // "std" or "bad_alloc" as necessary to form the exception specification.
1305 // However, we do not make these implicit declarations visible to name
1306 // lookup.
Douglas Gregor87f54062009-09-15 22:30:29 +00001307 if (!StdBadAlloc) {
1308 // The "std::bad_alloc" class has not yet been declared, so build it
1309 // implicitly.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001310 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00001311 getOrCreateStdNamespace(),
Douglas Gregor87f54062009-09-15 22:30:29 +00001312 SourceLocation(),
1313 &PP.getIdentifierTable().get("bad_alloc"),
1314 SourceLocation(), 0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001315 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00001316 }
1317
Sebastian Redlfaf68082008-12-03 20:26:15 +00001318 GlobalNewDeleteDeclared = true;
1319
1320 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1321 QualType SizeT = Context.getSizeType();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001322 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001323
Sebastian Redlfaf68082008-12-03 20:26:15 +00001324 DeclareGlobalAllocationFunction(
1325 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001326 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001327 DeclareGlobalAllocationFunction(
1328 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001329 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001330 DeclareGlobalAllocationFunction(
1331 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1332 Context.VoidTy, VoidPtr);
1333 DeclareGlobalAllocationFunction(
1334 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1335 Context.VoidTy, VoidPtr);
1336}
1337
1338/// DeclareGlobalAllocationFunction - Declares a single implicit global
1339/// allocation function if it doesn't already exist.
1340void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopes13c88c72009-12-16 16:59:22 +00001341 QualType Return, QualType Argument,
1342 bool AddMallocAttr) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001343 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1344
1345 // Check if this function is already declared.
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001346 {
Douglas Gregor17eb26b2008-12-23 22:05:29 +00001347 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001348 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001349 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth93538422010-02-03 11:02:14 +00001350 // Only look at non-template functions, as it is the predefined,
1351 // non-templated allocation function we are trying to declare here.
1352 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1353 QualType InitialParamType =
Douglas Gregor684d7bd2009-12-22 23:42:49 +00001354 Context.getCanonicalType(
Chandler Carruth93538422010-02-03 11:02:14 +00001355 Func->getParamDecl(0)->getType().getUnqualifiedType());
1356 // FIXME: Do we need to check for default arguments here?
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00001357 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1358 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001359 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth93538422010-02-03 11:02:14 +00001360 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00001361 }
Chandler Carruth93538422010-02-03 11:02:14 +00001362 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00001363 }
1364 }
1365
Douglas Gregor87f54062009-09-15 22:30:29 +00001366 QualType BadAllocType;
1367 bool HasBadAllocExceptionSpec
1368 = (Name.getCXXOverloadedOperator() == OO_New ||
1369 Name.getCXXOverloadedOperator() == OO_Array_New);
1370 if (HasBadAllocExceptionSpec) {
1371 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001372 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +00001373 }
John McCalldb40c7f2010-12-14 08:05:40 +00001374
1375 FunctionProtoType::ExtProtoInfo EPI;
1376 EPI.HasExceptionSpec = true;
1377 if (HasBadAllocExceptionSpec) {
1378 EPI.NumExceptions = 1;
1379 EPI.Exceptions = &BadAllocType;
1380 }
Douglas Gregor87f54062009-09-15 22:30:29 +00001381
John McCalldb40c7f2010-12-14 08:05:40 +00001382 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001383 FunctionDecl *Alloc =
1384 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCall8e7d6562010-08-26 03:08:43 +00001385 FnType, /*TInfo=*/0, SC_None,
1386 SC_None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001387 Alloc->setImplicit();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001388
1389 if (AddMallocAttr)
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001390 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Nuno Lopes13c88c72009-12-16 16:59:22 +00001391
Sebastian Redlfaf68082008-12-03 20:26:15 +00001392 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCallbcd03502009-12-07 02:54:59 +00001393 0, Argument, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00001394 SC_None,
1395 SC_None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00001396 Alloc->setParams(&Param, 1);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001397
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001398 // FIXME: Also add this declaration to the IdentifierResolver, but
1399 // make sure it is at the end of the chain to coincide with the
1400 // global scope.
John McCallcc14d1f2010-08-24 08:50:51 +00001401 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001402}
1403
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001404bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1405 DeclarationName Name,
Anders Carlssonf98849e2009-12-02 17:15:43 +00001406 FunctionDecl* &Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001407 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001408 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00001409 LookupQualifiedName(Found, RD);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001410
John McCall27b18f82009-11-17 02:14:36 +00001411 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001412 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001413
Chandler Carruthb6f99172010-06-28 00:30:51 +00001414 Found.suppressDiagnostics();
1415
John McCall66a87592010-08-04 00:31:26 +00001416 llvm::SmallVector<DeclAccessPair,4> Matches;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001417 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1418 F != FEnd; ++F) {
Chandler Carruth9b418232010-08-08 07:04:00 +00001419 NamedDecl *ND = (*F)->getUnderlyingDecl();
1420
1421 // Ignore template operator delete members from the check for a usual
1422 // deallocation function.
1423 if (isa<FunctionTemplateDecl>(ND))
1424 continue;
1425
1426 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall66a87592010-08-04 00:31:26 +00001427 Matches.push_back(F.getPair());
1428 }
1429
1430 // There's exactly one suitable operator; pick it.
1431 if (Matches.size() == 1) {
1432 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1433 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1434 Matches[0]);
1435 return false;
1436
1437 // We found multiple suitable operators; complain about the ambiguity.
1438 } else if (!Matches.empty()) {
1439 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1440 << Name << RD;
1441
1442 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1443 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1444 Diag((*F)->getUnderlyingDecl()->getLocation(),
1445 diag::note_member_declared_here) << Name;
1446 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001447 }
1448
1449 // We did find operator delete/operator delete[] declarations, but
1450 // none of them were suitable.
1451 if (!Found.empty()) {
1452 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1453 << Name << RD;
1454
1455 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
John McCall66a87592010-08-04 00:31:26 +00001456 F != FEnd; ++F)
1457 Diag((*F)->getUnderlyingDecl()->getLocation(),
1458 diag::note_member_declared_here) << Name;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001459
1460 return true;
1461 }
1462
1463 // Look for a global declaration.
1464 DeclareGlobalNewDelete();
1465 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1466
1467 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1468 Expr* DeallocArgs[1];
1469 DeallocArgs[0] = &Null;
1470 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1471 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1472 Operator))
1473 return true;
1474
1475 assert(Operator && "Did not find a deallocation function!");
1476 return false;
1477}
1478
Sebastian Redlbd150f42008-11-21 19:14:01 +00001479/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1480/// @code ::delete ptr; @endcode
1481/// or
1482/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00001483ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001484Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John McCallb268a282010-08-23 23:25:46 +00001485 bool ArrayForm, Expr *Ex) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001486 // C++ [expr.delete]p1:
1487 // The operand shall have a pointer type, or a class type having a single
1488 // conversion function to a pointer type. The result has type void.
1489 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00001490 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1491
Anders Carlssona471db02009-08-16 20:29:29 +00001492 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00001493 bool ArrayFormAsWritten = ArrayForm;
Mike Stump11289f42009-09-09 15:08:12 +00001494
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001495 if (!Ex->isTypeDependent()) {
1496 QualType Type = Ex->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001497
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001498 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregorf65f4902010-07-29 14:44:35 +00001499 if (RequireCompleteType(StartLoc, Type,
1500 PDiag(diag::err_delete_incomplete_class_type)))
1501 return ExprError();
1502
John McCallda4458e2010-03-31 01:36:47 +00001503 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1504
Fariborz Jahanianb54ccb22009-09-11 21:44:33 +00001505 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCallda4458e2010-03-31 01:36:47 +00001506 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001507 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001508 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00001509 NamedDecl *D = I.getDecl();
1510 if (isa<UsingShadowDecl>(D))
1511 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1512
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001513 // Skip over templated conversion functions; they aren't considered.
John McCallda4458e2010-03-31 01:36:47 +00001514 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001515 continue;
1516
John McCallda4458e2010-03-31 01:36:47 +00001517 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001518
1519 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1520 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00001521 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001522 ObjectPtrConversions.push_back(Conv);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001523 }
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001524 if (ObjectPtrConversions.size() == 1) {
1525 // We have a single conversion to a pointer-to-object type. Perform
1526 // that conversion.
John McCallda4458e2010-03-31 01:36:47 +00001527 // TODO: don't redo the conversion calculation.
John McCallda4458e2010-03-31 01:36:47 +00001528 if (!PerformImplicitConversion(Ex,
1529 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001530 AA_Converting)) {
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001531 Type = Ex->getType();
1532 }
1533 }
1534 else if (ObjectPtrConversions.size() > 1) {
1535 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1536 << Type << Ex->getSourceRange();
John McCallda4458e2010-03-31 01:36:47 +00001537 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1538 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001539 return ExprError();
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001540 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001541 }
1542
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001543 if (!Type->isPointerType())
1544 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1545 << Type << Ex->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001546
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001547 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregorbb3348e2010-05-24 17:01:56 +00001548 if (Pointee->isVoidType() && !isSFINAEContext()) {
1549 // The C++ standard bans deleting a pointer to a non-object type, which
1550 // effectively bans deletion of "void*". However, most compilers support
1551 // this, so we treat it as a warning unless we're in a SFINAE context.
1552 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1553 << Type << Ex->getSourceRange();
1554 } else if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001555 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1556 << Type << Ex->getSourceRange());
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001557 else if (!Pointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00001558 RequireCompleteType(StartLoc, Pointee,
Anders Carlssond624e162009-08-26 23:45:07 +00001559 PDiag(diag::warn_delete_incomplete)
1560 << Ex->getSourceRange()))
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001561 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001562
Douglas Gregor98496dc2009-09-29 21:38:53 +00001563 // C++ [expr.delete]p2:
1564 // [Note: a pointer to a const type can be the operand of a
1565 // delete-expression; it is not necessary to cast away the constness
1566 // (5.2.11) of the pointer expression before it is used as the operand
1567 // of the delete-expression. ]
1568 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
John McCalle3027922010-08-25 11:45:40 +00001569 CK_NoOp);
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00001570
1571 if (Pointee->isArrayType() && !ArrayForm) {
1572 Diag(StartLoc, diag::warn_delete_array_type)
1573 << Type << Ex->getSourceRange()
1574 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1575 ArrayForm = true;
1576 }
1577
Anders Carlssona471db02009-08-16 20:29:29 +00001578 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1579 ArrayForm ? OO_Array_Delete : OO_Delete);
1580
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001581 QualType PointeeElem = Context.getBaseElementType(Pointee);
1582 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001583 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1584
1585 if (!UseGlobal &&
1586 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00001587 return ExprError();
Anders Carlsson654e5c72009-11-14 03:17:38 +00001588
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001589 if (!RD->hasTrivialDestructor())
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001590 if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
Mike Stump11289f42009-09-09 15:08:12 +00001591 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001592 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001593 DiagnoseUseOfDecl(Dtor, StartLoc);
1594 }
Anders Carlssona471db02009-08-16 20:29:29 +00001595 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001596
Anders Carlssona471db02009-08-16 20:29:29 +00001597 if (!OperatorDelete) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001598 // Look for a global declaration.
Anders Carlssona471db02009-08-16 20:29:29 +00001599 DeclareGlobalNewDelete();
1600 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001601 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001602 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssona471db02009-08-16 20:29:29 +00001603 OperatorDelete))
1604 return ExprError();
1605 }
Mike Stump11289f42009-09-09 15:08:12 +00001606
John McCall0f55a032010-04-20 02:18:25 +00001607 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1608
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001609 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redlbd150f42008-11-21 19:14:01 +00001610 }
1611
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001612 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00001613 ArrayFormAsWritten, OperatorDelete,
1614 Ex, StartLoc));
Sebastian Redlbd150f42008-11-21 19:14:01 +00001615}
1616
Douglas Gregor633caca2009-11-23 23:44:04 +00001617/// \brief Check the use of the given variable as a C++ condition in an if,
1618/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00001619ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00001620 SourceLocation StmtLoc,
1621 bool ConvertToBoolean) {
Douglas Gregor633caca2009-11-23 23:44:04 +00001622 QualType T = ConditionVar->getType();
1623
1624 // C++ [stmt.select]p2:
1625 // The declarator shall not specify a function or an array.
1626 if (T->isFunctionType())
1627 return ExprError(Diag(ConditionVar->getLocation(),
1628 diag::err_invalid_use_of_function_type)
1629 << ConditionVar->getSourceRange());
1630 else if (T->isArrayType())
1631 return ExprError(Diag(ConditionVar->getLocation(),
1632 diag::err_invalid_use_of_array_type)
1633 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00001634
Douglas Gregore60e41a2010-05-06 17:25:47 +00001635 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1636 ConditionVar->getLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00001637 ConditionVar->getType().getNonReferenceType(),
John McCall4bc41ae2010-11-18 19:01:18 +00001638 VK_LValue);
Douglas Gregorb412e172010-07-25 18:17:45 +00001639 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
Douglas Gregore60e41a2010-05-06 17:25:47 +00001640 return ExprError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00001641
1642 return Owned(Condition);
Douglas Gregor633caca2009-11-23 23:44:04 +00001643}
1644
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001645/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1646bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1647 // C++ 6.4p4:
1648 // The value of a condition that is an initialized declaration in a statement
1649 // other than a switch statement is the value of the declared variable
1650 // implicitly converted to type bool. If that conversion is ill-formed, the
1651 // program is ill-formed.
1652 // The value of a condition that is an expression is the value of the
1653 // expression, implicitly converted to bool.
1654 //
Douglas Gregor5fb53972009-01-14 15:45:31 +00001655 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001656}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001657
1658/// Helper function to determine whether this is the (deprecated) C++
1659/// conversion from a string literal to a pointer to non-const char or
1660/// non-const wchar_t (for narrow and wide string literals,
1661/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00001662bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001663Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1664 // Look inside the implicit cast, if it exists.
1665 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1666 From = Cast->getSubExpr();
1667
1668 // A string literal (2.13.4) that is not a wide string literal can
1669 // be converted to an rvalue of type "pointer to char"; a wide
1670 // string literal can be converted to an rvalue of type "pointer
1671 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00001672 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001673 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001674 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00001675 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001676 // This conversion is considered only when there is an
1677 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall8ccfcb52009-09-24 19:53:00 +00001678 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001679 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1680 (!StrLit->isWide() &&
1681 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1682 ToPointeeType->getKind() == BuiltinType::Char_S))))
1683 return true;
1684 }
1685
1686 return false;
1687}
Douglas Gregor39c16d42008-10-24 04:54:22 +00001688
John McCalldadc5752010-08-24 06:29:42 +00001689static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00001690 SourceLocation CastLoc,
1691 QualType Ty,
1692 CastKind Kind,
1693 CXXMethodDecl *Method,
1694 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00001695 switch (Kind) {
1696 default: assert(0 && "Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00001697 case CK_ConstructorConversion: {
John McCall37ad5512010-08-23 06:44:23 +00001698 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregora4253922010-04-16 22:17:36 +00001699
1700 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
John McCallfaf5fb42010-08-26 23:41:50 +00001701 MultiExprArg(&From, 1),
Douglas Gregora4253922010-04-16 22:17:36 +00001702 CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00001703 return ExprError();
Douglas Gregora4253922010-04-16 22:17:36 +00001704
John McCalldadc5752010-08-24 06:29:42 +00001705 ExprResult Result =
Douglas Gregora4253922010-04-16 22:17:36 +00001706 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
John McCallbfd822c2010-08-24 07:32:53 +00001707 move_arg(ConstructorArgs),
Chandler Carruth01718152010-10-25 08:47:36 +00001708 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete,
1709 SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00001710 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00001711 return ExprError();
Douglas Gregora4253922010-04-16 22:17:36 +00001712
1713 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1714 }
1715
John McCalle3027922010-08-25 11:45:40 +00001716 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00001717 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1718
1719 // Create an implicit call expr that calls it.
1720 // FIXME: pass the FoundDecl for the user-defined conversion here
1721 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1722 return S.MaybeBindToTemporary(CE);
1723 }
1724 }
1725}
1726
Douglas Gregor5fb53972009-01-14 15:45:31 +00001727/// PerformImplicitConversion - Perform an implicit conversion of the
1728/// expression From to the type ToType using the pre-computed implicit
1729/// conversion sequence ICS. Returns true if there was an error, false
1730/// otherwise. The expression From is replaced with the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001731/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001732/// used in the error message.
1733bool
1734Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1735 const ImplicitConversionSequence &ICS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001736 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall0d1da222010-01-12 00:44:57 +00001737 switch (ICS.getKind()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001738 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001739 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redl7c353682009-11-14 21:15:49 +00001740 IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001741 return true;
1742 break;
1743
Anders Carlsson110b07b2009-09-15 06:28:28 +00001744 case ImplicitConversionSequence::UserDefinedConversion: {
1745
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001746 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00001747 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001748 QualType BeforeToType;
1749 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00001750 CastKind = CK_UserDefinedConversion;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001751
1752 // If the user-defined conversion is specified by a conversion function,
1753 // the initial standard conversion sequence converts the source type to
1754 // the implicit object parameter of the conversion function.
1755 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00001756 } else {
1757 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00001758 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001759 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00001760 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001761 // If the user-defined conversion is specified by a constructor, the
1762 // initial standard conversion sequence converts the source type to the
1763 // type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00001764 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1765 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001766 }
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00001767 // Watch out for elipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00001768 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001769 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001770 ICS.UserDefined.Before, AA_Converting,
Sebastian Redl7c353682009-11-14 21:15:49 +00001771 IgnoreBaseAccess))
Fariborz Jahanian55824512009-11-06 00:23:08 +00001772 return true;
1773 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001774
John McCalldadc5752010-08-24 06:29:42 +00001775 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00001776 = BuildCXXCastArgument(*this,
1777 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00001778 ToType.getNonReferenceType(),
1779 CastKind, cast<CXXMethodDecl>(FD),
John McCallb268a282010-08-23 23:25:46 +00001780 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00001781
1782 if (CastArg.isInvalid())
1783 return true;
Eli Friedmane96f1d32009-11-27 04:41:50 +00001784
1785 From = CastArg.takeAs<Expr>();
1786
Eli Friedmane96f1d32009-11-27 04:41:50 +00001787 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001788 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001789 }
John McCall0d1da222010-01-12 00:44:57 +00001790
1791 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00001792 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00001793 PDiag(diag::err_typecheck_ambiguous_condition)
1794 << From->getSourceRange());
1795 return true;
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001796
Douglas Gregor39c16d42008-10-24 04:54:22 +00001797 case ImplicitConversionSequence::EllipsisConversion:
1798 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001799 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001800
1801 case ImplicitConversionSequence::BadConversion:
1802 return true;
1803 }
1804
1805 // Everything went well.
1806 return false;
1807}
1808
1809/// PerformImplicitConversion - Perform an implicit conversion of the
1810/// expression From to the type ToType by following the standard
1811/// conversion sequence SCS. Returns true if there was an error, false
1812/// otherwise. The expression From is replaced with the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00001813/// expression. Flavor is the context in which we're performing this
1814/// conversion, for use in error messages.
Mike Stump11289f42009-09-09 15:08:12 +00001815bool
Douglas Gregor39c16d42008-10-24 04:54:22 +00001816Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001817 const StandardConversionSequence& SCS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001818 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001819 // Overall FIXME: we are recomputing too many types here and doing far too
1820 // much extra work. What this means is that we need to keep track of more
1821 // information that is computed when we try the implicit conversion initially,
1822 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001823 QualType FromType = From->getType();
1824
Douglas Gregor2fe98832008-11-03 19:09:14 +00001825 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00001826 // FIXME: When can ToType be a reference type?
1827 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001828 if (SCS.Second == ICK_Derived_To_Base) {
John McCall37ad5512010-08-23 06:44:23 +00001829 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001830 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCall37ad5512010-08-23 06:44:23 +00001831 MultiExprArg(*this, &From, 1),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001832 /*FIXME:ConstructLoc*/SourceLocation(),
1833 ConstructorArgs))
1834 return true;
John McCalldadc5752010-08-24 06:29:42 +00001835 ExprResult FromResult =
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001836 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1837 ToType, SCS.CopyConstructor,
John McCallbfd822c2010-08-24 07:32:53 +00001838 move_arg(ConstructorArgs),
1839 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00001840 CXXConstructExpr::CK_Complete,
1841 SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001842 if (FromResult.isInvalid())
1843 return true;
1844 From = FromResult.takeAs<Expr>();
1845 return false;
1846 }
John McCalldadc5752010-08-24 06:29:42 +00001847 ExprResult FromResult =
Mike Stump11289f42009-09-09 15:08:12 +00001848 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1849 ToType, SCS.CopyConstructor,
John McCallbfd822c2010-08-24 07:32:53 +00001850 MultiExprArg(*this, &From, 1),
1851 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00001852 CXXConstructExpr::CK_Complete,
1853 SourceRange());
Mike Stump11289f42009-09-09 15:08:12 +00001854
Anders Carlsson6eb55572009-08-25 05:12:04 +00001855 if (FromResult.isInvalid())
1856 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001857
Anders Carlsson6eb55572009-08-25 05:12:04 +00001858 From = FromResult.takeAs<Expr>();
Douglas Gregor2fe98832008-11-03 19:09:14 +00001859 return false;
1860 }
1861
Douglas Gregor980fb162010-04-29 18:24:40 +00001862 // Resolve overloaded function references.
1863 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1864 DeclAccessPair Found;
1865 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1866 true, Found);
1867 if (!Fn)
1868 return true;
1869
1870 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1871 return true;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001872
Douglas Gregor980fb162010-04-29 18:24:40 +00001873 From = FixOverloadedFunctionReference(From, Found, Fn);
1874 FromType = From->getType();
1875 }
1876
Douglas Gregor39c16d42008-10-24 04:54:22 +00001877 // Perform the first implicit conversion.
1878 switch (SCS.First) {
1879 case ICK_Identity:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001880 // Nothing to do.
1881 break;
1882
John McCall34376a62010-12-04 03:47:34 +00001883 case ICK_Lvalue_To_Rvalue:
1884 // Should this get its own ICK?
1885 if (From->getObjectKind() == OK_ObjCProperty) {
1886 ConvertPropertyForRValue(From);
John McCalled75c092010-12-07 22:54:16 +00001887 if (!From->isGLValue()) break;
John McCall34376a62010-12-04 03:47:34 +00001888 }
1889
1890 FromType = FromType.getUnqualifiedType();
1891 From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
1892 From, 0, VK_RValue);
1893 break;
1894
Douglas Gregor39c16d42008-10-24 04:54:22 +00001895 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00001896 FromType = Context.getArrayDecayedType(FromType);
John McCalle3027922010-08-25 11:45:40 +00001897 ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001898 break;
1899
1900 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001901 FromType = Context.getPointerType(FromType);
John McCalle3027922010-08-25 11:45:40 +00001902 ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001903 break;
1904
1905 default:
1906 assert(false && "Improper first standard conversion");
1907 break;
1908 }
1909
1910 // Perform the second implicit conversion
1911 switch (SCS.Second) {
1912 case ICK_Identity:
Sebastian Redl5d431642009-10-10 12:04:10 +00001913 // If both sides are functions (or pointers/references to them), there could
1914 // be incompatible exception declarations.
1915 if (CheckExceptionSpecCompatibility(From, ToType))
1916 return true;
1917 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001918 break;
1919
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001920 case ICK_NoReturn_Adjustment:
1921 // If both sides are functions (or pointers/references to them), there could
1922 // be incompatible exception declarations.
1923 if (CheckExceptionSpecCompatibility(From, ToType))
1924 return true;
1925
John McCall4f5019e2010-12-19 02:44:49 +00001926 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001927 break;
1928
Douglas Gregor39c16d42008-10-24 04:54:22 +00001929 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001930 case ICK_Integral_Conversion:
John McCalle3027922010-08-25 11:45:40 +00001931 ImpCastExprToType(From, ToType, CK_IntegralCast);
Eli Friedman06ed2a52009-10-20 08:27:19 +00001932 break;
1933
1934 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001935 case ICK_Floating_Conversion:
John McCalle3027922010-08-25 11:45:40 +00001936 ImpCastExprToType(From, ToType, CK_FloatingCast);
Eli Friedman06ed2a52009-10-20 08:27:19 +00001937 break;
1938
1939 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00001940 case ICK_Complex_Conversion: {
1941 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
1942 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
1943 CastKind CK;
1944 if (FromEl->isRealFloatingType()) {
1945 if (ToEl->isRealFloatingType())
1946 CK = CK_FloatingComplexCast;
1947 else
1948 CK = CK_FloatingComplexToIntegralComplex;
1949 } else if (ToEl->isRealFloatingType()) {
1950 CK = CK_IntegralComplexToFloatingComplex;
1951 } else {
1952 CK = CK_IntegralComplexCast;
1953 }
1954 ImpCastExprToType(From, ToType, CK);
Eli Friedman06ed2a52009-10-20 08:27:19 +00001955 break;
John McCall8cb679e2010-11-15 09:13:47 +00001956 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00001957
Douglas Gregor39c16d42008-10-24 04:54:22 +00001958 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00001959 if (ToType->isRealFloatingType())
John McCalle3027922010-08-25 11:45:40 +00001960 ImpCastExprToType(From, ToType, CK_IntegralToFloating);
Eli Friedman06ed2a52009-10-20 08:27:19 +00001961 else
John McCalle3027922010-08-25 11:45:40 +00001962 ImpCastExprToType(From, ToType, CK_FloatingToIntegral);
Eli Friedman06ed2a52009-10-20 08:27:19 +00001963 break;
1964
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001965 case ICK_Compatible_Conversion:
John McCalle3027922010-08-25 11:45:40 +00001966 ImpCastExprToType(From, ToType, CK_NoOp);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001967 break;
1968
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001969 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00001970 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001971 // Diagnose incompatible Objective-C conversions
Mike Stump11289f42009-09-09 15:08:12 +00001972 Diag(From->getSourceRange().getBegin(),
Douglas Gregor47d3f272008-12-19 17:40:08 +00001973 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001974 << From->getType() << ToType << Action
Douglas Gregor47d3f272008-12-19 17:40:08 +00001975 << From->getSourceRange();
1976 }
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001977
John McCall8cb679e2010-11-15 09:13:47 +00001978 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00001979 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00001980 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001981 return true;
John McCall2536c6d2010-08-25 10:28:54 +00001982 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001983 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001984 }
1985
1986 case ICK_Pointer_Member: {
John McCall8cb679e2010-11-15 09:13:47 +00001987 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00001988 CXXCastPath BasePath;
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001989 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1990 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001991 return true;
Sebastian Redl5d431642009-10-10 12:04:10 +00001992 if (CheckExceptionSpecCompatibility(From, ToType))
1993 return true;
John McCall2536c6d2010-08-25 10:28:54 +00001994 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001995 break;
1996 }
Anders Carlsson7fa434c2009-11-23 20:04:44 +00001997 case ICK_Boolean_Conversion: {
John McCall8cb679e2010-11-15 09:13:47 +00001998 CastKind Kind = CK_Invalid;
1999 switch (FromType->getScalarTypeKind()) {
2000 case Type::STK_Pointer: Kind = CK_PointerToBoolean; break;
2001 case Type::STK_MemberPointer: Kind = CK_MemberPointerToBoolean; break;
2002 case Type::STK_Bool: llvm_unreachable("bool -> bool conversion?");
2003 case Type::STK_Integral: Kind = CK_IntegralToBoolean; break;
2004 case Type::STK_Floating: Kind = CK_FloatingToBoolean; break;
2005 case Type::STK_IntegralComplex: Kind = CK_IntegralComplexToBoolean; break;
2006 case Type::STK_FloatingComplex: Kind = CK_FloatingComplexToBoolean; break;
2007 }
Anders Carlsson7fa434c2009-11-23 20:04:44 +00002008
2009 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor39c16d42008-10-24 04:54:22 +00002010 break;
Anders Carlsson7fa434c2009-11-23 20:04:44 +00002011 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002012
Douglas Gregor88d292c2010-05-13 16:44:06 +00002013 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00002014 CXXCastPath BasePath;
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00002015 if (CheckDerivedToBaseConversion(From->getType(),
2016 ToType.getNonReferenceType(),
2017 From->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00002018 From->getSourceRange(),
2019 &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002020 IgnoreBaseAccess))
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00002021 return true;
Douglas Gregor88d292c2010-05-13 16:44:06 +00002022
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002023 ImpCastExprToType(From, ToType.getNonReferenceType(),
John McCalle3027922010-08-25 11:45:40 +00002024 CK_DerivedToBase, CastCategory(From),
John McCallcf142162010-08-07 06:22:56 +00002025 &BasePath);
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00002026 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00002027 }
2028
Douglas Gregor46188682010-05-18 22:42:18 +00002029 case ICK_Vector_Conversion:
John McCalle3027922010-08-25 11:45:40 +00002030 ImpCastExprToType(From, ToType, CK_BitCast);
Douglas Gregor46188682010-05-18 22:42:18 +00002031 break;
2032
2033 case ICK_Vector_Splat:
John McCalle3027922010-08-25 11:45:40 +00002034 ImpCastExprToType(From, ToType, CK_VectorSplat);
Douglas Gregor46188682010-05-18 22:42:18 +00002035 break;
2036
2037 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00002038 // Case 1. x -> _Complex y
2039 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2040 QualType ElType = ToComplex->getElementType();
2041 bool isFloatingComplex = ElType->isRealFloatingType();
2042
2043 // x -> y
2044 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2045 // do nothing
2046 } else if (From->getType()->isRealFloatingType()) {
2047 ImpCastExprToType(From, ElType,
2048 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral);
2049 } else {
2050 assert(From->getType()->isIntegerType());
2051 ImpCastExprToType(From, ElType,
2052 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast);
2053 }
2054 // y -> _Complex y
2055 ImpCastExprToType(From, ToType,
2056 isFloatingComplex ? CK_FloatingRealToComplex
2057 : CK_IntegralRealToComplex);
2058
2059 // Case 2. _Complex x -> y
2060 } else {
2061 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2062 assert(FromComplex);
2063
2064 QualType ElType = FromComplex->getElementType();
2065 bool isFloatingComplex = ElType->isRealFloatingType();
2066
2067 // _Complex x -> x
2068 ImpCastExprToType(From, ElType,
2069 isFloatingComplex ? CK_FloatingComplexToReal
2070 : CK_IntegralComplexToReal);
2071
2072 // x -> y
2073 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2074 // do nothing
2075 } else if (ToType->isRealFloatingType()) {
2076 ImpCastExprToType(From, ToType,
2077 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating);
2078 } else {
2079 assert(ToType->isIntegerType());
2080 ImpCastExprToType(From, ToType,
2081 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast);
2082 }
2083 }
Douglas Gregor46188682010-05-18 22:42:18 +00002084 break;
2085
2086 case ICK_Lvalue_To_Rvalue:
2087 case ICK_Array_To_Pointer:
2088 case ICK_Function_To_Pointer:
2089 case ICK_Qualification:
2090 case ICK_Num_Conversion_Kinds:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002091 assert(false && "Improper second standard conversion");
2092 break;
2093 }
2094
2095 switch (SCS.Third) {
2096 case ICK_Identity:
2097 // Nothing to do.
2098 break;
2099
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002100 case ICK_Qualification: {
2101 // The qualification keeps the category of the inner expression, unless the
2102 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00002103 ExprValueKind VK = ToType->isReferenceType() ?
2104 CastCategory(From) : VK_RValue;
Douglas Gregora8a089b2010-07-13 18:40:04 +00002105 ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
John McCalle3027922010-08-25 11:45:40 +00002106 CK_NoOp, VK);
Douglas Gregore489a7d2010-02-28 18:30:25 +00002107
2108 if (SCS.DeprecatedStringLiteralToCharPtr)
2109 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2110 << ToType.getNonReferenceType();
2111
Douglas Gregor39c16d42008-10-24 04:54:22 +00002112 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002113 }
2114
Douglas Gregor39c16d42008-10-24 04:54:22 +00002115 default:
Douglas Gregor46188682010-05-18 22:42:18 +00002116 assert(false && "Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002117 break;
2118 }
2119
2120 return false;
2121}
2122
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002123ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor54e5b132010-09-09 16:14:44 +00002124 SourceLocation KWLoc,
2125 ParsedType Ty,
2126 SourceLocation RParen) {
2127 TypeSourceInfo *TSInfo;
2128 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump11289f42009-09-09 15:08:12 +00002129
Douglas Gregor54e5b132010-09-09 16:14:44 +00002130 if (!TSInfo)
2131 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002132 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor54e5b132010-09-09 16:14:44 +00002133}
2134
Sebastian Redl058fc822010-09-14 23:40:14 +00002135static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT, QualType T,
2136 SourceLocation KeyLoc) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002137 assert(!T->isDependentType() &&
2138 "Cannot evaluate traits for dependent types.");
2139 ASTContext &C = Self.Context;
2140 switch(UTT) {
2141 default: assert(false && "Unknown type trait or not implemented");
2142 case UTT_IsPOD: return T->isPODType();
2143 case UTT_IsLiteral: return T->isLiteralType();
2144 case UTT_IsClass: // Fallthrough
2145 case UTT_IsUnion:
2146 if (const RecordType *Record = T->getAs<RecordType>()) {
2147 bool Union = Record->getDecl()->isUnion();
2148 return UTT == UTT_IsUnion ? Union : !Union;
2149 }
2150 return false;
2151 case UTT_IsEnum: return T->isEnumeralType();
2152 case UTT_IsPolymorphic:
2153 if (const RecordType *Record = T->getAs<RecordType>()) {
2154 // Type traits are only parsed in C++, so we've got CXXRecords.
2155 return cast<CXXRecordDecl>(Record->getDecl())->isPolymorphic();
2156 }
2157 return false;
2158 case UTT_IsAbstract:
2159 if (const RecordType *RT = T->getAs<RecordType>())
2160 return cast<CXXRecordDecl>(RT->getDecl())->isAbstract();
2161 return false;
2162 case UTT_IsEmpty:
2163 if (const RecordType *Record = T->getAs<RecordType>()) {
2164 return !Record->getDecl()->isUnion()
2165 && cast<CXXRecordDecl>(Record->getDecl())->isEmpty();
2166 }
2167 return false;
2168 case UTT_HasTrivialConstructor:
2169 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2170 // If __is_pod (type) is true then the trait is true, else if type is
2171 // a cv class or union type (or array thereof) with a trivial default
2172 // constructor ([class.ctor]) then the trait is true, else it is false.
2173 if (T->isPODType())
2174 return true;
2175 if (const RecordType *RT =
2176 C.getBaseElementType(T)->getAs<RecordType>())
2177 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialConstructor();
2178 return false;
2179 case UTT_HasTrivialCopy:
2180 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2181 // If __is_pod (type) is true or type is a reference type then
2182 // the trait is true, else if type is a cv class or union type
2183 // with a trivial copy constructor ([class.copy]) then the trait
2184 // is true, else it is false.
2185 if (T->isPODType() || T->isReferenceType())
2186 return true;
2187 if (const RecordType *RT = T->getAs<RecordType>())
2188 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2189 return false;
2190 case UTT_HasTrivialAssign:
2191 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2192 // If type is const qualified or is a reference type then the
2193 // trait is false. Otherwise if __is_pod (type) is true then the
2194 // trait is true, else if type is a cv class or union type with
2195 // a trivial copy assignment ([class.copy]) then the trait is
2196 // true, else it is false.
2197 // Note: the const and reference restrictions are interesting,
2198 // given that const and reference members don't prevent a class
2199 // from having a trivial copy assignment operator (but do cause
2200 // errors if the copy assignment operator is actually used, q.v.
2201 // [class.copy]p12).
2202
2203 if (C.getBaseElementType(T).isConstQualified())
2204 return false;
2205 if (T->isPODType())
2206 return true;
2207 if (const RecordType *RT = T->getAs<RecordType>())
2208 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2209 return false;
2210 case UTT_HasTrivialDestructor:
2211 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2212 // If __is_pod (type) is true or type is a reference type
2213 // then the trait is true, else if type is a cv class or union
2214 // type (or array thereof) with a trivial destructor
2215 // ([class.dtor]) then the trait is true, else it is
2216 // false.
2217 if (T->isPODType() || T->isReferenceType())
2218 return true;
2219 if (const RecordType *RT =
2220 C.getBaseElementType(T)->getAs<RecordType>())
2221 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2222 return false;
2223 // TODO: Propagate nothrowness for implicitly declared special members.
2224 case UTT_HasNothrowAssign:
2225 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2226 // If type is const qualified or is a reference type then the
2227 // trait is false. Otherwise if __has_trivial_assign (type)
2228 // is true then the trait is true, else if type is a cv class
2229 // or union type with copy assignment operators that are known
2230 // not to throw an exception then the trait is true, else it is
2231 // false.
2232 if (C.getBaseElementType(T).isConstQualified())
2233 return false;
2234 if (T->isReferenceType())
2235 return false;
2236 if (T->isPODType())
2237 return true;
2238 if (const RecordType *RT = T->getAs<RecordType>()) {
2239 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2240 if (RD->hasTrivialCopyAssignment())
2241 return true;
2242
2243 bool FoundAssign = false;
2244 bool AllNoThrow = true;
2245 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redl058fc822010-09-14 23:40:14 +00002246 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2247 Sema::LookupOrdinaryName);
2248 if (Self.LookupQualifiedName(Res, RD)) {
2249 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2250 Op != OpEnd; ++Op) {
2251 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2252 if (Operator->isCopyAssignmentOperator()) {
2253 FoundAssign = true;
2254 const FunctionProtoType *CPT
2255 = Operator->getType()->getAs<FunctionProtoType>();
2256 if (!CPT->hasEmptyExceptionSpec()) {
2257 AllNoThrow = false;
2258 break;
2259 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002260 }
2261 }
2262 }
2263
2264 return FoundAssign && AllNoThrow;
2265 }
2266 return false;
2267 case UTT_HasNothrowCopy:
2268 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2269 // If __has_trivial_copy (type) is true then the trait is true, else
2270 // if type is a cv class or union type with copy constructors that are
2271 // known not to throw an exception then the trait is true, else it is
2272 // false.
2273 if (T->isPODType() || T->isReferenceType())
2274 return true;
2275 if (const RecordType *RT = T->getAs<RecordType>()) {
2276 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2277 if (RD->hasTrivialCopyConstructor())
2278 return true;
2279
2280 bool FoundConstructor = false;
2281 bool AllNoThrow = true;
2282 unsigned FoundTQs;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002283 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl951006f2010-09-13 21:10:20 +00002284 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002285 Con != ConEnd; ++Con) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00002286 // A template constructor is never a copy constructor.
2287 // FIXME: However, it may actually be selected at the actual overload
2288 // resolution point.
2289 if (isa<FunctionTemplateDecl>(*Con))
2290 continue;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002291 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2292 if (Constructor->isCopyConstructor(FoundTQs)) {
2293 FoundConstructor = true;
2294 const FunctionProtoType *CPT
2295 = Constructor->getType()->getAs<FunctionProtoType>();
Sebastian Redlc15c3262010-09-13 22:02:47 +00002296 // TODO: check whether evaluating default arguments can throw.
2297 // For now, we'll be conservative and assume that they can throw.
2298 if (!CPT->hasEmptyExceptionSpec() || CPT->getNumArgs() > 1) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002299 AllNoThrow = false;
2300 break;
2301 }
2302 }
2303 }
2304
2305 return FoundConstructor && AllNoThrow;
2306 }
2307 return false;
2308 case UTT_HasNothrowConstructor:
2309 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2310 // If __has_trivial_constructor (type) is true then the trait is
2311 // true, else if type is a cv class or union type (or array
2312 // thereof) with a default constructor that is known not to
2313 // throw an exception then the trait is true, else it is false.
2314 if (T->isPODType())
2315 return true;
2316 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2317 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2318 if (RD->hasTrivialConstructor())
2319 return true;
2320
Sebastian Redlc15c3262010-09-13 22:02:47 +00002321 DeclContext::lookup_const_iterator Con, ConEnd;
2322 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2323 Con != ConEnd; ++Con) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00002324 // FIXME: In C++0x, a constructor template can be a default constructor.
2325 if (isa<FunctionTemplateDecl>(*Con))
2326 continue;
Sebastian Redlc15c3262010-09-13 22:02:47 +00002327 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2328 if (Constructor->isDefaultConstructor()) {
2329 const FunctionProtoType *CPT
2330 = Constructor->getType()->getAs<FunctionProtoType>();
2331 // TODO: check whether evaluating default arguments can throw.
2332 // For now, we'll be conservative and assume that they can throw.
2333 return CPT->hasEmptyExceptionSpec() && CPT->getNumArgs() == 0;
2334 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002335 }
2336 }
2337 return false;
2338 case UTT_HasVirtualDestructor:
2339 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2340 // If type is a class type with a virtual destructor ([class.dtor])
2341 // then the trait is true, else it is false.
2342 if (const RecordType *Record = T->getAs<RecordType>()) {
2343 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redl058fc822010-09-14 23:40:14 +00002344 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002345 return Destructor->isVirtual();
2346 }
2347 return false;
2348 }
2349}
2350
2351ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor54e5b132010-09-09 16:14:44 +00002352 SourceLocation KWLoc,
2353 TypeSourceInfo *TSInfo,
2354 SourceLocation RParen) {
2355 QualType T = TSInfo->getType();
2356
Anders Carlsson1f9648d2009-07-07 19:06:02 +00002357 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
2358 // all traits except __is_class, __is_enum and __is_union require a the type
Sebastian Redla190d362010-09-08 00:48:43 +00002359 // to be complete, an array of unknown bound, or void.
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002360 if (UTT != UTT_IsClass && UTT != UTT_IsEnum && UTT != UTT_IsUnion) {
Sebastian Redla190d362010-09-08 00:48:43 +00002361 QualType E = T;
2362 if (T->isIncompleteArrayType())
2363 E = Context.getAsArrayType(T)->getElementType();
2364 if (!T->isVoidType() &&
2365 RequireCompleteType(KWLoc, E,
Anders Carlsson029fc692009-08-26 22:59:12 +00002366 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson1f9648d2009-07-07 19:06:02 +00002367 return ExprError();
2368 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002369
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002370 bool Value = false;
2371 if (!T->isDependentType())
Sebastian Redl058fc822010-09-14 23:40:14 +00002372 Value = EvaluateUnaryTypeTrait(*this, UTT, T, KWLoc);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002373
2374 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson1f9648d2009-07-07 19:06:02 +00002375 RParen, Context.BoolTy));
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002376}
Sebastian Redl5822f082009-02-07 20:10:22 +00002377
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002378ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
2379 SourceLocation KWLoc,
2380 ParsedType LhsTy,
2381 ParsedType RhsTy,
2382 SourceLocation RParen) {
2383 TypeSourceInfo *LhsTSInfo;
2384 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
2385 if (!LhsTSInfo)
2386 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
2387
2388 TypeSourceInfo *RhsTSInfo;
2389 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
2390 if (!RhsTSInfo)
2391 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
2392
2393 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
2394}
2395
2396static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
2397 QualType LhsT, QualType RhsT,
2398 SourceLocation KeyLoc) {
2399 assert((!LhsT->isDependentType() || RhsT->isDependentType()) &&
2400 "Cannot evaluate traits for dependent types.");
2401
2402 switch(BTT) {
2403 case BTT_IsBaseOf:
2404 // C++0x [meta.rel]p2
2405 // Base is a base class of Derived without regard to cv-qualifiers or
2406 // Base and Derived are not unions and name the same class type without
2407 // regard to cv-qualifiers.
2408 if (Self.IsDerivedFrom(RhsT, LhsT) ||
2409 (!LhsT->isUnionType() && !RhsT->isUnionType()
2410 && LhsT->getAsCXXRecordDecl() == RhsT->getAsCXXRecordDecl()))
2411 return true;
2412
2413 return false;
Francois Pichet34b21132010-12-08 22:35:30 +00002414 case BTT_TypeCompatible:
2415 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
2416 RhsT.getUnqualifiedType());
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002417 }
2418 llvm_unreachable("Unknown type trait or not implemented");
2419}
2420
2421ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
2422 SourceLocation KWLoc,
2423 TypeSourceInfo *LhsTSInfo,
2424 TypeSourceInfo *RhsTSInfo,
2425 SourceLocation RParen) {
2426 QualType LhsT = LhsTSInfo->getType();
2427 QualType RhsT = RhsTSInfo->getType();
2428
2429 if (BTT == BTT_IsBaseOf) {
2430 // C++0x [meta.rel]p2
2431 // If Base and Derived are class types and are different types
2432 // (ignoring possible cv-qualifiers) then Derived shall be a complete
2433 // type. []
2434 CXXRecordDecl *LhsDecl = LhsT->getAsCXXRecordDecl();
2435 CXXRecordDecl *RhsDecl = RhsT->getAsCXXRecordDecl();
2436 if (!LhsT->isDependentType() && !RhsT->isDependentType() &&
2437 LhsDecl && RhsDecl && LhsT != RhsT &&
2438 RequireCompleteType(KWLoc, RhsT,
2439 diag::err_incomplete_type_used_in_type_trait_expr))
2440 return ExprError();
Francois Pichet34b21132010-12-08 22:35:30 +00002441 } else if (BTT == BTT_TypeCompatible) {
2442 if (getLangOptions().CPlusPlus) {
2443 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
2444 << SourceRange(KWLoc, RParen);
2445 return ExprError();
2446 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002447 }
2448
2449 bool Value = false;
2450 if (!LhsT->isDependentType() && !RhsT->isDependentType())
2451 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
2452
Francois Pichet34b21132010-12-08 22:35:30 +00002453 // Select trait result type.
2454 QualType ResultType;
2455 switch (BTT) {
2456 default: llvm_unreachable("Unknown type trait or not implemented");
2457 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
2458 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
2459 }
2460
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002461 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
2462 RhsTSInfo, Value, RParen,
Francois Pichet34b21132010-12-08 22:35:30 +00002463 ResultType));
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002464}
2465
John McCall7decc9e2010-11-18 06:31:45 +00002466QualType Sema::CheckPointerToMemberOperands(Expr *&lex, Expr *&rex,
2467 ExprValueKind &VK,
2468 SourceLocation Loc,
2469 bool isIndirect) {
Sebastian Redl5822f082009-02-07 20:10:22 +00002470 const char *OpSpelling = isIndirect ? "->*" : ".*";
2471 // C++ 5.5p2
2472 // The binary operator .* [p3: ->*] binds its second operand, which shall
2473 // be of type "pointer to member of T" (where T is a completely-defined
2474 // class type) [...]
2475 QualType RType = rex->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002476 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00002477 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00002478 Diag(Loc, diag::err_bad_memptr_rhs)
2479 << OpSpelling << RType << rex->getSourceRange();
2480 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00002481 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00002482
Sebastian Redl5822f082009-02-07 20:10:22 +00002483 QualType Class(MemPtr->getClass(), 0);
2484
Douglas Gregord07ba342010-10-13 20:41:14 +00002485 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
2486 // member pointer points must be completely-defined. However, there is no
2487 // reason for this semantic distinction, and the rule is not enforced by
2488 // other compilers. Therefore, we do not check this property, as it is
2489 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00002490
Sebastian Redl5822f082009-02-07 20:10:22 +00002491 // C++ 5.5p2
2492 // [...] to its first operand, which shall be of class T or of a class of
2493 // which T is an unambiguous and accessible base class. [p3: a pointer to
2494 // such a class]
2495 QualType LType = lex->getType();
2496 if (isIndirect) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002497 if (const PointerType *Ptr = LType->getAs<PointerType>())
John McCall7decc9e2010-11-18 06:31:45 +00002498 LType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00002499 else {
2500 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanian59f64202009-10-26 20:45:27 +00002501 << OpSpelling << 1 << LType
Douglas Gregora771f462010-03-31 17:46:05 +00002502 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00002503 return QualType();
2504 }
2505 }
2506
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002507 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00002508 // If we want to check the hierarchy, we need a complete type.
2509 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
2510 << OpSpelling << (int)isIndirect)) {
2511 return QualType();
2512 }
Anders Carlssona70cff62010-04-24 19:06:50 +00002513 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002514 /*DetectVirtual=*/false);
Mike Stump87c57ac2009-05-16 07:39:55 +00002515 // FIXME: Would it be useful to print full ambiguity paths, or is that
2516 // overkill?
Sebastian Redl5822f082009-02-07 20:10:22 +00002517 if (!IsDerivedFrom(LType, Class, Paths) ||
2518 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
2519 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman1fcf66b2010-01-16 00:00:48 +00002520 << (int)isIndirect << lex->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00002521 return QualType();
2522 }
Eli Friedman1fcf66b2010-01-16 00:00:48 +00002523 // Cast LHS to type of use.
2524 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
John McCall2536c6d2010-08-25 10:28:54 +00002525 ExprValueKind VK =
2526 isIndirect ? VK_RValue : CastCategory(lex);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002527
John McCallcf142162010-08-07 06:22:56 +00002528 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00002529 BuildBasePathArray(Paths, BasePath);
John McCall2536c6d2010-08-25 10:28:54 +00002530 ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00002531 }
2532
Douglas Gregor747eb782010-07-08 06:14:04 +00002533 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00002534 // Diagnose use of pointer-to-member type which when used as
2535 // the functional cast in a pointer-to-member expression.
2536 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2537 return QualType();
2538 }
John McCall7decc9e2010-11-18 06:31:45 +00002539
Sebastian Redl5822f082009-02-07 20:10:22 +00002540 // C++ 5.5p2
2541 // The result is an object or a function of the type specified by the
2542 // second operand.
2543 // The cv qualifiers are the union of those in the pointer and the left side,
2544 // in accordance with 5.5p5 and 5.2.5.
2545 // FIXME: This returns a dereferenced member function pointer as a normal
2546 // function type. However, the only operation valid on such functions is
Mike Stump87c57ac2009-05-16 07:39:55 +00002547 // calling them. There's also a GCC extension to get a function pointer to the
2548 // thing, which is another complication, because this type - unlike the type
2549 // that is the result of this expression - takes the class as the first
Sebastian Redl5822f082009-02-07 20:10:22 +00002550 // argument.
2551 // We probably need a "MemberFunctionClosureType" or something like that.
2552 QualType Result = MemPtr->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00002553 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00002554
2555 // C++ [expr.mptr.oper]p6:
2556 // The result of a .* expression whose second operand is a pointer
2557 // to a data member is of the same value category as its
2558 // first operand. The result of a .* expression whose second
2559 // operand is a pointer to a member function is a prvalue. The
2560 // result of an ->* expression is an lvalue if its second operand
2561 // is a pointer to data member and a prvalue otherwise.
2562 if (Result->isFunctionType())
2563 VK = VK_RValue;
2564 else if (isIndirect)
2565 VK = VK_LValue;
2566 else
2567 VK = lex->getValueKind();
2568
Sebastian Redl5822f082009-02-07 20:10:22 +00002569 return Result;
2570}
Sebastian Redl1a99f442009-04-16 17:51:27 +00002571
Sebastian Redl1a99f442009-04-16 17:51:27 +00002572/// \brief Try to convert a type to another according to C++0x 5.16p3.
2573///
2574/// This is part of the parameter validation for the ? operator. If either
2575/// value operand is a class type, the two operands are attempted to be
2576/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002577/// It returns true if the program is ill-formed and has already been diagnosed
2578/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002579static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2580 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00002581 bool &HaveConversion,
2582 QualType &ToType) {
2583 HaveConversion = false;
2584 ToType = To->getType();
2585
2586 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
2587 SourceLocation());
Sebastian Redl1a99f442009-04-16 17:51:27 +00002588 // C++0x 5.16p3
2589 // The process for determining whether an operand expression E1 of type T1
2590 // can be converted to match an operand expression E2 of type T2 is defined
2591 // as follows:
2592 // -- If E2 is an lvalue:
John McCall086a4642010-11-24 05:12:34 +00002593 bool ToIsLvalue = To->isLValue();
Douglas Gregorf9edf802010-03-26 20:59:55 +00002594 if (ToIsLvalue) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002595 // E1 can be converted to match E2 if E1 can be implicitly converted to
2596 // type "lvalue reference to T2", subject to the constraint that in the
2597 // conversion the reference must bind directly to E1.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002598 QualType T = Self.Context.getLValueReferenceType(ToType);
2599 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2600
2601 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2602 if (InitSeq.isDirectReferenceBinding()) {
2603 ToType = T;
2604 HaveConversion = true;
2605 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002606 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002607
2608 if (InitSeq.isAmbiguous())
2609 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002610 }
John McCall65eb8792010-02-25 01:37:24 +00002611
Sebastian Redl1a99f442009-04-16 17:51:27 +00002612 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2613 // -- if E1 and E2 have class type, and the underlying class types are
2614 // the same or one is a base class of the other:
2615 QualType FTy = From->getType();
2616 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002617 const RecordType *FRec = FTy->getAs<RecordType>();
2618 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002619 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2620 Self.IsDerivedFrom(FTy, TTy);
2621 if (FRec && TRec &&
2622 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002623 // E1 can be converted to match E2 if the class of T2 is the
2624 // same type as, or a base class of, the class of T1, and
2625 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00002626 if (FRec == TRec || FDerivedFromT) {
2627 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002628 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2629 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2630 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2631 HaveConversion = true;
2632 return false;
2633 }
2634
2635 if (InitSeq.isAmbiguous())
2636 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2637 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00002638 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002639
2640 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002641 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002642
2643 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2644 // implicitly converted to the type that expression E2 would have
Douglas Gregorf9edf802010-03-26 20:59:55 +00002645 // if E2 were converted to an rvalue (or the type it has, if E2 is
2646 // an rvalue).
2647 //
2648 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2649 // to the array-to-pointer or function-to-pointer conversions.
2650 if (!TTy->getAs<TagType>())
2651 TTy = TTy.getUnqualifiedType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002652
2653 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2654 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2655 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2656 ToType = TTy;
2657 if (InitSeq.isAmbiguous())
2658 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2659
Sebastian Redl1a99f442009-04-16 17:51:27 +00002660 return false;
2661}
2662
2663/// \brief Try to find a common type for two according to C++0x 5.16p5.
2664///
2665/// This is part of the parameter validation for the ? operator. If either
2666/// value operand is a class type, overload resolution is used to find a
2667/// conversion to a common type.
2668static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2669 SourceLocation Loc) {
2670 Expr *Args[2] = { LHS, RHS };
John McCallbc077cf2010-02-08 23:07:23 +00002671 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002672 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002673
2674 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00002675 switch (CandidateSet.BestViableFunction(Self, Loc, Best)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002676 case OR_Success:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002677 // We found a match. Perform the conversions on the arguments and move on.
2678 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002679 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00002680 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002681 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002682 break;
2683 return false;
2684
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002685 case OR_No_Viable_Function:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002686 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2687 << LHS->getType() << RHS->getType()
2688 << LHS->getSourceRange() << RHS->getSourceRange();
2689 return true;
2690
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002691 case OR_Ambiguous:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002692 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2693 << LHS->getType() << RHS->getType()
2694 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00002695 // FIXME: Print the possible common types by printing the return types of
2696 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002697 break;
2698
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002699 case OR_Deleted:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002700 assert(false && "Conditional operator has only built-in overloads");
2701 break;
2702 }
2703 return true;
2704}
2705
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002706/// \brief Perform an "extended" implicit conversion as returned by
2707/// TryClassUnification.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002708static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2709 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2710 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2711 SourceLocation());
2712 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00002713 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1));
Douglas Gregor838fcc32010-03-26 20:14:36 +00002714 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002715 return true;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002716
2717 E = Result.takeAs<Expr>();
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002718 return false;
2719}
2720
Sebastian Redl1a99f442009-04-16 17:51:27 +00002721/// \brief Check the operands of ?: under C++ semantics.
2722///
2723/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2724/// extension. In this case, LHS == Cond. (But they're not aliases.)
2725QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCall7decc9e2010-11-18 06:31:45 +00002726 Expr *&SAVE, ExprValueKind &VK,
John McCall4bc41ae2010-11-18 19:01:18 +00002727 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002728 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002729 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2730 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002731
2732 // C++0x 5.16p1
2733 // The first expression is contextually converted to bool.
2734 if (!Cond->isTypeDependent()) {
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00002735 if (SAVE && Cond->getType()->isArrayType()) {
2736 QualType CondTy = Cond->getType();
2737 CondTy = Context.getArrayDecayedType(CondTy);
2738 ImpCastExprToType(Cond, CondTy, CK_ArrayToPointerDecay);
2739 SAVE = LHS = Cond;
2740 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00002741 if (CheckCXXBooleanCondition(Cond))
2742 return QualType();
2743 }
2744
John McCall7decc9e2010-11-18 06:31:45 +00002745 // Assume r-value.
2746 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00002747 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00002748
Sebastian Redl1a99f442009-04-16 17:51:27 +00002749 // Either of the arguments dependent?
2750 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2751 return Context.DependentTy;
2752
2753 // C++0x 5.16p2
2754 // If either the second or the third operand has type (cv) void, ...
2755 QualType LTy = LHS->getType();
2756 QualType RTy = RHS->getType();
2757 bool LVoid = LTy->isVoidType();
2758 bool RVoid = RTy->isVoidType();
2759 if (LVoid || RVoid) {
2760 // ... then the [l2r] conversions are performed on the second and third
2761 // operands ...
Douglas Gregorb92a1562010-02-03 00:27:59 +00002762 DefaultFunctionArrayLvalueConversion(LHS);
2763 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002764 LTy = LHS->getType();
2765 RTy = RHS->getType();
2766
2767 // ... and one of the following shall hold:
2768 // -- The second or the third operand (but not both) is a throw-
2769 // expression; the result is of the type of the other and is an rvalue.
2770 bool LThrow = isa<CXXThrowExpr>(LHS);
2771 bool RThrow = isa<CXXThrowExpr>(RHS);
2772 if (LThrow && !RThrow)
2773 return RTy;
2774 if (RThrow && !LThrow)
2775 return LTy;
2776
2777 // -- Both the second and third operands have type void; the result is of
2778 // type void and is an rvalue.
2779 if (LVoid && RVoid)
2780 return Context.VoidTy;
2781
2782 // Neither holds, error.
2783 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2784 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2785 << LHS->getSourceRange() << RHS->getSourceRange();
2786 return QualType();
2787 }
2788
2789 // Neither is void.
2790
2791 // C++0x 5.16p3
2792 // Otherwise, if the second and third operand have different types, and
2793 // either has (cv) class type, and attempt is made to convert each of those
2794 // operands to the other.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002795 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00002796 (LTy->isRecordType() || RTy->isRecordType())) {
2797 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2798 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002799 QualType L2RType, R2LType;
2800 bool HaveL2R, HaveR2L;
2801 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002802 return QualType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002803 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002804 return QualType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002805
Sebastian Redl1a99f442009-04-16 17:51:27 +00002806 // If both can be converted, [...] the program is ill-formed.
2807 if (HaveL2R && HaveR2L) {
2808 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2809 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2810 return QualType();
2811 }
2812
2813 // If exactly one conversion is possible, that conversion is applied to
2814 // the chosen operand and the converted operands are used in place of the
2815 // original operands for the remainder of this section.
2816 if (HaveL2R) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002817 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002818 return QualType();
2819 LTy = LHS->getType();
2820 } else if (HaveR2L) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002821 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002822 return QualType();
2823 RTy = RHS->getType();
2824 }
2825 }
2826
2827 // C++0x 5.16p4
John McCall7decc9e2010-11-18 06:31:45 +00002828 // If the second and third operands are glvalues of the same value
2829 // category and have the same type, the result is of that type and
2830 // value category and it is a bit-field if the second or the third
2831 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00002832 // We only extend this to bitfields, not to the crazy other kinds of
2833 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00002834 bool Same = Context.hasSameType(LTy, RTy);
John McCall7decc9e2010-11-18 06:31:45 +00002835 if (Same &&
2836 LHS->getValueKind() != VK_RValue &&
2837 LHS->getValueKind() == RHS->getValueKind() &&
John McCall4bc41ae2010-11-18 19:01:18 +00002838 (LHS->getObjectKind() == OK_Ordinary ||
2839 LHS->getObjectKind() == OK_BitField) &&
2840 (RHS->getObjectKind() == OK_Ordinary ||
2841 RHS->getObjectKind() == OK_BitField)) {
John McCall7decc9e2010-11-18 06:31:45 +00002842 VK = LHS->getValueKind();
John McCall4bc41ae2010-11-18 19:01:18 +00002843 if (LHS->getObjectKind() == OK_BitField ||
2844 RHS->getObjectKind() == OK_BitField)
2845 OK = OK_BitField;
John McCall7decc9e2010-11-18 06:31:45 +00002846 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00002847 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00002848
2849 // C++0x 5.16p5
2850 // Otherwise, the result is an rvalue. If the second and third operands
2851 // do not have the same type, and either has (cv) class type, ...
2852 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2853 // ... overload resolution is used to determine the conversions (if any)
2854 // to be applied to the operands. If the overload resolution fails, the
2855 // program is ill-formed.
2856 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2857 return QualType();
2858 }
2859
2860 // C++0x 5.16p6
2861 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2862 // conversions are performed on the second and third operands.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002863 DefaultFunctionArrayLvalueConversion(LHS);
2864 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002865 LTy = LHS->getType();
2866 RTy = RHS->getType();
2867
2868 // After those conversions, one of the following shall hold:
2869 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00002870 // is of that type. If the operands have class type, the result
2871 // is a prvalue temporary of the result type, which is
2872 // copy-initialized from either the second operand or the third
2873 // operand depending on the value of the first operand.
2874 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
2875 if (LTy->isRecordType()) {
2876 // The operands have class type. Make a temporary copy.
2877 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
John McCalldadc5752010-08-24 06:29:42 +00002878 ExprResult LHSCopy = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00002879 SourceLocation(),
2880 Owned(LHS));
Douglas Gregorfa6010b2010-05-19 23:40:50 +00002881 if (LHSCopy.isInvalid())
2882 return QualType();
2883
John McCalldadc5752010-08-24 06:29:42 +00002884 ExprResult RHSCopy = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00002885 SourceLocation(),
2886 Owned(RHS));
Douglas Gregorfa6010b2010-05-19 23:40:50 +00002887 if (RHSCopy.isInvalid())
2888 return QualType();
2889
2890 LHS = LHSCopy.takeAs<Expr>();
2891 RHS = RHSCopy.takeAs<Expr>();
2892 }
2893
Sebastian Redl1a99f442009-04-16 17:51:27 +00002894 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00002895 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00002896
Douglas Gregor46188682010-05-18 22:42:18 +00002897 // Extension: conditional operator involving vector types.
2898 if (LTy->isVectorType() || RTy->isVectorType())
2899 return CheckVectorOperands(QuestionLoc, LHS, RHS);
2900
Sebastian Redl1a99f442009-04-16 17:51:27 +00002901 // -- The second and third operands have arithmetic or enumeration type;
2902 // the usual arithmetic conversions are performed to bring them to a
2903 // common type, and the result is of that type.
2904 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2905 UsualArithmeticConversions(LHS, RHS);
2906 return LHS->getType();
2907 }
2908
2909 // -- The second and third operands have pointer type, or one has pointer
2910 // type and the other is a null pointer constant; pointer conversions
2911 // and qualification conversions are performed to bring them to their
2912 // composite pointer type. The result is of the composite pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00002913 // -- The second and third operands have pointer to member type, or one has
2914 // pointer to member type and the other is a null pointer constant;
2915 // pointer to member conversions and qualification conversions are
2916 // performed to bring them to a common type, whose cv-qualification
2917 // shall match the cv-qualification of either the second or the third
2918 // operand. The result is of the common type.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002919 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00002920 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002921 isSFINAEContext()? 0 : &NonStandardCompositeType);
2922 if (!Composite.isNull()) {
2923 if (NonStandardCompositeType)
2924 Diag(QuestionLoc,
2925 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2926 << LTy << RTy << Composite
2927 << LHS->getSourceRange() << RHS->getSourceRange();
2928
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002929 return Composite;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002930 }
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00002931
Douglas Gregor697a3912010-04-01 22:47:07 +00002932 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00002933 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2934 if (!Composite.isNull())
2935 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002936
Sebastian Redl1a99f442009-04-16 17:51:27 +00002937 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2938 << LHS->getType() << RHS->getType()
2939 << LHS->getSourceRange() << RHS->getSourceRange();
2940 return QualType();
2941}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002942
2943/// \brief Find a merged pointer type and convert the two expressions to it.
2944///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002945/// This finds the composite pointer type (or member pointer type) for @p E1
2946/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2947/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002948/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002949///
Douglas Gregor19175ff2010-04-16 23:20:25 +00002950/// \param Loc The location of the operator requiring these two expressions to
2951/// be converted to the composite pointer type.
2952///
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002953/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2954/// a non-standard (but still sane) composite type to which both expressions
2955/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2956/// will be set true.
Douglas Gregor19175ff2010-04-16 23:20:25 +00002957QualType Sema::FindCompositePointerType(SourceLocation Loc,
2958 Expr *&E1, Expr *&E2,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002959 bool *NonStandardCompositeType) {
2960 if (NonStandardCompositeType)
2961 *NonStandardCompositeType = false;
2962
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002963 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2964 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002965
Fariborz Jahanian33e148f2009-12-08 20:04:24 +00002966 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2967 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002968 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002969
2970 // C++0x 5.9p2
2971 // Pointer conversions and qualification conversions are performed on
2972 // pointer operands to bring them to their composite pointer type. If
2973 // one operand is a null pointer constant, the composite pointer type is
2974 // the type of the other operand.
Douglas Gregor56751b52009-09-25 04:25:58 +00002975 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002976 if (T2->isMemberPointerType())
John McCalle3027922010-08-25 11:45:40 +00002977 ImpCastExprToType(E1, T2, CK_NullToMemberPointer);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002978 else
John McCalle84af4e2010-11-13 01:35:44 +00002979 ImpCastExprToType(E1, T2, CK_NullToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002980 return T2;
2981 }
Douglas Gregor56751b52009-09-25 04:25:58 +00002982 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002983 if (T1->isMemberPointerType())
John McCalle3027922010-08-25 11:45:40 +00002984 ImpCastExprToType(E2, T1, CK_NullToMemberPointer);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002985 else
John McCalle84af4e2010-11-13 01:35:44 +00002986 ImpCastExprToType(E2, T1, CK_NullToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002987 return T1;
2988 }
Mike Stump11289f42009-09-09 15:08:12 +00002989
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002990 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00002991 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2992 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002993 return QualType();
2994
2995 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2996 // the other has type "pointer to cv2 T" and the composite pointer type is
2997 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2998 // Otherwise, the composite pointer type is a pointer type similar to the
2999 // type of one of the operands, with a cv-qualification signature that is
3000 // the union of the cv-qualification signatures of the operand types.
3001 // In practice, the first part here is redundant; it's subsumed by the second.
3002 // What we do here is, we build the two possible composite types, and try the
3003 // conversions in both directions. If only one works, or if the two composite
3004 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00003005 // FIXME: extended qualifiers?
Sebastian Redl658262f2009-11-16 21:03:45 +00003006 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
3007 QualifierVector QualifierUnion;
3008 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
3009 ContainingClassVector;
3010 ContainingClassVector MemberOfClass;
3011 QualType Composite1 = Context.getCanonicalType(T1),
3012 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003013 unsigned NeedConstBefore = 0;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003014 do {
3015 const PointerType *Ptr1, *Ptr2;
3016 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3017 (Ptr2 = Composite2->getAs<PointerType>())) {
3018 Composite1 = Ptr1->getPointeeType();
3019 Composite2 = Ptr2->getPointeeType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003020
3021 // If we're allowed to create a non-standard composite type, keep track
3022 // of where we need to fill in additional 'const' qualifiers.
3023 if (NonStandardCompositeType &&
3024 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3025 NeedConstBefore = QualifierUnion.size();
3026
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003027 QualifierUnion.push_back(
3028 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3029 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3030 continue;
3031 }
Mike Stump11289f42009-09-09 15:08:12 +00003032
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003033 const MemberPointerType *MemPtr1, *MemPtr2;
3034 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3035 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3036 Composite1 = MemPtr1->getPointeeType();
3037 Composite2 = MemPtr2->getPointeeType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003038
3039 // If we're allowed to create a non-standard composite type, keep track
3040 // of where we need to fill in additional 'const' qualifiers.
3041 if (NonStandardCompositeType &&
3042 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3043 NeedConstBefore = QualifierUnion.size();
3044
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003045 QualifierUnion.push_back(
3046 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3047 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3048 MemPtr2->getClass()));
3049 continue;
3050 }
Mike Stump11289f42009-09-09 15:08:12 +00003051
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003052 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00003053
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003054 // Cannot unwrap any more types.
3055 break;
3056 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00003057
Douglas Gregor6f5f6422010-02-25 22:29:57 +00003058 if (NeedConstBefore && NonStandardCompositeType) {
3059 // Extension: Add 'const' to qualifiers that come before the first qualifier
3060 // mismatch, so that our (non-standard!) composite type meets the
3061 // requirements of C++ [conv.qual]p4 bullet 3.
3062 for (unsigned I = 0; I != NeedConstBefore; ++I) {
3063 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3064 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3065 *NonStandardCompositeType = true;
3066 }
3067 }
3068 }
3069
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003070 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-11-16 21:03:45 +00003071 ContainingClassVector::reverse_iterator MOC
3072 = MemberOfClass.rbegin();
3073 for (QualifierVector::reverse_iterator
3074 I = QualifierUnion.rbegin(),
3075 E = QualifierUnion.rend();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003076 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00003077 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003078 if (MOC->first && MOC->second) {
3079 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00003080 Composite1 = Context.getMemberPointerType(
3081 Context.getQualifiedType(Composite1, Quals),
3082 MOC->first);
3083 Composite2 = Context.getMemberPointerType(
3084 Context.getQualifiedType(Composite2, Quals),
3085 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003086 } else {
3087 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00003088 Composite1
3089 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3090 Composite2
3091 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00003092 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003093 }
3094
Douglas Gregor19175ff2010-04-16 23:20:25 +00003095 // Try to convert to the first composite pointer type.
3096 InitializedEntity Entity1
3097 = InitializedEntity::InitializeTemporary(Composite1);
3098 InitializationKind Kind
3099 = InitializationKind::CreateCopy(Loc, SourceLocation());
3100 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3101 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump11289f42009-09-09 15:08:12 +00003102
Douglas Gregor19175ff2010-04-16 23:20:25 +00003103 if (E1ToC1 && E2ToC1) {
3104 // Conversion to Composite1 is viable.
3105 if (!Context.hasSameType(Composite1, Composite2)) {
3106 // Composite2 is a different type from Composite1. Check whether
3107 // Composite2 is also viable.
3108 InitializedEntity Entity2
3109 = InitializedEntity::InitializeTemporary(Composite2);
3110 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3111 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3112 if (E1ToC2 && E2ToC2) {
3113 // Both Composite1 and Composite2 are viable and are different;
3114 // this is an ambiguity.
3115 return QualType();
3116 }
3117 }
3118
3119 // Convert E1 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00003120 ExprResult E1Result
John McCall37ad5512010-08-23 06:44:23 +00003121 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00003122 if (E1Result.isInvalid())
3123 return QualType();
3124 E1 = E1Result.takeAs<Expr>();
3125
3126 // Convert E2 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00003127 ExprResult E2Result
John McCall37ad5512010-08-23 06:44:23 +00003128 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00003129 if (E2Result.isInvalid())
3130 return QualType();
3131 E2 = E2Result.takeAs<Expr>();
3132
3133 return Composite1;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003134 }
3135
Douglas Gregor19175ff2010-04-16 23:20:25 +00003136 // Check whether Composite2 is viable.
3137 InitializedEntity Entity2
3138 = InitializedEntity::InitializeTemporary(Composite2);
3139 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3140 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3141 if (!E1ToC2 || !E2ToC2)
3142 return QualType();
3143
3144 // Convert E1 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00003145 ExprResult E1Result
John McCall37ad5512010-08-23 06:44:23 +00003146 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00003147 if (E1Result.isInvalid())
3148 return QualType();
3149 E1 = E1Result.takeAs<Expr>();
3150
3151 // Convert E2 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00003152 ExprResult E2Result
John McCall37ad5512010-08-23 06:44:23 +00003153 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00003154 if (E2Result.isInvalid())
3155 return QualType();
3156 E2 = E2Result.takeAs<Expr>();
3157
3158 return Composite2;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00003159}
Anders Carlsson85a307d2009-05-17 18:41:29 +00003160
John McCalldadc5752010-08-24 06:29:42 +00003161ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00003162 if (!E)
3163 return ExprError();
3164
Anders Carlssonf86a8d12009-08-15 23:41:35 +00003165 if (!Context.getLangOptions().CPlusPlus)
3166 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00003167
Douglas Gregor363b1512009-12-24 18:51:59 +00003168 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
3169
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003170 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlsson2d4cada2009-05-30 20:36:53 +00003171 if (!RT)
3172 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00003173
Anders Carlssonbb4cfdf2010-07-16 21:18:37 +00003174 // If this is the result of a call or an Objective-C message send expression,
3175 // our source might actually be a reference, in which case we shouldn't bind.
Anders Carlssonaedb46f2009-09-14 01:30:44 +00003176 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
Anders Carlssonbb4cfdf2010-07-16 21:18:37 +00003177 if (CE->getCallReturnType()->isReferenceType())
Anders Carlssonaedb46f2009-09-14 01:30:44 +00003178 return Owned(E);
Anders Carlssonbb4cfdf2010-07-16 21:18:37 +00003179 } else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
3180 if (const ObjCMethodDecl *MD = ME->getMethodDecl()) {
3181 if (MD->getResultType()->isReferenceType())
3182 return Owned(E);
3183 }
Anders Carlssonaedb46f2009-09-14 01:30:44 +00003184 }
John McCall67da35c2010-02-04 22:26:26 +00003185
3186 // That should be enough to guarantee that this type is complete.
3187 // If it has a trivial destructor, we can avoid the extra copy.
3188 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCallbdb989e2010-08-12 02:40:37 +00003189 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall67da35c2010-02-04 22:26:26 +00003190 return Owned(E);
3191
Douglas Gregore71edda2010-07-01 22:47:18 +00003192 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
Anders Carlssonc78576e2009-05-30 21:21:49 +00003193 ExprTemporaries.push_back(Temp);
Douglas Gregore71edda2010-07-01 22:47:18 +00003194 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Fariborz Jahanian67828442009-08-03 19:13:25 +00003195 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00003196 CheckDestructorAccess(E->getExprLoc(), Destructor,
3197 PDiag(diag::err_access_dtor_temp)
3198 << E->getType());
3199 }
Anders Carlsson2d4cada2009-05-30 20:36:53 +00003200 // FIXME: Add the temporary to the temporaries vector.
3201 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
3202}
3203
John McCall5d413782010-12-06 08:20:24 +00003204Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Anders Carlssonb3d05d62009-06-05 15:38:08 +00003205 assert(SubExpr && "sub expression can't be null!");
Mike Stump11289f42009-09-09 15:08:12 +00003206
Douglas Gregor580cd4a2009-12-03 17:10:37 +00003207 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3208 assert(ExprTemporaries.size() >= FirstTemporary);
3209 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlssonb3d05d62009-06-05 15:38:08 +00003210 return SubExpr;
Mike Stump11289f42009-09-09 15:08:12 +00003211
John McCall5d413782010-12-06 08:20:24 +00003212 Expr *E = ExprWithCleanups::Create(Context, SubExpr,
3213 &ExprTemporaries[FirstTemporary],
3214 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor580cd4a2009-12-03 17:10:37 +00003215 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
3216 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00003217
Anders Carlssonb3d05d62009-06-05 15:38:08 +00003218 return E;
3219}
3220
John McCalldadc5752010-08-24 06:29:42 +00003221ExprResult
John McCall5d413782010-12-06 08:20:24 +00003222Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00003223 if (SubExpr.isInvalid())
3224 return ExprError();
3225
John McCall5d413782010-12-06 08:20:24 +00003226 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00003227}
3228
John McCall5d413782010-12-06 08:20:24 +00003229Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00003230 assert(SubStmt && "sub statement can't be null!");
3231
3232 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3233 assert(ExprTemporaries.size() >= FirstTemporary);
3234 if (ExprTemporaries.size() == FirstTemporary)
3235 return SubStmt;
3236
3237 // FIXME: In order to attach the temporaries, wrap the statement into
3238 // a StmtExpr; currently this is only used for asm statements.
3239 // This is hacky, either create a new CXXStmtWithTemporaries statement or
3240 // a new AsmStmtWithTemporaries.
3241 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
3242 SourceLocation(),
3243 SourceLocation());
3244 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
3245 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00003246 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00003247}
3248
John McCalldadc5752010-08-24 06:29:42 +00003249ExprResult
John McCallb268a282010-08-23 23:25:46 +00003250Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallba7bf592010-08-24 05:47:05 +00003251 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00003252 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003253 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003254 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003255 if (Result.isInvalid()) return ExprError();
3256 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00003257
John McCallb268a282010-08-23 23:25:46 +00003258 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00003259 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003260 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00003261 // If we have a pointer to a dependent type and are using the -> operator,
3262 // the object type is the type that the pointer points to. We might still
3263 // have enough information about that type to do something useful.
3264 if (OpKind == tok::arrow)
3265 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3266 BaseType = Ptr->getPointeeType();
3267
John McCallba7bf592010-08-24 05:47:05 +00003268 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00003269 MayBePseudoDestructor = true;
John McCallb268a282010-08-23 23:25:46 +00003270 return Owned(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003271 }
Mike Stump11289f42009-09-09 15:08:12 +00003272
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003273 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00003274 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003275 // returned, with the original second operand.
3276 if (OpKind == tok::arrow) {
John McCallc1538c02009-09-30 01:01:30 +00003277 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00003278 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00003279 llvm::SmallVector<SourceLocation, 8> Locations;
John McCallbd0465b2009-09-30 01:30:54 +00003280 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc1538c02009-09-30 01:01:30 +00003281
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003282 while (BaseType->isRecordType()) {
John McCallb268a282010-08-23 23:25:46 +00003283 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
3284 if (Result.isInvalid())
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003285 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00003286 Base = Result.get();
3287 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonfbd2d492009-10-13 22:55:59 +00003288 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallb268a282010-08-23 23:25:46 +00003289 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00003290 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCallbd0465b2009-09-30 01:30:54 +00003291 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00003292 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00003293 for (unsigned i = 0; i < Locations.size(); i++)
3294 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00003295 return ExprError();
3296 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003297 }
Mike Stump11289f42009-09-09 15:08:12 +00003298
Douglas Gregore4f764f2009-11-20 19:58:21 +00003299 if (BaseType->isPointerType())
3300 BaseType = BaseType->getPointeeType();
3301 }
Mike Stump11289f42009-09-09 15:08:12 +00003302
3303 // We could end up with various non-record types here, such as extended
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003304 // vector types or Objective-C interfaces. Just return early and let
3305 // ActOnMemberReferenceExpr do the work.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00003306 if (!BaseType->isRecordType()) {
3307 // C++ [basic.lookup.classref]p2:
3308 // [...] If the type of the object expression is of pointer to scalar
3309 // type, the unqualified-id is looked up in the context of the complete
3310 // postfix-expression.
Douglas Gregore610ada2010-02-24 18:44:31 +00003311 //
3312 // This also indicates that we should be parsing a
3313 // pseudo-destructor-name.
John McCallba7bf592010-08-24 05:47:05 +00003314 ObjectType = ParsedType();
Douglas Gregore610ada2010-02-24 18:44:31 +00003315 MayBePseudoDestructor = true;
John McCallb268a282010-08-23 23:25:46 +00003316 return Owned(Base);
Douglas Gregor2b6ca462009-09-03 21:38:09 +00003317 }
Mike Stump11289f42009-09-09 15:08:12 +00003318
Douglas Gregor3fad6172009-11-17 05:17:33 +00003319 // The object type must be complete (or dependent).
3320 if (!BaseType->isDependentType() &&
3321 RequireCompleteType(OpLoc, BaseType,
3322 PDiag(diag::err_incomplete_member_access)))
3323 return ExprError();
3324
Douglas Gregor2b6ca462009-09-03 21:38:09 +00003325 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00003326 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00003327 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00003328 // type C (or of pointer to a class type C), the unqualified-id is looked
3329 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00003330 ObjectType = ParsedType::make(BaseType);
Mike Stump11289f42009-09-09 15:08:12 +00003331 return move(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00003332}
3333
John McCalldadc5752010-08-24 06:29:42 +00003334ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCallb268a282010-08-23 23:25:46 +00003335 Expr *MemExpr) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003336 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCallb268a282010-08-23 23:25:46 +00003337 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
3338 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregora771f462010-03-31 17:46:05 +00003339 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003340
3341 return ActOnCallExpr(/*Scope*/ 0,
John McCallb268a282010-08-23 23:25:46 +00003342 MemExpr,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003343 /*LPLoc*/ ExpectedLParenLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00003344 MultiExprArg(),
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003345 /*RPLoc*/ ExpectedLParenLoc);
3346}
Douglas Gregore610ada2010-02-24 18:44:31 +00003347
John McCalldadc5752010-08-24 06:29:42 +00003348ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003349 SourceLocation OpLoc,
3350 tok::TokenKind OpKind,
3351 const CXXScopeSpec &SS,
Douglas Gregor651fe5e2010-02-24 23:40:28 +00003352 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003353 SourceLocation CCLoc,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00003354 SourceLocation TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00003355 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003356 bool HasTrailingLParen) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00003357 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003358
3359 // C++ [expr.pseudo]p2:
3360 // The left-hand side of the dot operator shall be of scalar type. The
3361 // left-hand side of the arrow operator shall be of pointer to scalar type.
3362 // This scalar type is the object type.
John McCallb268a282010-08-23 23:25:46 +00003363 QualType ObjectType = Base->getType();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003364 if (OpKind == tok::arrow) {
3365 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3366 ObjectType = Ptr->getPointeeType();
John McCallb268a282010-08-23 23:25:46 +00003367 } else if (!Base->isTypeDependent()) {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003368 // The user wrote "p->" when she probably meant "p."; fix it.
3369 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3370 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00003371 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003372 if (isSFINAEContext())
3373 return ExprError();
3374
3375 OpKind = tok::period;
3376 }
3377 }
3378
3379 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
3380 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
John McCallb268a282010-08-23 23:25:46 +00003381 << ObjectType << Base->getSourceRange();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003382 return ExprError();
3383 }
3384
3385 // C++ [expr.pseudo]p2:
3386 // [...] The cv-unqualified versions of the object type and of the type
3387 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00003388 if (DestructedTypeInfo) {
3389 QualType DestructedType = DestructedTypeInfo->getType();
3390 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00003391 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregor678f90d2010-02-25 01:56:36 +00003392 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
3393 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
3394 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00003395 << ObjectType << DestructedType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00003396 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor678f90d2010-02-25 01:56:36 +00003397
3398 // Recover by setting the destructed type to the object type.
3399 DestructedType = ObjectType;
3400 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
3401 DestructedTypeStart);
3402 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3403 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003404 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00003405
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003406 // C++ [expr.pseudo]p2:
3407 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
3408 // form
3409 //
3410 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
3411 //
3412 // shall designate the same scalar type.
3413 if (ScopeTypeInfo) {
3414 QualType ScopeType = ScopeTypeInfo->getType();
3415 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00003416 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003417
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00003418 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003419 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00003420 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00003421 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003422
3423 ScopeType = QualType();
3424 ScopeTypeInfo = 0;
3425 }
3426 }
3427
John McCallb268a282010-08-23 23:25:46 +00003428 Expr *Result
3429 = new (Context) CXXPseudoDestructorExpr(Context, Base,
3430 OpKind == tok::arrow, OpLoc,
3431 SS.getScopeRep(), SS.getRange(),
3432 ScopeTypeInfo,
3433 CCLoc,
3434 TildeLoc,
3435 Destructed);
Douglas Gregor678f90d2010-02-25 01:56:36 +00003436
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003437 if (HasTrailingLParen)
John McCallb268a282010-08-23 23:25:46 +00003438 return Owned(Result);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003439
John McCallb268a282010-08-23 23:25:46 +00003440 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003441}
3442
John McCalldadc5752010-08-24 06:29:42 +00003443ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003444 SourceLocation OpLoc,
3445 tok::TokenKind OpKind,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003446 CXXScopeSpec &SS,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003447 UnqualifiedId &FirstTypeName,
3448 SourceLocation CCLoc,
3449 SourceLocation TildeLoc,
3450 UnqualifiedId &SecondTypeName,
3451 bool HasTrailingLParen) {
3452 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3453 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3454 "Invalid first type name in pseudo-destructor");
3455 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3456 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3457 "Invalid second type name in pseudo-destructor");
3458
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003459 // C++ [expr.pseudo]p2:
3460 // The left-hand side of the dot operator shall be of scalar type. The
3461 // left-hand side of the arrow operator shall be of pointer to scalar type.
3462 // This scalar type is the object type.
John McCallb268a282010-08-23 23:25:46 +00003463 QualType ObjectType = Base->getType();
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003464 if (OpKind == tok::arrow) {
3465 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3466 ObjectType = Ptr->getPointeeType();
Douglas Gregor678f90d2010-02-25 01:56:36 +00003467 } else if (!ObjectType->isDependentType()) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003468 // The user wrote "p->" when she probably meant "p."; fix it.
3469 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregor678f90d2010-02-25 01:56:36 +00003470 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00003471 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003472 if (isSFINAEContext())
3473 return ExprError();
3474
3475 OpKind = tok::period;
3476 }
3477 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00003478
3479 // Compute the object type that we should use for name lookup purposes. Only
3480 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00003481 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00003482 if (!SS.isSet()) {
John McCallba7bf592010-08-24 05:47:05 +00003483 if (const Type *T = ObjectType->getAs<RecordType>())
3484 ObjectTypePtrForLookup = ParsedType::make(QualType(T, 0));
3485 else if (ObjectType->isDependentType())
3486 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00003487 }
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003488
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003489 // Convert the name of the type being destructed (following the ~) into a
3490 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003491 QualType DestructedType;
3492 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregor678f90d2010-02-25 01:56:36 +00003493 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003494 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
John McCallba7bf592010-08-24 05:47:05 +00003495 ParsedType T = getTypeName(*SecondTypeName.Identifier,
3496 SecondTypeName.StartLocation,
3497 S, &SS, true, ObjectTypePtrForLookup);
Douglas Gregor678f90d2010-02-25 01:56:36 +00003498 if (!T &&
3499 ((SS.isSet() && !computeDeclContext(SS, false)) ||
3500 (!SS.isSet() && ObjectType->isDependentType()))) {
3501 // The name of the type being destroyed is a dependent name, and we
3502 // couldn't find anything useful in scope. Just store the identifier and
3503 // it's location, and we'll perform (qualified) name lookup again at
3504 // template instantiation time.
3505 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
3506 SecondTypeName.StartLocation);
3507 } else if (!T) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003508 Diag(SecondTypeName.StartLocation,
3509 diag::err_pseudo_dtor_destructor_non_type)
3510 << SecondTypeName.Identifier << ObjectType;
3511 if (isSFINAEContext())
3512 return ExprError();
3513
3514 // Recover by assuming we had the right type all along.
3515 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003516 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003517 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003518 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003519 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003520 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003521 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3522 TemplateId->getTemplateArgs(),
3523 TemplateId->NumArgs);
John McCall3e56fd42010-08-23 07:28:44 +00003524 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003525 TemplateId->TemplateNameLoc,
3526 TemplateId->LAngleLoc,
3527 TemplateArgsPtr,
3528 TemplateId->RAngleLoc);
3529 if (T.isInvalid() || !T.get()) {
3530 // Recover by assuming we had the right type all along.
3531 DestructedType = ObjectType;
3532 } else
3533 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003534 }
3535
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003536 // If we've performed some kind of recovery, (re-)build the type source
3537 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00003538 if (!DestructedType.isNull()) {
3539 if (!DestructedTypeInfo)
3540 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003541 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00003542 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3543 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003544
3545 // Convert the name of the scope type (the type prior to '::') into a type.
3546 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003547 QualType ScopeType;
3548 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3549 FirstTypeName.Identifier) {
3550 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
John McCallba7bf592010-08-24 05:47:05 +00003551 ParsedType T = getTypeName(*FirstTypeName.Identifier,
3552 FirstTypeName.StartLocation,
3553 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003554 if (!T) {
3555 Diag(FirstTypeName.StartLocation,
3556 diag::err_pseudo_dtor_destructor_non_type)
3557 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003558
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003559 if (isSFINAEContext())
3560 return ExprError();
3561
3562 // Just drop this type. It's unnecessary anyway.
3563 ScopeType = QualType();
3564 } else
3565 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003566 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003567 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003568 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003569 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3570 TemplateId->getTemplateArgs(),
3571 TemplateId->NumArgs);
John McCall3e56fd42010-08-23 07:28:44 +00003572 TypeResult T = ActOnTemplateIdType(TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00003573 TemplateId->TemplateNameLoc,
3574 TemplateId->LAngleLoc,
3575 TemplateArgsPtr,
3576 TemplateId->RAngleLoc);
3577 if (T.isInvalid() || !T.get()) {
3578 // Recover by dropping this type.
3579 ScopeType = QualType();
3580 } else
3581 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00003582 }
3583 }
Douglas Gregor90ad9222010-02-24 23:02:30 +00003584
3585 if (!ScopeType.isNull() && !ScopeTypeInfo)
3586 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3587 FirstTypeName.StartLocation);
3588
3589
John McCallb268a282010-08-23 23:25:46 +00003590 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00003591 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00003592 Destructed, HasTrailingLParen);
Douglas Gregore610ada2010-02-24 18:44:31 +00003593}
3594
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003595CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall16df1e52010-03-30 21:47:33 +00003596 NamedDecl *FoundDecl,
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003597 CXXMethodDecl *Method) {
John McCall16df1e52010-03-30 21:47:33 +00003598 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3599 FoundDecl, Method))
Eli Friedmanf7195532009-12-09 04:53:56 +00003600 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
3601
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003602 MemberExpr *ME =
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003603 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
John McCall7decc9e2010-11-18 06:31:45 +00003604 SourceLocation(), Method->getType(),
3605 VK_RValue, OK_Ordinary);
3606 QualType ResultType = Method->getResultType();
3607 ExprValueKind VK = Expr::getValueKindForType(ResultType);
3608 ResultType = ResultType.getNonLValueExprType(Context);
3609
Douglas Gregor27381f32009-11-23 12:27:39 +00003610 MarkDeclarationReferenced(Exp->getLocStart(), Method);
3611 CXXMemberCallExpr *CE =
John McCall7decc9e2010-11-18 06:31:45 +00003612 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
Douglas Gregor27381f32009-11-23 12:27:39 +00003613 Exp->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00003614 return CE;
3615}
3616
Sebastian Redl4202c0f2010-09-10 20:55:43 +00003617ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
3618 SourceLocation RParen) {
Sebastian Redl4202c0f2010-09-10 20:55:43 +00003619 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
3620 Operand->CanThrow(Context),
3621 KeyLoc, RParen));
3622}
3623
3624ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
3625 Expr *Operand, SourceLocation RParen) {
3626 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00003627}
3628
John McCall34376a62010-12-04 03:47:34 +00003629/// Perform the conversions required for an expression used in a
3630/// context that ignores the result.
3631void Sema::IgnoredValueConversions(Expr *&E) {
John McCallfee942d2010-12-02 02:07:15 +00003632 // C99 6.3.2.1:
3633 // [Except in specific positions,] an lvalue that does not have
3634 // array type is converted to the value stored in the
3635 // designated object (and is no longer an lvalue).
John McCall34376a62010-12-04 03:47:34 +00003636 if (E->isRValue()) return;
John McCallfee942d2010-12-02 02:07:15 +00003637
John McCall34376a62010-12-04 03:47:34 +00003638 // We always want to do this on ObjC property references.
3639 if (E->getObjectKind() == OK_ObjCProperty) {
3640 ConvertPropertyForRValue(E);
3641 if (E->isRValue()) return;
3642 }
3643
3644 // Otherwise, this rule does not apply in C++, at least not for the moment.
3645 if (getLangOptions().CPlusPlus) return;
3646
3647 // GCC seems to also exclude expressions of incomplete enum type.
3648 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
3649 if (!T->getDecl()->isComplete()) {
3650 // FIXME: stupid workaround for a codegen bug!
3651 ImpCastExprToType(E, Context.VoidTy, CK_ToVoid);
3652 return;
3653 }
3654 }
3655
3656 DefaultFunctionArrayLvalueConversion(E);
John McCallca61b652010-12-04 12:29:11 +00003657 if (!E->getType()->isVoidType())
3658 RequireCompleteType(E->getExprLoc(), E->getType(),
3659 diag::err_incomplete_type);
John McCall34376a62010-12-04 03:47:34 +00003660}
3661
3662ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) {
Douglas Gregora6e053e2010-12-15 01:34:56 +00003663 if (!FullExpr)
3664 return ExprError();
John McCall34376a62010-12-04 03:47:34 +00003665
Douglas Gregor506bd562010-12-13 22:49:22 +00003666 if (DiagnoseUnexpandedParameterPack(FullExpr))
3667 return ExprError();
3668
John McCall34376a62010-12-04 03:47:34 +00003669 IgnoredValueConversions(FullExpr);
John McCallacf0ee52010-10-08 02:01:28 +00003670 CheckImplicitConversions(FullExpr);
John McCall5d413782010-12-06 08:20:24 +00003671 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00003672}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00003673
3674StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
3675 if (!FullStmt) return StmtError();
3676
John McCall5d413782010-12-06 08:20:24 +00003677 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00003678}