blob: 5a2a827230852df0d46a9856ca4f5d72144600b6 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall2a7fb272010-08-25 05:32:35 +000015#include "clang/Sema/DeclSpec.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/ParsedTemplate.h"
John McCall469a1eb2011-02-02 13:00:07 +000019#include "clang/Sema/ScopeInfo.h"
Richard Smith7a614d82011-06-11 17:19:42 +000020#include "clang/Sema/Scope.h"
John McCall2a7fb272010-08-25 05:32:35 +000021#include "clang/Sema/TemplateDeduction.h"
Steve Naroff210679c2007-08-25 14:02:58 +000022#include "clang/AST/ASTContext.h"
Nick Lewyckyfca84b22012-01-24 21:15:41 +000023#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000024#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000025#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000026#include "clang/AST/ExprCXX.h"
Fariborz Jahaniand4266622010-06-16 18:56:04 +000027#include "clang/AST/ExprObjC.h"
Douglas Gregorb57fb492010-02-24 22:38:50 +000028#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000029#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000030#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000031#include "clang/Lex/Preprocessor.h"
David Blaikie91ec7892011-12-16 16:03:09 +000032#include "TypeLocBuilder.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000033#include "llvm/ADT/STLExtras.h"
Chandler Carruth73e0a912011-05-01 07:23:17 +000034#include "llvm/Support/ErrorHandling.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000035using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000036using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000037
John McCallb3d87482010-08-24 05:47:05 +000038ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000039 IdentifierInfo &II,
John McCallb3d87482010-08-24 05:47:05 +000040 SourceLocation NameLoc,
41 Scope *S, CXXScopeSpec &SS,
42 ParsedType ObjectTypePtr,
43 bool EnteringContext) {
Douglas Gregor124b8782010-02-16 19:09:40 +000044 // Determine where to perform name lookup.
45
46 // FIXME: This area of the standard is very messy, and the current
47 // wording is rather unclear about which scopes we search for the
48 // destructor name; see core issues 399 and 555. Issue 399 in
49 // particular shows where the current description of destructor name
50 // lookup is completely out of line with existing practice, e.g.,
51 // this appears to be ill-formed:
52 //
53 // namespace N {
54 // template <typename T> struct S {
55 // ~S();
56 // };
57 // }
58 //
59 // void f(N::S<int>* s) {
60 // s->N::S<int>::~S();
61 // }
62 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000063 // See also PR6358 and PR6359.
Sebastian Redlc0fee502010-07-07 23:17:38 +000064 // For this reason, we're currently only doing the C++03 version of this
65 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregor124b8782010-02-16 19:09:40 +000066 QualType SearchType;
67 DeclContext *LookupCtx = 0;
68 bool isDependent = false;
69 bool LookInScope = false;
70
71 // If we have an object type, it's because we are in a
72 // pseudo-destructor-expression or a member access expression, and
73 // we know what type we're looking for.
74 if (ObjectTypePtr)
75 SearchType = GetTypeFromParser(ObjectTypePtr);
76
77 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000078 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000079
Douglas Gregor93649fd2010-02-23 00:15:22 +000080 bool AlreadySearched = false;
81 bool LookAtPrefix = true;
Sebastian Redlc0fee502010-07-07 23:17:38 +000082 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000083 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redlc0fee502010-07-07 23:17:38 +000084 // the type-names are looked up as types in the scope designated by the
85 // nested-name-specifier. In a qualified-id of the form:
NAKAMURA Takumi00995302011-01-27 07:09:49 +000086 //
87 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redlc0fee502010-07-07 23:17:38 +000088 //
89 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth5e895a82010-02-21 10:19:54 +000090 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +000091 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +000092 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregor124b8782010-02-16 19:09:40 +000093 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000094 // the class-names are looked up as types in the scope designated by
Sebastian Redlc0fee502010-07-07 23:17:38 +000095 // the nested-name-specifier.
Douglas Gregor124b8782010-02-16 19:09:40 +000096 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000097 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000098 // code below is permitted to look at the prefix of the
Sebastian Redlc0fee502010-07-07 23:17:38 +000099 // nested-name-specifier.
100 DeclContext *DC = computeDeclContext(SS, EnteringContext);
101 if (DC && DC->isFileContext()) {
102 AlreadySearched = true;
103 LookupCtx = DC;
104 isDependent = false;
105 } else if (DC && isa<CXXRecordDecl>(DC))
106 LookAtPrefix = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000107
Sebastian Redlc0fee502010-07-07 23:17:38 +0000108 // The second case from the C++03 rules quoted further above.
Douglas Gregor93649fd2010-02-23 00:15:22 +0000109 NestedNameSpecifier *Prefix = 0;
110 if (AlreadySearched) {
111 // Nothing left to do.
112 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
113 CXXScopeSpec PrefixSS;
Douglas Gregor7e384942011-02-25 16:07:42 +0000114 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor93649fd2010-02-23 00:15:22 +0000115 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
116 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000117 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000118 LookupCtx = computeDeclContext(SearchType);
119 isDependent = SearchType->isDependentType();
120 } else {
121 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000122 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000123 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000124
Douglas Gregoredc90502010-02-25 04:46:04 +0000125 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000126 } else if (ObjectTypePtr) {
127 // C++ [basic.lookup.classref]p3:
128 // If the unqualified-id is ~type-name, the type-name is looked up
129 // in the context of the entire postfix-expression. If the type T
130 // of the object expression is of a class type C, the type-name is
131 // also looked up in the scope of class C. At least one of the
132 // lookups shall find a name that refers to (possibly
133 // cv-qualified) T.
134 LookupCtx = computeDeclContext(SearchType);
135 isDependent = SearchType->isDependentType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000136 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregor124b8782010-02-16 19:09:40 +0000137 "Caller should have completed object type");
138
139 LookInScope = true;
140 } else {
141 // Perform lookup into the current scope (only).
142 LookInScope = true;
143 }
144
Douglas Gregor7ec18732011-03-04 22:32:08 +0000145 TypeDecl *NonMatchingTypeDecl = 0;
Douglas Gregor124b8782010-02-16 19:09:40 +0000146 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
147 for (unsigned Step = 0; Step != 2; ++Step) {
148 // Look for the name first in the computed lookup context (if we
Douglas Gregor7ec18732011-03-04 22:32:08 +0000149 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregor124b8782010-02-16 19:09:40 +0000150 // we're allowed to look there).
151 Found.clear();
152 if (Step == 0 && LookupCtx)
153 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000154 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000155 LookupName(Found, S);
156 else
157 continue;
158
159 // FIXME: Should we be suppressing ambiguities here?
160 if (Found.isAmbiguous())
John McCallb3d87482010-08-24 05:47:05 +0000161 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000162
163 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
164 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000165
166 if (SearchType.isNull() || SearchType->isDependentType() ||
167 Context.hasSameUnqualifiedType(T, SearchType)) {
168 // We found our type!
169
John McCallb3d87482010-08-24 05:47:05 +0000170 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000171 }
John Wiegley36784e72011-03-08 08:13:22 +0000172
Douglas Gregor7ec18732011-03-04 22:32:08 +0000173 if (!SearchType.isNull())
174 NonMatchingTypeDecl = Type;
Douglas Gregor124b8782010-02-16 19:09:40 +0000175 }
176
177 // If the name that we found is a class template name, and it is
178 // the same name as the template name in the last part of the
179 // nested-name-specifier (if present) or the object type, then
180 // this is the destructor for that class.
181 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000182 // issue 399, for which there isn't even an obvious direction.
Douglas Gregor124b8782010-02-16 19:09:40 +0000183 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
184 QualType MemberOfType;
185 if (SS.isSet()) {
186 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
187 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000188 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
189 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000190 }
191 }
192 if (MemberOfType.isNull())
193 MemberOfType = SearchType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000194
Douglas Gregor124b8782010-02-16 19:09:40 +0000195 if (MemberOfType.isNull())
196 continue;
197
198 // We're referring into a class template specialization. If the
199 // class template we found is the same as the template being
200 // specialized, we found what we are looking for.
201 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
202 if (ClassTemplateSpecializationDecl *Spec
203 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
204 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
205 Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000206 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000207 }
208
209 continue;
210 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000211
Douglas Gregor124b8782010-02-16 19:09:40 +0000212 // We're referring to an unresolved class template
213 // specialization. Determine whether we class template we found
214 // is the same as the template being specialized or, if we don't
215 // know which template is being specialized, that it at least
216 // has the same name.
217 if (const TemplateSpecializationType *SpecType
218 = MemberOfType->getAs<TemplateSpecializationType>()) {
219 TemplateName SpecName = SpecType->getTemplateName();
220
221 // The class template we found is the same template being
222 // specialized.
223 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
224 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000225 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000226
227 continue;
228 }
229
230 // The class template we found has the same name as the
231 // (dependent) template name being specialized.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000232 if (DependentTemplateName *DepTemplate
Douglas Gregor124b8782010-02-16 19:09:40 +0000233 = SpecName.getAsDependentTemplateName()) {
234 if (DepTemplate->isIdentifier() &&
235 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallb3d87482010-08-24 05:47:05 +0000236 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000237
238 continue;
239 }
240 }
241 }
242 }
243
244 if (isDependent) {
245 // We didn't find our type, but that's okay: it's dependent
246 // anyway.
Douglas Gregore29425b2011-02-28 22:42:13 +0000247
248 // FIXME: What if we have no nested-name-specifier?
249 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
250 SS.getWithLocInContext(Context),
251 II, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000252 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000253 }
254
Douglas Gregor7ec18732011-03-04 22:32:08 +0000255 if (NonMatchingTypeDecl) {
256 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
257 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
258 << T << SearchType;
259 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
260 << T;
261 } else if (ObjectTypePtr)
262 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000263 << &II;
Douglas Gregor124b8782010-02-16 19:09:40 +0000264 else
265 Diag(NameLoc, diag::err_destructor_class_name);
266
John McCallb3d87482010-08-24 05:47:05 +0000267 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000268}
269
David Blaikie53a75c02011-12-08 16:13:53 +0000270ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
David Blaikie4db8c442011-12-12 04:13:55 +0000271 if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
David Blaikie53a75c02011-12-08 16:13:53 +0000272 return ParsedType();
273 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
274 && "only get destructor types from declspecs");
275 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
276 QualType SearchType = GetTypeFromParser(ObjectType);
277 if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
278 return ParsedType::make(T);
279 }
280
281 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
282 << T << SearchType;
283 return ParsedType();
284}
285
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000286/// \brief Build a C++ typeid expression with a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000287ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000288 SourceLocation TypeidLoc,
289 TypeSourceInfo *Operand,
290 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000291 // C++ [expr.typeid]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000292 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000293 // that is the operand of typeid are always ignored.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000294 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000295 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000296 Qualifiers Quals;
297 QualType T
298 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
299 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000300 if (T->getAs<RecordType>() &&
301 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
302 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000303
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000304 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
305 Operand,
306 SourceRange(TypeidLoc, RParenLoc)));
307}
308
309/// \brief Build a C++ typeid expression with an expression operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000310ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000311 SourceLocation TypeidLoc,
312 Expr *E,
313 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000314 if (E && !E->isTypeDependent()) {
John McCall6dbba4f2011-10-11 23:14:30 +0000315 if (E->getType()->isPlaceholderType()) {
316 ExprResult result = CheckPlaceholderExpr(E);
317 if (result.isInvalid()) return ExprError();
318 E = result.take();
319 }
320
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000321 QualType T = E->getType();
322 if (const RecordType *RecordT = T->getAs<RecordType>()) {
323 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
324 // C++ [expr.typeid]p3:
325 // [...] If the type of the expression is a class type, the class
326 // shall be completely-defined.
327 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
328 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000329
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000330 // C++ [expr.typeid]p3:
Sebastian Redl906082e2010-07-20 04:20:21 +0000331 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000332 // polymorphic class type [...] [the] expression is an unevaluated
333 // operand. [...]
Sebastian Redl906082e2010-07-20 04:20:21 +0000334 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Eli Friedmanef331b72012-01-20 01:26:23 +0000335 // The subexpression is potentially evaluated; switch the context
336 // and recheck the subexpression.
337 ExprResult Result = TranformToPotentiallyEvaluated(E);
338 if (Result.isInvalid()) return ExprError();
339 E = Result.take();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000340
341 // We require a vtable to query the type at run time.
342 MarkVTableUsed(TypeidLoc, RecordD);
343 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000344 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000345
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000346 // C++ [expr.typeid]p4:
347 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000348 // cv-qualified type, the result of the typeid expression refers to a
349 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000350 // type.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000351 Qualifiers Quals;
352 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
353 if (!Context.hasSameType(T, UnqualT)) {
354 T = UnqualT;
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +0000355 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take();
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000356 }
357 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000358
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000359 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCall9ae2f072010-08-23 23:25:46 +0000360 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000361 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000362}
363
364/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCall60d7b3a2010-08-24 06:29:42 +0000365ExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000366Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
367 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000368 // Find the std::type_info type.
Sebastian Redlce0682f2011-03-31 19:29:24 +0000369 if (!getStdNamespace())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000370 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000371
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000372 if (!CXXTypeInfoDecl) {
373 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
374 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
375 LookupQualifiedName(R, getStdNamespace());
376 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
377 if (!CXXTypeInfoDecl)
378 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
379 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000380
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000381 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000382
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000383 if (isType) {
384 // The operand is a type; handle it as such.
385 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +0000386 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
387 &TInfo);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000388 if (T.isNull())
389 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000390
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000391 if (!TInfo)
392 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000393
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000394 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000395 }
Mike Stump1eb44332009-09-09 15:08:12 +0000396
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000397 // The operand is an expression.
John McCall9ae2f072010-08-23 23:25:46 +0000398 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000399}
400
Francois Pichet6915c522010-12-27 01:32:00 +0000401/// Retrieve the UuidAttr associated with QT.
402static UuidAttr *GetUuidAttrOfType(QualType QT) {
403 // Optionally remove one level of pointer, reference or array indirection.
John McCallf4c73712011-01-19 06:33:43 +0000404 const Type *Ty = QT.getTypePtr();;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000405 if (QT->isPointerType() || QT->isReferenceType())
406 Ty = QT->getPointeeType().getTypePtr();
407 else if (QT->isArrayType())
408 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
409
Francois Pichet8db75a22011-05-08 10:02:20 +0000410 // Loop all record redeclaration looking for an uuid attribute.
Francois Pichet6915c522010-12-27 01:32:00 +0000411 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Francois Pichet8db75a22011-05-08 10:02:20 +0000412 for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(),
413 E = RD->redecls_end(); I != E; ++I) {
414 if (UuidAttr *Uuid = I->getAttr<UuidAttr>())
Francois Pichet6915c522010-12-27 01:32:00 +0000415 return Uuid;
Francois Pichet6915c522010-12-27 01:32:00 +0000416 }
Francois Pichet8db75a22011-05-08 10:02:20 +0000417
Francois Pichet6915c522010-12-27 01:32:00 +0000418 return 0;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000419}
420
Francois Pichet01b7c302010-09-08 12:20:18 +0000421/// \brief Build a Microsoft __uuidof expression with a type operand.
422ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
423 SourceLocation TypeidLoc,
424 TypeSourceInfo *Operand,
425 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000426 if (!Operand->getType()->isDependentType()) {
427 if (!GetUuidAttrOfType(Operand->getType()))
428 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
429 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000430
Francois Pichet01b7c302010-09-08 12:20:18 +0000431 // FIXME: add __uuidof semantic analysis for type operand.
432 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
433 Operand,
434 SourceRange(TypeidLoc, RParenLoc)));
435}
436
437/// \brief Build a Microsoft __uuidof expression with an expression operand.
438ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
439 SourceLocation TypeidLoc,
440 Expr *E,
441 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000442 if (!E->getType()->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000443 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichet6915c522010-12-27 01:32:00 +0000444 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
445 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
446 }
447 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet01b7c302010-09-08 12:20:18 +0000448 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
449 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000450 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet01b7c302010-09-08 12:20:18 +0000451}
452
453/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
454ExprResult
455Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
456 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000457 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet01b7c302010-09-08 12:20:18 +0000458 if (!MSVCGuidDecl) {
459 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
460 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
461 LookupQualifiedName(R, Context.getTranslationUnitDecl());
462 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
463 if (!MSVCGuidDecl)
464 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000465 }
466
Francois Pichet01b7c302010-09-08 12:20:18 +0000467 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000468
Francois Pichet01b7c302010-09-08 12:20:18 +0000469 if (isType) {
470 // The operand is a type; handle it as such.
471 TypeSourceInfo *TInfo = 0;
472 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
473 &TInfo);
474 if (T.isNull())
475 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000476
Francois Pichet01b7c302010-09-08 12:20:18 +0000477 if (!TInfo)
478 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
479
480 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
481 }
482
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000483 // The operand is an expression.
Francois Pichet01b7c302010-09-08 12:20:18 +0000484 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
485}
486
Steve Naroff1b273c42007-09-16 14:56:35 +0000487/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCall60d7b3a2010-08-24 06:29:42 +0000488ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000489Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000490 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000491 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000492 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
493 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000494}
Chris Lattner50dd2892008-02-26 00:51:44 +0000495
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000496/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCall60d7b3a2010-08-24 06:29:42 +0000497ExprResult
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000498Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
499 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
500}
501
Chris Lattner50dd2892008-02-26 00:51:44 +0000502/// ActOnCXXThrow - Parse throw expressions.
John McCall60d7b3a2010-08-24 06:29:42 +0000503ExprResult
Douglas Gregorbca01b42011-07-06 22:04:06 +0000504Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
505 bool IsThrownVarInScope = false;
506 if (Ex) {
507 // C++0x [class.copymove]p31:
508 // When certain criteria are met, an implementation is allowed to omit the
509 // copy/move construction of a class object [...]
510 //
511 // - in a throw-expression, when the operand is the name of a
512 // non-volatile automatic object (other than a function or catch-
513 // clause parameter) whose scope does not extend beyond the end of the
514 // innermost enclosing try-block (if there is one), the copy/move
515 // operation from the operand to the exception object (15.1) can be
516 // omitted by constructing the automatic object directly into the
517 // exception object
518 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
519 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
520 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
521 for( ; S; S = S->getParent()) {
522 if (S->isDeclScope(Var)) {
523 IsThrownVarInScope = true;
524 break;
525 }
526
527 if (S->getFlags() &
528 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
529 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
530 Scope::TryScope))
531 break;
532 }
533 }
534 }
535 }
536
537 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
538}
539
540ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
541 bool IsThrownVarInScope) {
Anders Carlsson729b8532011-02-23 03:46:46 +0000542 // Don't report an error if 'throw' is used in system headers.
Anders Carlsson15348ae2011-02-28 02:27:16 +0000543 if (!getLangOptions().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +0000544 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb1fba312011-02-19 21:53:09 +0000545 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Douglas Gregorbca01b42011-07-06 22:04:06 +0000546
John Wiegley429bb272011-04-08 18:41:53 +0000547 if (Ex && !Ex->isTypeDependent()) {
Douglas Gregorbca01b42011-07-06 22:04:06 +0000548 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
John Wiegley429bb272011-04-08 18:41:53 +0000549 if (ExRes.isInvalid())
550 return ExprError();
551 Ex = ExRes.take();
552 }
Douglas Gregorbca01b42011-07-06 22:04:06 +0000553
554 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
555 IsThrownVarInScope));
Sebastian Redl972041f2009-04-27 20:27:31 +0000556}
557
558/// CheckCXXThrowOperand - Validate the operand of a throw.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000559ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
560 bool IsThrownVarInScope) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000561 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000562 // A throw-expression initializes a temporary object, called the exception
563 // object, the type of which is determined by removing any top-level
564 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000565 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor154fe982009-12-23 22:04:40 +0000566 // or "pointer to function returning T", [...]
567 if (E->getType().hasQualifiers())
John Wiegley429bb272011-04-08 18:41:53 +0000568 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +0000569 E->getValueKind()).take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000570
John Wiegley429bb272011-04-08 18:41:53 +0000571 ExprResult Res = DefaultFunctionArrayConversion(E);
572 if (Res.isInvalid())
573 return ExprError();
574 E = Res.take();
Sebastian Redl972041f2009-04-27 20:27:31 +0000575
576 // If the type of the exception would be an incomplete type or a pointer
577 // to an incomplete type other than (cv) void the program is ill-formed.
578 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000579 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000580 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000581 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000582 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000583 }
584 if (!isPointer || !Ty->isVoidType()) {
585 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000586 PDiag(isPointer ? diag::err_throw_incomplete_ptr
587 : diag::err_throw_incomplete)
588 << E->getSourceRange()))
John Wiegley429bb272011-04-08 18:41:53 +0000589 return ExprError();
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000590
Douglas Gregorbf422f92010-04-15 18:05:39 +0000591 if (RequireNonAbstractType(ThrowLoc, E->getType(),
592 PDiag(diag::err_throw_abstract_type)
593 << E->getSourceRange()))
John Wiegley429bb272011-04-08 18:41:53 +0000594 return ExprError();
Sebastian Redl972041f2009-04-27 20:27:31 +0000595 }
596
John McCallac418162010-04-22 01:10:34 +0000597 // Initialize the exception result. This implicitly weeds out
598 // abstract types or types with inaccessible copy constructors.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000599
600 // C++0x [class.copymove]p31:
601 // When certain criteria are met, an implementation is allowed to omit the
602 // copy/move construction of a class object [...]
603 //
604 // - in a throw-expression, when the operand is the name of a
605 // non-volatile automatic object (other than a function or catch-clause
606 // parameter) whose scope does not extend beyond the end of the
607 // innermost enclosing try-block (if there is one), the copy/move
608 // operation from the operand to the exception object (15.1) can be
609 // omitted by constructing the automatic object directly into the
610 // exception object
611 const VarDecl *NRVOVariable = 0;
612 if (IsThrownVarInScope)
613 NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
614
John McCallac418162010-04-22 01:10:34 +0000615 InitializedEntity Entity =
Douglas Gregor72dfa272011-01-21 22:46:35 +0000616 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
Douglas Gregorbca01b42011-07-06 22:04:06 +0000617 /*NRVO=*/NRVOVariable != 0);
John Wiegley429bb272011-04-08 18:41:53 +0000618 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregorbca01b42011-07-06 22:04:06 +0000619 QualType(), E,
620 IsThrownVarInScope);
John McCallac418162010-04-22 01:10:34 +0000621 if (Res.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000622 return ExprError();
623 E = Res.take();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000624
Eli Friedman5ed9b932010-06-03 20:39:03 +0000625 // If the exception has class type, we need additional handling.
626 const RecordType *RecordTy = Ty->getAs<RecordType>();
627 if (!RecordTy)
John Wiegley429bb272011-04-08 18:41:53 +0000628 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000629 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
630
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000631 // If we are throwing a polymorphic class type or pointer thereof,
632 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000633 MarkVTableUsed(ThrowLoc, RD);
634
Eli Friedman98efb9f2010-10-12 20:32:36 +0000635 // If a pointer is thrown, the referenced object will not be destroyed.
636 if (isPointer)
John Wiegley429bb272011-04-08 18:41:53 +0000637 return Owned(E);
Eli Friedman98efb9f2010-10-12 20:32:36 +0000638
Eli Friedman5ed9b932010-06-03 20:39:03 +0000639 // If the class has a non-trivial destructor, we must be able to call it.
640 if (RD->hasTrivialDestructor())
John Wiegley429bb272011-04-08 18:41:53 +0000641 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000642
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000643 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +0000644 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
Eli Friedman5ed9b932010-06-03 20:39:03 +0000645 if (!Destructor)
John Wiegley429bb272011-04-08 18:41:53 +0000646 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000647
Eli Friedman5f2987c2012-02-02 03:46:19 +0000648 MarkFunctionReferenced(E->getExprLoc(), Destructor);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000649 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000650 PDiag(diag::err_access_dtor_exception) << Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000651 return Owned(E);
Chris Lattner50dd2892008-02-26 00:51:44 +0000652}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000653
Eli Friedman72899c32012-01-07 04:59:52 +0000654QualType Sema::getCurrentThisType() {
655 DeclContext *DC = getFunctionLevelDeclContext();
Richard Smith7a614d82011-06-11 17:19:42 +0000656 QualType ThisTy;
657 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
658 if (method && method->isInstance())
659 ThisTy = method->getThisType(Context);
660 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
661 // C++0x [expr.prim]p4:
662 // Otherwise, if a member-declarator declares a non-static data member
663 // of a class X, the expression this is a prvalue of type "pointer to X"
664 // within the optional brace-or-equal-initializer.
665 Scope *S = getScopeForContext(DC);
666 if (!S || S->getFlags() & Scope::ThisScope)
667 ThisTy = Context.getPointerType(Context.getRecordType(RD));
668 }
John McCall469a1eb2011-02-02 13:00:07 +0000669
Richard Smith7a614d82011-06-11 17:19:42 +0000670 return ThisTy;
John McCall5808ce42011-02-03 08:15:49 +0000671}
672
Douglas Gregora1f21142012-02-01 17:04:21 +0000673void Sema::CheckCXXThisCapture(SourceLocation Loc, bool Explicit) {
Eli Friedman72899c32012-01-07 04:59:52 +0000674 // We don't need to capture this in an unevaluated context.
Douglas Gregora1f21142012-02-01 17:04:21 +0000675 if (ExprEvalContexts.back().Context == Unevaluated && !Explicit)
Eli Friedman72899c32012-01-07 04:59:52 +0000676 return;
677
678 // Otherwise, check that we can capture 'this'.
679 unsigned NumClosures = 0;
680 for (unsigned idx = FunctionScopes.size() - 1; idx != 0; idx--) {
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000681 if (CapturingScopeInfo *CSI =
682 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
683 if (CSI->CXXThisCaptureIndex != 0) {
684 // 'this' is already being captured; there isn't anything more to do.
Eli Friedman72899c32012-01-07 04:59:52 +0000685 break;
686 }
Douglas Gregora1f21142012-02-01 17:04:21 +0000687
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000688 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000689 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregora1f21142012-02-01 17:04:21 +0000690 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
691 Explicit) {
692 // This closure can capture 'this'; continue looking upwards.
Eli Friedman72899c32012-01-07 04:59:52 +0000693 NumClosures++;
Douglas Gregora1f21142012-02-01 17:04:21 +0000694 Explicit = false;
Eli Friedman72899c32012-01-07 04:59:52 +0000695 continue;
696 }
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000697 // This context can't implicitly capture 'this'; fail out.
Douglas Gregora1f21142012-02-01 17:04:21 +0000698 Diag(Loc, diag::err_this_capture) << Explicit;
Eli Friedman72899c32012-01-07 04:59:52 +0000699 return;
700 }
Eli Friedman72899c32012-01-07 04:59:52 +0000701 break;
702 }
703
704 // Mark that we're implicitly capturing 'this' in all the scopes we skipped.
705 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
706 // contexts.
707 for (unsigned idx = FunctionScopes.size() - 1;
708 NumClosures; --idx, --NumClosures) {
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000709 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
710 bool isNested = NumClosures > 1;
Douglas Gregor93962e52012-02-01 01:18:43 +0000711 CSI->AddThisCapture(isNested, Loc);
Eli Friedman72899c32012-01-07 04:59:52 +0000712 }
713}
714
Richard Smith7a614d82011-06-11 17:19:42 +0000715ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCall5808ce42011-02-03 08:15:49 +0000716 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
717 /// is a non-lvalue expression whose value is the address of the object for
718 /// which the function is called.
719
Douglas Gregor341350e2011-10-18 16:47:30 +0000720 QualType ThisTy = getCurrentThisType();
Richard Smith7a614d82011-06-11 17:19:42 +0000721 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCall5808ce42011-02-03 08:15:49 +0000722
Eli Friedman72899c32012-01-07 04:59:52 +0000723 CheckCXXThisCapture(Loc);
Richard Smith7a614d82011-06-11 17:19:42 +0000724 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000725}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000726
John McCall60d7b3a2010-08-24 06:29:42 +0000727ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000728Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000729 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000730 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000731 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000732 if (!TypeRep)
733 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000734
John McCall9d125032010-01-15 18:39:57 +0000735 TypeSourceInfo *TInfo;
736 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
737 if (!TInfo)
738 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000739
740 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
741}
742
743/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
744/// Can be interpreted either as function-style casting ("int(x)")
745/// or class type construction ("ClassType(x,y,z)")
746/// or creation of a value-initialized type ("int()").
747ExprResult
748Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
749 SourceLocation LParenLoc,
750 MultiExprArg exprs,
751 SourceLocation RParenLoc) {
752 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000753 unsigned NumExprs = exprs.size();
754 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000755 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000756 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
757
Sebastian Redlf53597f2009-03-15 17:47:39 +0000758 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000759 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000760 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Douglas Gregorab6677e2010-09-08 00:15:04 +0000762 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000763 LParenLoc,
764 Exprs, NumExprs,
765 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000766 }
767
Anders Carlssonbb60a502009-08-27 03:53:50 +0000768 if (Ty->isArrayType())
769 return ExprError(Diag(TyBeginLoc,
770 diag::err_value_init_for_array_type) << FullRange);
771 if (!Ty->isVoidType() &&
772 RequireCompleteType(TyBeginLoc, Ty,
773 PDiag(diag::err_invalid_incomplete_type_use)
774 << FullRange))
775 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000776
Anders Carlssonbb60a502009-08-27 03:53:50 +0000777 if (RequireNonAbstractType(TyBeginLoc, Ty,
778 diag::err_allocation_of_abstract_type))
779 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000780
781
Douglas Gregor506ae412009-01-16 18:33:17 +0000782 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000783 // If the expression list is a single expression, the type conversion
784 // expression is equivalent (in definedness, and if defined in meaning) to the
785 // corresponding cast expression.
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000786 if (NumExprs == 1) {
John McCallb45ae252011-10-05 07:41:44 +0000787 Expr *Arg = Exprs[0];
Anders Carlsson0aebc812009-09-09 21:33:21 +0000788 exprs.release();
John McCallb45ae252011-10-05 07:41:44 +0000789 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000790 }
791
Douglas Gregor19311e72010-09-08 21:40:08 +0000792 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
793 InitializationKind Kind
794 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
795 LParenLoc, RParenLoc)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000796 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor19311e72010-09-08 21:40:08 +0000797 LParenLoc, RParenLoc);
798 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
799 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000800
Douglas Gregor19311e72010-09-08 21:40:08 +0000801 // FIXME: Improve AST representation?
802 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000803}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000804
John McCall6ec278d2011-01-27 09:37:56 +0000805/// doesUsualArrayDeleteWantSize - Answers whether the usual
806/// operator delete[] for the given type has a size_t parameter.
807static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
808 QualType allocType) {
809 const RecordType *record =
810 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
811 if (!record) return false;
812
813 // Try to find an operator delete[] in class scope.
814
815 DeclarationName deleteName =
816 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
817 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
818 S.LookupQualifiedName(ops, record->getDecl());
819
820 // We're just doing this for information.
821 ops.suppressDiagnostics();
822
823 // Very likely: there's no operator delete[].
824 if (ops.empty()) return false;
825
826 // If it's ambiguous, it should be illegal to call operator delete[]
827 // on this thing, so it doesn't matter if we allocate extra space or not.
828 if (ops.isAmbiguous()) return false;
829
830 LookupResult::Filter filter = ops.makeFilter();
831 while (filter.hasNext()) {
832 NamedDecl *del = filter.next()->getUnderlyingDecl();
833
834 // C++0x [basic.stc.dynamic.deallocation]p2:
835 // A template instance is never a usual deallocation function,
836 // regardless of its signature.
837 if (isa<FunctionTemplateDecl>(del)) {
838 filter.erase();
839 continue;
840 }
841
842 // C++0x [basic.stc.dynamic.deallocation]p2:
843 // If class T does not declare [an operator delete[] with one
844 // parameter] but does declare a member deallocation function
845 // named operator delete[] with exactly two parameters, the
846 // second of which has type std::size_t, then this function
847 // is a usual deallocation function.
848 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
849 filter.erase();
850 continue;
851 }
852 }
853 filter.done();
854
855 if (!ops.isSingleResult()) return false;
856
857 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
858 return (del->getNumParams() == 2);
859}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000860
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000861/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
862/// @code new (memory) int[size][4] @endcode
863/// or
864/// @code ::new Foo(23, "hello") @endcode
865/// For the interpretation of this heap of arguments, consult the base version.
John McCall60d7b3a2010-08-24 06:29:42 +0000866ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000867Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000868 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000869 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000870 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000871 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000872 SourceLocation ConstructorRParen) {
Richard Smith34b41d92011-02-20 03:19:35 +0000873 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
874
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000875 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000876 // If the specified type is an array, unwrap it and save the expression.
877 if (D.getNumTypeObjects() > 0 &&
878 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
879 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith34b41d92011-02-20 03:19:35 +0000880 if (TypeContainsAuto)
881 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
882 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000883 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000884 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
885 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000886 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000887 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
888 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000889
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000890 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000891 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000892 }
893
Douglas Gregor043cad22009-09-11 00:18:58 +0000894 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000895 if (ArraySize) {
896 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000897 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
898 break;
899
900 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
901 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smith282e7e62012-02-04 09:53:13 +0000902 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
903 Array.NumElts = VerifyIntegerConstantExpression(NumElts, 0,
904 PDiag(diag::err_new_array_nonconst)).take();
905 if (!Array.NumElts)
906 return ExprError();
Douglas Gregor043cad22009-09-11 00:18:58 +0000907 }
908 }
909 }
910 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000911
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +0000912 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
John McCallbf1a0282010-06-04 23:28:52 +0000913 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000914 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000915 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000916
Mike Stump1eb44332009-09-09 15:08:12 +0000917 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000918 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000919 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000920 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000921 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000922 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000923 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000924 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000925 ConstructorLParen,
926 move(ConstructorArgs),
Richard Smith34b41d92011-02-20 03:19:35 +0000927 ConstructorRParen,
928 TypeContainsAuto);
Douglas Gregor3433cf72009-05-21 00:00:09 +0000929}
930
John McCall60d7b3a2010-08-24 06:29:42 +0000931ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000932Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
933 SourceLocation PlacementLParen,
934 MultiExprArg PlacementArgs,
935 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000936 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000937 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000938 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000939 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000940 SourceLocation ConstructorLParen,
941 MultiExprArg ConstructorArgs,
Richard Smith34b41d92011-02-20 03:19:35 +0000942 SourceLocation ConstructorRParen,
943 bool TypeMayContainAuto) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000944 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000945
Richard Smith34b41d92011-02-20 03:19:35 +0000946 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
947 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
948 if (ConstructorArgs.size() == 0)
949 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
950 << AllocType << TypeRange);
951 if (ConstructorArgs.size() != 1) {
952 Expr *FirstBad = ConstructorArgs.get()[1];
953 return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
954 diag::err_auto_new_ctor_multiple_expressions)
955 << AllocType << TypeRange);
956 }
Richard Smitha085da82011-03-17 16:11:59 +0000957 TypeSourceInfo *DeducedType = 0;
Sebastian Redlb832f6d2012-01-23 22:09:39 +0000958 if (DeduceAutoType(AllocTypeInfo, ConstructorArgs.get()[0], DeducedType) ==
959 DAR_Failed)
Richard Smith34b41d92011-02-20 03:19:35 +0000960 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
961 << AllocType
962 << ConstructorArgs.get()[0]->getType()
963 << TypeRange
964 << ConstructorArgs.get()[0]->getSourceRange());
Richard Smitha085da82011-03-17 16:11:59 +0000965 if (!DeducedType)
966 return ExprError();
Richard Smith34b41d92011-02-20 03:19:35 +0000967
Richard Smitha085da82011-03-17 16:11:59 +0000968 AllocTypeInfo = DeducedType;
969 AllocType = AllocTypeInfo->getType();
Richard Smith34b41d92011-02-20 03:19:35 +0000970 }
971
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000972 // Per C++0x [expr.new]p5, the type being constructed may be a
973 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +0000974 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000975 if (const ConstantArrayType *Array
976 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000977 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
978 Context.getSizeType(),
979 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +0000980 AllocType = Array->getElementType();
981 }
982 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000983
Douglas Gregora0750762010-10-06 16:00:31 +0000984 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
985 return ExprError();
986
John McCallf85e1932011-06-15 23:02:42 +0000987 // In ARC, infer 'retaining' for the allocated
988 if (getLangOptions().ObjCAutoRefCount &&
989 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
990 AllocType->isObjCLifetimeType()) {
991 AllocType = Context.getLifetimeQualifiedType(AllocType,
992 AllocType->getObjCARCImplicitLifetime());
993 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000994
John McCallf85e1932011-06-15 23:02:42 +0000995 QualType ResultType = Context.getPointerType(AllocType);
996
Richard Smithf39aec12012-02-04 07:07:42 +0000997 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
998 // integral or enumeration type with a non-negative value."
999 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1000 // enumeration type, or a class type for which a single non-explicit
1001 // conversion function to integral or unscoped enumeration type exists.
Sebastian Redl28507842009-02-26 14:39:58 +00001002 if (ArraySize && !ArraySize->isTypeDependent()) {
Eli Friedmanceccab92012-01-26 00:26:18 +00001003 ExprResult ConvertedSize = ConvertToIntegralOrEnumerationType(
Richard Smithebaf0e62011-10-18 20:49:44 +00001004 StartLoc, ArraySize,
Richard Smithf39aec12012-02-04 07:07:42 +00001005 PDiag(diag::err_array_size_not_integral) << getLangOptions().CPlusPlus0x,
Richard Smithebaf0e62011-10-18 20:49:44 +00001006 PDiag(diag::err_array_size_incomplete_type)
1007 << ArraySize->getSourceRange(),
1008 PDiag(diag::err_array_size_explicit_conversion),
1009 PDiag(diag::note_array_size_conversion),
1010 PDiag(diag::err_array_size_ambiguous_conversion),
1011 PDiag(diag::note_array_size_conversion),
1012 PDiag(getLangOptions().CPlusPlus0x ?
1013 diag::warn_cxx98_compat_array_size_conversion :
Richard Smithf39aec12012-02-04 07:07:42 +00001014 diag::ext_array_size_conversion),
1015 /*AllowScopedEnumerations*/ false);
Douglas Gregor6bc574d2010-06-30 00:20:43 +00001016 if (ConvertedSize.isInvalid())
1017 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001018
John McCall9ae2f072010-08-23 23:25:46 +00001019 ArraySize = ConvertedSize.take();
John McCall806054d2012-01-11 00:14:46 +00001020 QualType SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001021 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +00001022 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001023
Richard Smith0b458fd2012-02-04 05:35:53 +00001024 // C++98 [expr.new]p7:
1025 // The expression in a direct-new-declarator shall have integral type
1026 // with a non-negative value.
1027 //
1028 // Let's see if this is a constant < 0. If so, we reject it out of
1029 // hand. Otherwise, if it's not a constant, we must have an unparenthesized
1030 // array type.
1031 //
1032 // Note: such a construct has well-defined semantics in C++11: it throws
1033 // std::bad_array_new_length.
Sebastian Redl28507842009-02-26 14:39:58 +00001034 if (!ArraySize->isValueDependent()) {
1035 llvm::APSInt Value;
Richard Smith282e7e62012-02-04 09:53:13 +00001036 // We've already performed any required implicit conversion to integer or
1037 // unscoped enumeration type.
Richard Smith0b458fd2012-02-04 05:35:53 +00001038 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Sebastian Redl28507842009-02-26 14:39:58 +00001039 if (Value < llvm::APSInt(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001040 llvm::APInt::getNullValue(Value.getBitWidth()),
Richard Smith0b458fd2012-02-04 05:35:53 +00001041 Value.isUnsigned())) {
1042 if (getLangOptions().CPlusPlus0x)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001043 Diag(ArraySize->getSourceRange().getBegin(),
Richard Smith0b458fd2012-02-04 05:35:53 +00001044 diag::warn_typecheck_negative_array_new_size)
Douglas Gregor2767ce22010-08-18 00:39:00 +00001045 << ArraySize->getSourceRange();
Richard Smith0b458fd2012-02-04 05:35:53 +00001046 else
1047 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
1048 diag::err_typecheck_negative_array_size)
1049 << ArraySize->getSourceRange());
1050 } else if (!AllocType->isDependentType()) {
1051 unsigned ActiveSizeBits =
1052 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1053 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
1054 if (getLangOptions().CPlusPlus0x)
1055 Diag(ArraySize->getSourceRange().getBegin(),
1056 diag::warn_array_new_too_large)
1057 << Value.toString(10)
1058 << ArraySize->getSourceRange();
1059 else
1060 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
1061 diag::err_array_too_large)
1062 << Value.toString(10)
1063 << ArraySize->getSourceRange());
Douglas Gregor2767ce22010-08-18 00:39:00 +00001064 }
1065 }
Douglas Gregor4bd40312010-07-13 15:54:32 +00001066 } else if (TypeIdParens.isValid()) {
1067 // Can't have dynamic array size when the type-id is in parentheses.
1068 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1069 << ArraySize->getSourceRange()
1070 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1071 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001072
Douglas Gregor4bd40312010-07-13 15:54:32 +00001073 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +00001074 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001075 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001076
John McCallf85e1932011-06-15 23:02:42 +00001077 // ARC: warn about ABI issues.
1078 if (getLangOptions().ObjCAutoRefCount) {
1079 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1080 if (BaseAllocType.hasStrongOrWeakObjCLifetime())
1081 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1082 << 0 << BaseAllocType;
1083 }
1084
John McCall7d166272011-05-15 07:14:44 +00001085 // Note that we do *not* convert the argument in any way. It can
1086 // be signed, larger than size_t, whatever.
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001087 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001088
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001089 FunctionDecl *OperatorNew = 0;
1090 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001091 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
1092 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001093
Sebastian Redl28507842009-02-26 14:39:58 +00001094 if (!AllocType->isDependentType() &&
1095 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
1096 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +00001097 SourceRange(PlacementLParen, PlacementRParen),
1098 UseGlobal, AllocType, ArraySize, PlaceArgs,
1099 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +00001100 return ExprError();
John McCall6ec278d2011-01-27 09:37:56 +00001101
1102 // If this is an array allocation, compute whether the usual array
1103 // deallocation function for the type has a size_t parameter.
1104 bool UsualArrayDeleteWantsSize = false;
1105 if (ArraySize && !AllocType->isDependentType())
1106 UsualArrayDeleteWantsSize
1107 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1108
Chris Lattner5f9e2722011-07-23 10:55:15 +00001109 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001110 if (OperatorNew) {
1111 // Add default arguments, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001112 const FunctionProtoType *Proto =
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001113 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001114 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00001115 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001116
Anders Carlsson28e94832010-05-03 02:07:56 +00001117 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001118 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlsson28e94832010-05-03 02:07:56 +00001119 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001120 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001121
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001122 NumPlaceArgs = AllPlaceArgs.size();
1123 if (NumPlaceArgs > 0)
1124 PlaceArgs = &AllPlaceArgs[0];
1125 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001126
Nick Lewyckyfca84b22012-01-24 21:15:41 +00001127 // Warn if the type is over-aligned and is being allocated by global operator
1128 // new.
Nick Lewycky507a8a32012-02-04 03:30:14 +00001129 if (NumPlaceArgs == 0 && OperatorNew &&
Nick Lewyckyfca84b22012-01-24 21:15:41 +00001130 (OperatorNew->isImplicit() ||
1131 getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) {
1132 if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
1133 unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
1134 if (Align > SuitableAlign)
1135 Diag(StartLoc, diag::warn_overaligned_type)
1136 << AllocType
1137 << unsigned(Align / Context.getCharWidth())
1138 << unsigned(SuitableAlign / Context.getCharWidth());
1139 }
1140 }
1141
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001142 bool Init = ConstructorLParen.isValid();
1143 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001144 CXXConstructorDecl *Constructor = 0;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001145 bool HadMultipleCandidates = false;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001146 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
1147 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +00001148 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +00001149
Anders Carlsson48c95012010-05-03 15:45:23 +00001150 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +00001151 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +00001152 SourceRange InitRange(ConsArgs[0]->getLocStart(),
1153 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001154
Anders Carlsson48c95012010-05-03 15:45:23 +00001155 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1156 return ExprError();
1157 }
1158
Douglas Gregor99a2e602009-12-16 01:38:02 +00001159 if (!AllocType->isDependentType() &&
1160 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
1161 // C++0x [expr.new]p15:
1162 // A new-expression that creates an object of type T initializes that
1163 // object as follows:
1164 InitializationKind Kind
1165 // - If the new-initializer is omitted, the object is default-
1166 // initialized (8.5); if no initialization is performed,
1167 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001168 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001169 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor99a2e602009-12-16 01:38:02 +00001170 // initialization rules of 8.5 for direct-initialization.
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001171 : InitializationKind::CreateDirect(TypeRange.getBegin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001172 ConstructorLParen,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001173 ConstructorRParen);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001174
Douglas Gregor99a2e602009-12-16 01:38:02 +00001175 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00001176 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001177 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001178 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001179 move(ConstructorArgs));
1180 if (FullInit.isInvalid())
1181 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001182
1183 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor99a2e602009-12-16 01:38:02 +00001184 // constructor call, which CXXNewExpr handles directly.
1185 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1186 if (CXXBindTemporaryExpr *Binder
1187 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1188 FullInitExpr = Binder->getSubExpr();
1189 if (CXXConstructExpr *Construct
1190 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1191 Constructor = Construct->getConstructor();
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001192 HadMultipleCandidates = Construct->hadMultipleCandidates();
Douglas Gregor99a2e602009-12-16 01:38:02 +00001193 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1194 AEnd = Construct->arg_end();
1195 A != AEnd; ++A)
John McCall3fa5cae2010-10-26 07:05:15 +00001196 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001197 } else {
1198 // Take the converted initializer.
1199 ConvertedConstructorArgs.push_back(FullInit.release());
1200 }
1201 } else {
1202 // No initialization required.
1203 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001204
Douglas Gregor99a2e602009-12-16 01:38:02 +00001205 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001206 NumConsArgs = ConvertedConstructorArgs.size();
1207 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001208 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001209
Douglas Gregor6d908702010-02-26 05:06:18 +00001210 // Mark the new and delete operators as referenced.
1211 if (OperatorNew)
Eli Friedman5f2987c2012-02-02 03:46:19 +00001212 MarkFunctionReferenced(StartLoc, OperatorNew);
Douglas Gregor6d908702010-02-26 05:06:18 +00001213 if (OperatorDelete)
Eli Friedman5f2987c2012-02-02 03:46:19 +00001214 MarkFunctionReferenced(StartLoc, OperatorDelete);
Douglas Gregor6d908702010-02-26 05:06:18 +00001215
John McCall84ff0fc2011-07-13 20:12:57 +00001216 // C++0x [expr.new]p17:
1217 // If the new expression creates an array of objects of class type,
1218 // access and ambiguity control are done for the destructor.
1219 if (ArraySize && Constructor) {
1220 if (CXXDestructorDecl *dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00001221 MarkFunctionReferenced(StartLoc, dtor);
John McCall84ff0fc2011-07-13 20:12:57 +00001222 CheckDestructorAccess(StartLoc, dtor,
1223 PDiag(diag::err_access_dtor)
1224 << Context.getBaseElementType(AllocType));
1225 }
1226 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001227
Sebastian Redlf53597f2009-03-15 17:47:39 +00001228 PlacementArgs.release();
1229 ConstructorArgs.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001230
Ted Kremenekad7fe862010-02-11 22:51:03 +00001231 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001232 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001233 ArraySize, Constructor, Init,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001234 ConsArgs, NumConsArgs,
1235 HadMultipleCandidates,
1236 OperatorDelete,
John McCall6ec278d2011-01-27 09:37:56 +00001237 UsualArrayDeleteWantsSize,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001238 ResultType, AllocTypeInfo,
1239 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001240 Init ? ConstructorRParen :
Chandler Carruth428edaf2010-10-25 08:47:36 +00001241 TypeRange.getEnd(),
1242 ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001243}
1244
1245/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1246/// in a new-expression.
1247/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +00001248bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00001249 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001250 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1251 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +00001252 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001253 return Diag(Loc, diag::err_bad_new_type)
1254 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001255 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001256 return Diag(Loc, diag::err_bad_new_type)
1257 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001258 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +00001259 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001260 PDiag(diag::err_new_incomplete_type)
1261 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001262 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +00001263 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +00001264 diag::err_allocation_of_abstract_type))
1265 return true;
Douglas Gregora0750762010-10-06 16:00:31 +00001266 else if (AllocType->isVariablyModifiedType())
1267 return Diag(Loc, diag::err_variably_modified_new_type)
1268 << AllocType;
Douglas Gregor5666d362011-04-15 19:46:20 +00001269 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1270 return Diag(Loc, diag::err_address_space_qualified_new)
1271 << AllocType.getUnqualifiedType() << AddressSpace;
John McCallf85e1932011-06-15 23:02:42 +00001272 else if (getLangOptions().ObjCAutoRefCount) {
1273 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1274 QualType BaseAllocType = Context.getBaseElementType(AT);
1275 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1276 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001277 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001278 << BaseAllocType;
1279 }
1280 }
Douglas Gregor5666d362011-04-15 19:46:20 +00001281
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001282 return false;
1283}
1284
Douglas Gregor6d908702010-02-26 05:06:18 +00001285/// \brief Determine whether the given function is a non-placement
1286/// deallocation function.
1287static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1288 if (FD->isInvalidDecl())
1289 return false;
1290
1291 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1292 return Method->isUsualDeallocationFunction();
1293
1294 return ((FD->getOverloadedOperator() == OO_Delete ||
1295 FD->getOverloadedOperator() == OO_Array_Delete) &&
1296 FD->getNumParams() == 1);
1297}
1298
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001299/// FindAllocationFunctions - Finds the overloads of operator new and delete
1300/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001301bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1302 bool UseGlobal, QualType AllocType,
1303 bool IsArray, Expr **PlaceArgs,
1304 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001305 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +00001306 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001307 // --- Choosing an allocation function ---
1308 // C++ 5.3.4p8 - 14 & 18
1309 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1310 // in the scope of the allocated class.
1311 // 2) If an array size is given, look for operator new[], else look for
1312 // operator new.
1313 // 3) The first argument is always size_t. Append the arguments from the
1314 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001315
Chris Lattner5f9e2722011-07-23 10:55:15 +00001316 SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001317 // We don't care about the actual value of this argument.
1318 // FIXME: Should the Sema create the expression and embed it in the syntax
1319 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001320 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001321 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssond67c4c32009-08-16 20:29:29 +00001322 Context.getSizeType(),
1323 SourceLocation());
1324 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001325 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1326
Douglas Gregor6d908702010-02-26 05:06:18 +00001327 // C++ [expr.new]p8:
1328 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001329 // function's name is operator new and the deallocation function's
Douglas Gregor6d908702010-02-26 05:06:18 +00001330 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001331 // type, the allocation function's name is operator new[] and the
1332 // deallocation function's name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001333 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1334 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001335 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1336 IsArray ? OO_Array_Delete : OO_Delete);
1337
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001338 QualType AllocElemType = Context.getBaseElementType(AllocType);
1339
1340 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001341 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001342 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001343 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001344 AllocArgs.size(), Record, /*AllowMissing=*/true,
1345 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001346 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001347 }
1348 if (!OperatorNew) {
1349 // Didn't find a member overload. Look for a global one.
1350 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001351 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001352 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001353 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1354 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001355 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001356 }
1357
John McCall9c82afc2010-04-20 02:18:25 +00001358 // We don't need an operator delete if we're running under
1359 // -fno-exceptions.
1360 if (!getLangOptions().Exceptions) {
1361 OperatorDelete = 0;
1362 return false;
1363 }
1364
Anders Carlssond9583892009-05-31 20:26:12 +00001365 // FindAllocationOverload can change the passed in arguments, so we need to
1366 // copy them back.
1367 if (NumPlaceArgs > 0)
1368 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001369
Douglas Gregor6d908702010-02-26 05:06:18 +00001370 // C++ [expr.new]p19:
1371 //
1372 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001373 // deallocation function's name is looked up in the global
Douglas Gregor6d908702010-02-26 05:06:18 +00001374 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001375 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6d908702010-02-26 05:06:18 +00001376 // the scope of T. If this lookup fails to find the name, or if
1377 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001378 // deallocation function's name is looked up in the global scope.
Douglas Gregor6d908702010-02-26 05:06:18 +00001379 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001380 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001381 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001382 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001383 LookupQualifiedName(FoundDelete, RD);
1384 }
John McCall90c8c572010-03-18 08:19:33 +00001385 if (FoundDelete.isAmbiguous())
1386 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001387
1388 if (FoundDelete.empty()) {
1389 DeclareGlobalNewDelete();
1390 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1391 }
1392
1393 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001394
Chris Lattner5f9e2722011-07-23 10:55:15 +00001395 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCall9aa472c2010-03-19 07:35:19 +00001396
John McCalledeb6c92010-09-14 21:34:24 +00001397 // Whether we're looking for a placement operator delete is dictated
1398 // by whether we selected a placement operator new, not by whether
1399 // we had explicit placement arguments. This matters for things like
1400 // struct A { void *operator new(size_t, int = 0); ... };
1401 // A *a = new A()
1402 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1403
1404 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001405 // C++ [expr.new]p20:
1406 // A declaration of a placement deallocation function matches the
1407 // declaration of a placement allocation function if it has the
1408 // same number of parameters and, after parameter transformations
1409 // (8.3.5), all parameter types except the first are
1410 // identical. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001411 //
Douglas Gregor6d908702010-02-26 05:06:18 +00001412 // To perform this comparison, we compute the function type that
1413 // the deallocation function should have, and use that type both
1414 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001415 //
1416 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001417 QualType ExpectedFunctionType;
1418 {
1419 const FunctionProtoType *Proto
1420 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001421
Chris Lattner5f9e2722011-07-23 10:55:15 +00001422 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001423 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6d908702010-02-26 05:06:18 +00001424 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1425 ArgTypes.push_back(Proto->getArgType(I));
1426
John McCalle23cf432010-12-14 08:05:40 +00001427 FunctionProtoType::ExtProtoInfo EPI;
1428 EPI.Variadic = Proto->isVariadic();
1429
Douglas Gregor6d908702010-02-26 05:06:18 +00001430 ExpectedFunctionType
1431 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalle23cf432010-12-14 08:05:40 +00001432 ArgTypes.size(), EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001433 }
1434
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001435 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001436 DEnd = FoundDelete.end();
1437 D != DEnd; ++D) {
1438 FunctionDecl *Fn = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001439 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6d908702010-02-26 05:06:18 +00001440 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1441 // Perform template argument deduction to try to match the
1442 // expected function type.
1443 TemplateDeductionInfo Info(Context, StartLoc);
1444 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1445 continue;
1446 } else
1447 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1448
1449 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001450 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001451 }
1452 } else {
1453 // C++ [expr.new]p20:
1454 // [...] Any non-placement deallocation function matches a
1455 // non-placement allocation function. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001456 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001457 DEnd = FoundDelete.end();
1458 D != DEnd; ++D) {
1459 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1460 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001461 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001462 }
1463 }
1464
1465 // C++ [expr.new]p20:
1466 // [...] If the lookup finds a single matching deallocation
1467 // function, that function will be called; otherwise, no
1468 // deallocation function will be called.
1469 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001470 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001471
1472 // C++0x [expr.new]p20:
1473 // If the lookup finds the two-parameter form of a usual
1474 // deallocation function (3.7.4.2) and that function, considered
1475 // as a placement deallocation function, would have been
1476 // selected as a match for the allocation function, the program
1477 // is ill-formed.
1478 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1479 isNonPlacementDeallocationFunction(OperatorDelete)) {
1480 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001481 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001482 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1483 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1484 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001485 } else {
1486 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001487 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001488 }
1489 }
1490
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001491 return false;
1492}
1493
Sebastian Redl7f662392008-12-04 22:20:51 +00001494/// FindAllocationOverload - Find an fitting overload for the allocation
1495/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001496bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1497 DeclarationName Name, Expr** Args,
1498 unsigned NumArgs, DeclContext *Ctx,
Sean Hunt2be7e902011-05-12 22:46:29 +00001499 bool AllowMissing, FunctionDecl *&Operator,
1500 bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001501 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1502 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001503 if (R.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001504 if (AllowMissing || !Diagnose)
Sebastian Redl7f662392008-12-04 22:20:51 +00001505 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001506 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001507 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001508 }
1509
John McCall90c8c572010-03-18 08:19:33 +00001510 if (R.isAmbiguous())
1511 return true;
1512
1513 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001514
John McCall5769d612010-02-08 23:07:23 +00001515 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001516 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001517 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001518 // Even member operator new/delete are implicitly treated as
1519 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001520 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001521
John McCall9aa472c2010-03-19 07:35:19 +00001522 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1523 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001524 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1525 Candidates,
1526 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001527 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001528 }
1529
John McCall9aa472c2010-03-19 07:35:19 +00001530 FunctionDecl *Fn = cast<FunctionDecl>(D);
1531 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001532 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001533 }
1534
1535 // Do the resolution.
1536 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001537 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001538 case OR_Success: {
1539 // Got one!
1540 FunctionDecl *FnDecl = Best->Function;
Eli Friedman5f2987c2012-02-02 03:46:19 +00001541 MarkFunctionReferenced(StartLoc, FnDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001542 // The first argument is size_t, and the first parameter must be size_t,
1543 // too. This is checked on declaration and can be assumed. (It can't be
1544 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001545 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001546 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1547 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001548 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1549 FnDecl->getParamDecl(i));
1550
1551 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1552 return true;
1553
John McCall60d7b3a2010-08-24 06:29:42 +00001554 ExprResult Result
Sean Hunt2be7e902011-05-12 22:46:29 +00001555 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001556 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001557 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001558
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001559 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001560 }
1561 Operator = FnDecl;
Sean Hunt2be7e902011-05-12 22:46:29 +00001562 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl,
1563 Diagnose);
Sebastian Redl7f662392008-12-04 22:20:51 +00001564 return false;
1565 }
1566
1567 case OR_No_Viable_Function:
Chandler Carruth361d3802011-06-08 10:26:03 +00001568 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001569 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1570 << Name << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001571 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1572 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001573 return true;
1574
1575 case OR_Ambiguous:
Chandler Carruth361d3802011-06-08 10:26:03 +00001576 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001577 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1578 << Name << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001579 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
1580 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001581 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001582
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001583 case OR_Deleted: {
Chandler Carruth361d3802011-06-08 10:26:03 +00001584 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001585 Diag(StartLoc, diag::err_ovl_deleted_call)
1586 << Best->Function->isDeleted()
1587 << Name
1588 << getDeletedOrUnavailableSuffix(Best->Function)
1589 << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001590 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1591 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001592 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001593 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001594 }
David Blaikieb219cfc2011-09-23 05:06:16 +00001595 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Sebastian Redl7f662392008-12-04 22:20:51 +00001596}
1597
1598
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001599/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1600/// delete. These are:
1601/// @code
Sebastian Redl8999fe12011-03-14 18:08:30 +00001602/// // C++03:
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001603/// void* operator new(std::size_t) throw(std::bad_alloc);
1604/// void* operator new[](std::size_t) throw(std::bad_alloc);
1605/// void operator delete(void *) throw();
1606/// void operator delete[](void *) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001607/// // C++0x:
1608/// void* operator new(std::size_t);
1609/// void* operator new[](std::size_t);
1610/// void operator delete(void *);
1611/// void operator delete[](void *);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001612/// @endcode
Sebastian Redl8999fe12011-03-14 18:08:30 +00001613/// C++0x operator delete is implicitly noexcept.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001614/// Note that the placement and nothrow forms of new are *not* implicitly
1615/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001616void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001617 if (GlobalNewDeleteDeclared)
1618 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001619
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001620 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001621 // [...] The following allocation and deallocation functions (18.4) are
1622 // implicitly declared in global scope in each translation unit of a
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001623 // program
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001624 //
Sebastian Redl8999fe12011-03-14 18:08:30 +00001625 // C++03:
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001626 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001627 // void* operator new[](std::size_t) throw(std::bad_alloc);
1628 // void operator delete(void*) throw();
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001629 // void operator delete[](void*) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001630 // C++0x:
1631 // void* operator new(std::size_t);
1632 // void* operator new[](std::size_t);
1633 // void operator delete(void*);
1634 // void operator delete[](void*);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001635 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001636 // These implicit declarations introduce only the function names operator
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001637 // new, operator new[], operator delete, operator delete[].
1638 //
1639 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1640 // "std" or "bad_alloc" as necessary to form the exception specification.
1641 // However, we do not make these implicit declarations visible to name
1642 // lookup.
Sebastian Redl8999fe12011-03-14 18:08:30 +00001643 // Note that the C++0x versions of operator delete are deallocation functions,
1644 // and thus are implicitly noexcept.
1645 if (!StdBadAlloc && !getLangOptions().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001646 // The "std::bad_alloc" class has not yet been declared, so build it
1647 // implicitly.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001648 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1649 getOrCreateStdNamespace(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001650 SourceLocation(), SourceLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001651 &PP.getIdentifierTable().get("bad_alloc"),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001652 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001653 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001654 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001655
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001656 GlobalNewDeleteDeclared = true;
1657
1658 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1659 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001660 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001661
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001662 DeclareGlobalAllocationFunction(
1663 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001664 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001665 DeclareGlobalAllocationFunction(
1666 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001667 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001668 DeclareGlobalAllocationFunction(
1669 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1670 Context.VoidTy, VoidPtr);
1671 DeclareGlobalAllocationFunction(
1672 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1673 Context.VoidTy, VoidPtr);
1674}
1675
1676/// DeclareGlobalAllocationFunction - Declares a single implicit global
1677/// allocation function if it doesn't already exist.
1678void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001679 QualType Return, QualType Argument,
1680 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001681 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1682
1683 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001684 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001685 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001686 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001687 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001688 // Only look at non-template functions, as it is the predefined,
1689 // non-templated allocation function we are trying to declare here.
1690 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1691 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001692 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001693 Func->getParamDecl(0)->getType().getUnqualifiedType());
1694 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001695 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1696 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001697 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001698 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001699 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001700 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001701 }
1702 }
1703
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001704 QualType BadAllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001705 bool HasBadAllocExceptionSpec
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001706 = (Name.getCXXOverloadedOperator() == OO_New ||
1707 Name.getCXXOverloadedOperator() == OO_Array_New);
Sebastian Redl8999fe12011-03-14 18:08:30 +00001708 if (HasBadAllocExceptionSpec && !getLangOptions().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001709 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001710 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001711 }
John McCalle23cf432010-12-14 08:05:40 +00001712
1713 FunctionProtoType::ExtProtoInfo EPI;
John McCalle23cf432010-12-14 08:05:40 +00001714 if (HasBadAllocExceptionSpec) {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001715 if (!getLangOptions().CPlusPlus0x) {
1716 EPI.ExceptionSpecType = EST_Dynamic;
1717 EPI.NumExceptions = 1;
1718 EPI.Exceptions = &BadAllocType;
1719 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00001720 } else {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001721 EPI.ExceptionSpecType = getLangOptions().CPlusPlus0x ?
1722 EST_BasicNoexcept : EST_DynamicNone;
John McCalle23cf432010-12-14 08:05:40 +00001723 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001724
John McCalle23cf432010-12-14 08:05:40 +00001725 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001726 FunctionDecl *Alloc =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001727 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1728 SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001729 FnType, /*TInfo=*/0, SC_None,
1730 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001731 Alloc->setImplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001732
Nuno Lopesfc284482009-12-16 16:59:22 +00001733 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001734 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001735
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001736 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001737 SourceLocation(), 0,
1738 Argument, /*TInfo=*/0,
1739 SC_None, SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00001740 Alloc->setParams(Param);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001741
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001742 // FIXME: Also add this declaration to the IdentifierResolver, but
1743 // make sure it is at the end of the chain to coincide with the
1744 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001745 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001746}
1747
Anders Carlsson78f74552009-11-15 18:45:20 +00001748bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1749 DeclarationName Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001750 FunctionDecl* &Operator, bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001751 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001752 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001753 LookupQualifiedName(Found, RD);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001754
John McCalla24dc2e2009-11-17 02:14:36 +00001755 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001756 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001757
Chandler Carruth23893242010-06-28 00:30:51 +00001758 Found.suppressDiagnostics();
1759
Chris Lattner5f9e2722011-07-23 10:55:15 +00001760 SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001761 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1762 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001763 NamedDecl *ND = (*F)->getUnderlyingDecl();
1764
1765 // Ignore template operator delete members from the check for a usual
1766 // deallocation function.
1767 if (isa<FunctionTemplateDecl>(ND))
1768 continue;
1769
1770 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001771 Matches.push_back(F.getPair());
1772 }
1773
1774 // There's exactly one suitable operator; pick it.
1775 if (Matches.size() == 1) {
1776 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
Sean Hunt2be7e902011-05-12 22:46:29 +00001777
1778 if (Operator->isDeleted()) {
1779 if (Diagnose) {
1780 Diag(StartLoc, diag::err_deleted_function_use);
1781 Diag(Operator->getLocation(), diag::note_unavailable_here) << true;
1782 }
1783 return true;
1784 }
1785
John McCall046a7462010-08-04 00:31:26 +00001786 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Sean Hunt2be7e902011-05-12 22:46:29 +00001787 Matches[0], Diagnose);
John McCall046a7462010-08-04 00:31:26 +00001788 return false;
1789
1790 // We found multiple suitable operators; complain about the ambiguity.
1791 } else if (!Matches.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001792 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001793 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1794 << Name << RD;
John McCall046a7462010-08-04 00:31:26 +00001795
Chris Lattner5f9e2722011-07-23 10:55:15 +00001796 for (SmallVectorImpl<DeclAccessPair>::iterator
Sean Huntcb45a0f2011-05-12 22:46:25 +00001797 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1798 Diag((*F)->getUnderlyingDecl()->getLocation(),
1799 diag::note_member_declared_here) << Name;
1800 }
John McCall046a7462010-08-04 00:31:26 +00001801 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001802 }
1803
1804 // We did find operator delete/operator delete[] declarations, but
1805 // none of them were suitable.
1806 if (!Found.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001807 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001808 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1809 << Name << RD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001810
Sean Huntcb45a0f2011-05-12 22:46:25 +00001811 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1812 F != FEnd; ++F)
1813 Diag((*F)->getUnderlyingDecl()->getLocation(),
1814 diag::note_member_declared_here) << Name;
1815 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001816 return true;
1817 }
1818
1819 // Look for a global declaration.
1820 DeclareGlobalNewDelete();
1821 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001822
Anders Carlsson78f74552009-11-15 18:45:20 +00001823 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1824 Expr* DeallocArgs[1];
1825 DeallocArgs[0] = &Null;
1826 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001827 DeallocArgs, 1, TUDecl, !Diagnose,
1828 Operator, Diagnose))
Anders Carlsson78f74552009-11-15 18:45:20 +00001829 return true;
1830
1831 assert(Operator && "Did not find a deallocation function!");
1832 return false;
1833}
1834
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001835/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1836/// @code ::delete ptr; @endcode
1837/// or
1838/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001839ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001840Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley429bb272011-04-08 18:41:53 +00001841 bool ArrayForm, Expr *ExE) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001842 // C++ [expr.delete]p1:
1843 // The operand shall have a pointer type, or a class type having a single
1844 // conversion function to a pointer type. The result has type void.
1845 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001846 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1847
John Wiegley429bb272011-04-08 18:41:53 +00001848 ExprResult Ex = Owned(ExE);
Anders Carlssond67c4c32009-08-16 20:29:29 +00001849 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001850 bool ArrayFormAsWritten = ArrayForm;
John McCall6ec278d2011-01-27 09:37:56 +00001851 bool UsualArrayDeleteWantsSize = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001852
John Wiegley429bb272011-04-08 18:41:53 +00001853 if (!Ex.get()->isTypeDependent()) {
1854 QualType Type = Ex.get()->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001855
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001856 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001857 if (RequireCompleteType(StartLoc, Type,
Douglas Gregor254a9422010-07-29 14:44:35 +00001858 PDiag(diag::err_delete_incomplete_class_type)))
1859 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001860
Chris Lattner5f9e2722011-07-23 10:55:15 +00001861 SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
John McCall32daa422010-03-31 01:36:47 +00001862
Fariborz Jahanian53462782009-09-11 21:44:33 +00001863 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001864 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001865 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001866 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001867 NamedDecl *D = I.getDecl();
1868 if (isa<UsingShadowDecl>(D))
1869 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1870
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001871 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001872 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001873 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001874
John McCall32daa422010-03-31 01:36:47 +00001875 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001876
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001877 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1878 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001879 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001880 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001881 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001882 if (ObjectPtrConversions.size() == 1) {
1883 // We have a single conversion to a pointer-to-object type. Perform
1884 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001885 // TODO: don't redo the conversion calculation.
John Wiegley429bb272011-04-08 18:41:53 +00001886 ExprResult Res =
1887 PerformImplicitConversion(Ex.get(),
John McCall32daa422010-03-31 01:36:47 +00001888 ObjectPtrConversions.front()->getConversionType(),
John Wiegley429bb272011-04-08 18:41:53 +00001889 AA_Converting);
1890 if (Res.isUsable()) {
1891 Ex = move(Res);
1892 Type = Ex.get()->getType();
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001893 }
1894 }
1895 else if (ObjectPtrConversions.size() > 1) {
1896 Diag(StartLoc, diag::err_ambiguous_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001897 << Type << Ex.get()->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001898 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1899 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001900 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001901 }
Sebastian Redl28507842009-02-26 14:39:58 +00001902 }
1903
Sebastian Redlf53597f2009-03-15 17:47:39 +00001904 if (!Type->isPointerType())
1905 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001906 << Type << Ex.get()->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001907
Ted Kremenek6217b802009-07-29 21:53:49 +00001908 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmane52c9142011-07-26 22:25:31 +00001909 QualType PointeeElem = Context.getBaseElementType(Pointee);
1910
1911 if (unsigned AddressSpace = Pointee.getAddressSpace())
1912 return Diag(Ex.get()->getLocStart(),
1913 diag::err_address_space_qualified_delete)
1914 << Pointee.getUnqualifiedType() << AddressSpace;
1915
1916 CXXRecordDecl *PointeeRD = 0;
Douglas Gregor94a61572010-05-24 17:01:56 +00001917 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001918 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregor94a61572010-05-24 17:01:56 +00001919 // effectively bans deletion of "void*". However, most compilers support
1920 // this, so we treat it as a warning unless we're in a SFINAE context.
1921 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001922 << Type << Ex.get()->getSourceRange();
Eli Friedmane52c9142011-07-26 22:25:31 +00001923 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00001924 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001925 << Type << Ex.get()->getSourceRange());
Eli Friedmane52c9142011-07-26 22:25:31 +00001926 } else if (!Pointee->isDependentType()) {
1927 if (!RequireCompleteType(StartLoc, Pointee,
1928 PDiag(diag::warn_delete_incomplete)
1929 << Ex.get()->getSourceRange())) {
1930 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
1931 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
1932 }
1933 }
1934
Abramo Bagnara30bb4202011-11-16 15:42:13 +00001935 // Perform lvalue-to-rvalue cast, if needed.
1936 Ex = DefaultLvalueConversion(Ex.take());
1937
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001938 // C++ [expr.delete]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001939 // [Note: a pointer to a const type can be the operand of a
1940 // delete-expression; it is not necessary to cast away the constness
1941 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001942 // of the delete-expression. ]
John McCallf85e1932011-06-15 23:02:42 +00001943 if (!Context.hasSameType(Ex.get()->getType(), Context.VoidPtrTy))
Abramo Bagnara30bb4202011-11-16 15:42:13 +00001944 Ex = Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy,
1945 CK_BitCast, Ex.take(), 0, VK_RValue));
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001946
1947 if (Pointee->isArrayType() && !ArrayForm) {
1948 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley429bb272011-04-08 18:41:53 +00001949 << Type << Ex.get()->getSourceRange()
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001950 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1951 ArrayForm = true;
1952 }
1953
Anders Carlssond67c4c32009-08-16 20:29:29 +00001954 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1955 ArrayForm ? OO_Array_Delete : OO_Delete);
1956
Eli Friedmane52c9142011-07-26 22:25:31 +00001957 if (PointeeRD) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001958 if (!UseGlobal &&
Eli Friedmane52c9142011-07-26 22:25:31 +00001959 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
1960 OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001961 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001962
John McCall6ec278d2011-01-27 09:37:56 +00001963 // If we're allocating an array of records, check whether the
1964 // usual operator delete[] has a size_t parameter.
1965 if (ArrayForm) {
1966 // If the user specifically asked to use the global allocator,
1967 // we'll need to do the lookup into the class.
1968 if (UseGlobal)
1969 UsualArrayDeleteWantsSize =
1970 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1971
1972 // Otherwise, the usual operator delete[] should be the
1973 // function we just found.
1974 else if (isa<CXXMethodDecl>(OperatorDelete))
1975 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1976 }
1977
Eli Friedmane52c9142011-07-26 22:25:31 +00001978 if (!PointeeRD->hasTrivialDestructor())
1979 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00001980 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001981 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00001982 DiagnoseUseOfDecl(Dtor, StartLoc);
1983 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00001984
1985 // C++ [expr.delete]p3:
1986 // In the first alternative (delete object), if the static type of the
1987 // object to be deleted is different from its dynamic type, the static
1988 // type shall be a base class of the dynamic type of the object to be
1989 // deleted and the static type shall have a virtual destructor or the
1990 // behavior is undefined.
1991 //
1992 // Note: a final class cannot be derived from, no issue there
Eli Friedmanef8c79c2011-07-26 23:27:24 +00001993 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
Eli Friedmane52c9142011-07-26 22:25:31 +00001994 CXXDestructorDecl *dtor = PointeeRD->getDestructor();
Eli Friedmanef8c79c2011-07-26 23:27:24 +00001995 if (dtor && !dtor->isVirtual()) {
1996 if (PointeeRD->isAbstract()) {
1997 // If the class is abstract, we warn by default, because we're
1998 // sure the code has undefined behavior.
1999 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
2000 << PointeeElem;
2001 } else if (!ArrayForm) {
2002 // Otherwise, if this is not an array delete, it's a bit suspect,
2003 // but not necessarily wrong.
2004 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
2005 }
2006 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00002007 }
John McCallf85e1932011-06-15 23:02:42 +00002008
2009 } else if (getLangOptions().ObjCAutoRefCount &&
2010 PointeeElem->isObjCLifetimeType() &&
2011 (PointeeElem.getObjCLifetime() == Qualifiers::OCL_Strong ||
2012 PointeeElem.getObjCLifetime() == Qualifiers::OCL_Weak) &&
2013 ArrayForm) {
2014 Diag(StartLoc, diag::warn_err_new_delete_object_array)
2015 << 1 << PointeeElem;
Anders Carlssond67c4c32009-08-16 20:29:29 +00002016 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002017
Anders Carlssond67c4c32009-08-16 20:29:29 +00002018 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00002019 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00002020 DeclareGlobalNewDelete();
2021 DeclContext *TUDecl = Context.getTranslationUnitDecl();
John Wiegley429bb272011-04-08 18:41:53 +00002022 Expr *Arg = Ex.get();
Mike Stump1eb44332009-09-09 15:08:12 +00002023 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
John Wiegley429bb272011-04-08 18:41:53 +00002024 &Arg, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00002025 OperatorDelete))
2026 return ExprError();
2027 }
Mike Stump1eb44332009-09-09 15:08:12 +00002028
Eli Friedman5f2987c2012-02-02 03:46:19 +00002029 MarkFunctionReferenced(StartLoc, OperatorDelete);
John McCall6ec278d2011-01-27 09:37:56 +00002030
Douglas Gregord880f522011-02-01 15:50:11 +00002031 // Check access and ambiguity of operator delete and destructor.
Eli Friedmane52c9142011-07-26 22:25:31 +00002032 if (PointeeRD) {
2033 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
John Wiegley429bb272011-04-08 18:41:53 +00002034 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregord880f522011-02-01 15:50:11 +00002035 PDiag(diag::err_access_dtor) << PointeeElem);
2036 }
2037 }
2038
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002039 }
2040
Sebastian Redlf53597f2009-03-15 17:47:39 +00002041 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall6ec278d2011-01-27 09:37:56 +00002042 ArrayFormAsWritten,
2043 UsualArrayDeleteWantsSize,
John Wiegley429bb272011-04-08 18:41:53 +00002044 OperatorDelete, Ex.take(), StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002045}
2046
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002047/// \brief Check the use of the given variable as a C++ condition in an if,
2048/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00002049ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00002050 SourceLocation StmtLoc,
2051 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002052 QualType T = ConditionVar->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002053
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002054 // C++ [stmt.select]p2:
2055 // The declarator shall not specify a function or an array.
2056 if (T->isFunctionType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002057 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002058 diag::err_invalid_use_of_function_type)
2059 << ConditionVar->getSourceRange());
2060 else if (T->isArrayType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002061 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002062 diag::err_invalid_use_of_array_type)
2063 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00002064
John Wiegley429bb272011-04-08 18:41:53 +00002065 ExprResult Condition =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002066 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2067 SourceLocation(),
2068 ConditionVar,
2069 ConditionVar->getLocation(),
2070 ConditionVar->getType().getNonReferenceType(),
John Wiegley429bb272011-04-08 18:41:53 +00002071 VK_LValue));
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002072
Eli Friedman5f2987c2012-02-02 03:46:19 +00002073 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002074
John Wiegley429bb272011-04-08 18:41:53 +00002075 if (ConvertToBoolean) {
2076 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
2077 if (Condition.isInvalid())
2078 return ExprError();
2079 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002080
John Wiegley429bb272011-04-08 18:41:53 +00002081 return move(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002082}
2083
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002084/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley429bb272011-04-08 18:41:53 +00002085ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002086 // C++ 6.4p4:
2087 // The value of a condition that is an initialized declaration in a statement
2088 // other than a switch statement is the value of the declared variable
2089 // implicitly converted to type bool. If that conversion is ill-formed, the
2090 // program is ill-formed.
2091 // The value of a condition that is an expression is the value of the
2092 // expression, implicitly converted to bool.
2093 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002094 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002095}
Douglas Gregor77a52232008-09-12 00:47:35 +00002096
2097/// Helper function to determine whether this is the (deprecated) C++
2098/// conversion from a string literal to a pointer to non-const char or
2099/// non-const wchar_t (for narrow and wide string literals,
2100/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00002101bool
Douglas Gregor77a52232008-09-12 00:47:35 +00002102Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2103 // Look inside the implicit cast, if it exists.
2104 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2105 From = Cast->getSubExpr();
2106
2107 // A string literal (2.13.4) that is not a wide string literal can
2108 // be converted to an rvalue of type "pointer to char"; a wide
2109 // string literal can be converted to an rvalue of type "pointer
2110 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00002111 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00002112 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00002113 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00002114 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00002115 // This conversion is considered only when there is an
2116 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregor5cee1192011-07-27 05:40:30 +00002117 if (!ToPtrType->getPointeeType().hasQualifiers()) {
2118 switch (StrLit->getKind()) {
2119 case StringLiteral::UTF8:
2120 case StringLiteral::UTF16:
2121 case StringLiteral::UTF32:
2122 // We don't allow UTF literals to be implicitly converted
2123 break;
2124 case StringLiteral::Ascii:
2125 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2126 ToPointeeType->getKind() == BuiltinType::Char_S);
2127 case StringLiteral::Wide:
2128 return ToPointeeType->isWideCharType();
2129 }
2130 }
Douglas Gregor77a52232008-09-12 00:47:35 +00002131 }
2132
2133 return false;
2134}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002135
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002136static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00002137 SourceLocation CastLoc,
2138 QualType Ty,
2139 CastKind Kind,
2140 CXXMethodDecl *Method,
John McCallca82a822011-09-21 08:36:56 +00002141 DeclAccessPair FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002142 bool HadMultipleCandidates,
John McCall2de56d12010-08-25 11:45:40 +00002143 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002144 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002145 default: llvm_unreachable("Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00002146 case CK_ConstructorConversion: {
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002147 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
John McCallca0408f2010-08-23 06:44:23 +00002148 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002149
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002150 if (S.CompleteConstructorCall(Constructor,
John McCallf312b1e2010-08-26 23:41:50 +00002151 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00002152 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00002153 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002154
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002155 S.CheckConstructorAccess(CastLoc, Constructor, Constructor->getAccess(),
2156 S.PDiag(diag::err_access_ctor));
2157
2158 ExprResult Result
2159 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2160 move_arg(ConstructorArgs),
2161 HadMultipleCandidates, /*ZeroInit*/ false,
2162 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002163 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00002164 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002165
Douglas Gregorba70ab62010-04-16 22:17:36 +00002166 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2167 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002168
John McCall2de56d12010-08-25 11:45:40 +00002169 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002170 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002171
Douglas Gregorba70ab62010-04-16 22:17:36 +00002172 // Create an implicit call expr that calls it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002173 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method,
2174 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002175 if (Result.isInvalid())
2176 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00002177 // Record usage of conversion in an implicit cast.
2178 Result = S.Owned(ImplicitCastExpr::Create(S.Context,
2179 Result.get()->getType(),
2180 CK_UserDefinedConversion,
2181 Result.get(), 0,
2182 Result.get()->getValueKind()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002183
John McCallca82a822011-09-21 08:36:56 +00002184 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2185
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002186 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002187 }
2188 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002189}
Douglas Gregorba70ab62010-04-16 22:17:36 +00002190
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002191/// PerformImplicitConversion - Perform an implicit conversion of the
2192/// expression From to the type ToType using the pre-computed implicit
John Wiegley429bb272011-04-08 18:41:53 +00002193/// conversion sequence ICS. Returns the converted
Douglas Gregor68647482009-12-16 03:45:30 +00002194/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002195/// used in the error message.
John Wiegley429bb272011-04-08 18:41:53 +00002196ExprResult
2197Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002198 const ImplicitConversionSequence &ICS,
John McCallf85e1932011-06-15 23:02:42 +00002199 AssignmentAction Action,
2200 CheckedConversionKind CCK) {
John McCall1d318332010-01-12 00:44:57 +00002201 switch (ICS.getKind()) {
John Wiegley429bb272011-04-08 18:41:53 +00002202 case ImplicitConversionSequence::StandardConversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002203 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2204 Action, CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002205 if (Res.isInvalid())
2206 return ExprError();
2207 From = Res.take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002208 break;
John Wiegley429bb272011-04-08 18:41:53 +00002209 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002210
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002211 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002212
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00002213 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00002214 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002215 QualType BeforeToType;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00002216 assert(FD && "FIXME: aggregate initialization from init list");
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002217 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00002218 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002219
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002220 // If the user-defined conversion is specified by a conversion function,
2221 // the initial standard conversion sequence converts the source type to
2222 // the implicit object parameter of the conversion function.
2223 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00002224 } else {
2225 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00002226 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002227 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00002228 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002229 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002230 // initial standard conversion sequence converts the source type to the
2231 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00002232 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2233 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002234 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00002235 // Watch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00002236 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley429bb272011-04-08 18:41:53 +00002237 ExprResult Res =
Richard Smithc8d7f582011-11-29 22:48:16 +00002238 PerformImplicitConversion(From, BeforeToType,
2239 ICS.UserDefined.Before, AA_Converting,
2240 CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002241 if (Res.isInvalid())
2242 return ExprError();
2243 From = Res.take();
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002244 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002245
2246 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00002247 = BuildCXXCastArgument(*this,
2248 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00002249 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002250 CastKind, cast<CXXMethodDecl>(FD),
2251 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002252 ICS.UserDefined.HadMultipleCandidates,
John McCall9ae2f072010-08-23 23:25:46 +00002253 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002254
2255 if (CastArg.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00002256 return ExprError();
Eli Friedmand8889622009-11-27 04:41:50 +00002257
John Wiegley429bb272011-04-08 18:41:53 +00002258 From = CastArg.take();
Eli Friedmand8889622009-11-27 04:41:50 +00002259
Richard Smithc8d7f582011-11-29 22:48:16 +00002260 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2261 AA_Converting, CCK);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00002262 }
John McCall1d318332010-01-12 00:44:57 +00002263
2264 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00002265 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00002266 PDiag(diag::err_typecheck_ambiguous_condition)
2267 << From->getSourceRange());
John Wiegley429bb272011-04-08 18:41:53 +00002268 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002269
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002270 case ImplicitConversionSequence::EllipsisConversion:
David Blaikieb219cfc2011-09-23 05:06:16 +00002271 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002272
2273 case ImplicitConversionSequence::BadConversion:
John Wiegley429bb272011-04-08 18:41:53 +00002274 return ExprError();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002275 }
2276
2277 // Everything went well.
John Wiegley429bb272011-04-08 18:41:53 +00002278 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002279}
2280
Richard Smithc8d7f582011-11-29 22:48:16 +00002281/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002282/// expression From to the type ToType by following the standard
John Wiegley429bb272011-04-08 18:41:53 +00002283/// conversion sequence SCS. Returns the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00002284/// expression. Flavor is the context in which we're performing this
2285/// conversion, for use in error messages.
John Wiegley429bb272011-04-08 18:41:53 +00002286ExprResult
Richard Smithc8d7f582011-11-29 22:48:16 +00002287Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00002288 const StandardConversionSequence& SCS,
John McCallf85e1932011-06-15 23:02:42 +00002289 AssignmentAction Action,
2290 CheckedConversionKind CCK) {
2291 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2292
Mike Stump390b4cc2009-05-16 07:39:55 +00002293 // Overall FIXME: we are recomputing too many types here and doing far too
2294 // much extra work. What this means is that we need to keep track of more
2295 // information that is computed when we try the implicit conversion initially,
2296 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002297 QualType FromType = From->getType();
John McCallf85e1932011-06-15 23:02:42 +00002298
Douglas Gregor225c41e2008-11-03 19:09:14 +00002299 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00002300 // FIXME: When can ToType be a reference type?
2301 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002302 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00002303 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002304 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00002305 MultiExprArg(*this, &From, 1),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002306 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002307 ConstructorArgs))
John Wiegley429bb272011-04-08 18:41:53 +00002308 return ExprError();
2309 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2310 ToType, SCS.CopyConstructor,
2311 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002312 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002313 /*ZeroInit*/ false,
2314 CXXConstructExpr::CK_Complete,
2315 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002316 }
John Wiegley429bb272011-04-08 18:41:53 +00002317 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2318 ToType, SCS.CopyConstructor,
2319 MultiExprArg(*this, &From, 1),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002320 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002321 /*ZeroInit*/ false,
2322 CXXConstructExpr::CK_Complete,
2323 SourceRange());
Douglas Gregor225c41e2008-11-03 19:09:14 +00002324 }
2325
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002326 // Resolve overloaded function references.
2327 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2328 DeclAccessPair Found;
2329 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2330 true, Found);
2331 if (!Fn)
John Wiegley429bb272011-04-08 18:41:53 +00002332 return ExprError();
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002333
2334 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
John Wiegley429bb272011-04-08 18:41:53 +00002335 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002336
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002337 From = FixOverloadedFunctionReference(From, Found, Fn);
2338 FromType = From->getType();
2339 }
2340
Richard Smithc8d7f582011-11-29 22:48:16 +00002341 // Perform the first implicit conversion.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002342 switch (SCS.First) {
2343 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002344 // Nothing to do.
2345 break;
2346
Eli Friedmand814eaf2012-01-24 22:51:26 +00002347 case ICK_Lvalue_To_Rvalue: {
John McCall3c3b7f92011-10-25 17:37:35 +00002348 assert(From->getObjectKind() != OK_ObjCProperty);
John McCallf6a16482010-12-04 03:47:34 +00002349 FromType = FromType.getUnqualifiedType();
Eli Friedmand814eaf2012-01-24 22:51:26 +00002350 ExprResult FromRes = DefaultLvalueConversion(From);
2351 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
2352 From = FromRes.take();
John McCallf6a16482010-12-04 03:47:34 +00002353 break;
Eli Friedmand814eaf2012-01-24 22:51:26 +00002354 }
John McCallf6a16482010-12-04 03:47:34 +00002355
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002356 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002357 FromType = Context.getArrayDecayedType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002358 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2359 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002360 break;
2361
2362 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002363 FromType = Context.getPointerType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002364 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2365 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002366 break;
2367
2368 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002369 llvm_unreachable("Improper first standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002370 }
2371
Richard Smithc8d7f582011-11-29 22:48:16 +00002372 // Perform the second implicit conversion
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002373 switch (SCS.Second) {
2374 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002375 // If both sides are functions (or pointers/references to them), there could
2376 // be incompatible exception declarations.
2377 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002378 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002379 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002380 break;
2381
Douglas Gregor43c79c22009-12-09 00:47:37 +00002382 case ICK_NoReturn_Adjustment:
2383 // If both sides are functions (or pointers/references to them), there could
2384 // be incompatible exception declarations.
2385 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002386 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002387
Richard Smithc8d7f582011-11-29 22:48:16 +00002388 From = ImpCastExprToType(From, ToType, CK_NoOp,
2389 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor43c79c22009-12-09 00:47:37 +00002390 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002391
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002392 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002393 case ICK_Integral_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002394 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2395 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002396 break;
2397
2398 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002399 case ICK_Floating_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002400 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2401 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002402 break;
2403
2404 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00002405 case ICK_Complex_Conversion: {
2406 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2407 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2408 CastKind CK;
2409 if (FromEl->isRealFloatingType()) {
2410 if (ToEl->isRealFloatingType())
2411 CK = CK_FloatingComplexCast;
2412 else
2413 CK = CK_FloatingComplexToIntegralComplex;
2414 } else if (ToEl->isRealFloatingType()) {
2415 CK = CK_IntegralComplexToFloatingComplex;
2416 } else {
2417 CK = CK_IntegralComplexCast;
2418 }
Richard Smithc8d7f582011-11-29 22:48:16 +00002419 From = ImpCastExprToType(From, ToType, CK,
2420 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002421 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00002422 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002423
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002424 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002425 if (ToType->isRealFloatingType())
Richard Smithc8d7f582011-11-29 22:48:16 +00002426 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2427 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002428 else
Richard Smithc8d7f582011-11-29 22:48:16 +00002429 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2430 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002431 break;
2432
Douglas Gregorf9201e02009-02-11 23:02:49 +00002433 case ICK_Compatible_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002434 From = ImpCastExprToType(From, ToType, CK_NoOp,
2435 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002436 break;
2437
John McCallf85e1932011-06-15 23:02:42 +00002438 case ICK_Writeback_Conversion:
Anders Carlsson61faec12009-09-12 04:46:44 +00002439 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00002440 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002441 // Diagnose incompatible Objective-C conversions
Douglas Gregor8cf0d222011-06-11 04:42:12 +00002442 if (Action == AA_Initializing || Action == AA_Assigning)
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002443 Diag(From->getSourceRange().getBegin(),
2444 diag::ext_typecheck_convert_incompatible_pointer)
2445 << ToType << From->getType() << Action
Anna Zaks67221552011-07-28 19:51:27 +00002446 << From->getSourceRange() << 0;
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002447 else
2448 Diag(From->getSourceRange().getBegin(),
2449 diag::ext_typecheck_convert_incompatible_pointer)
2450 << From->getType() << ToType << Action
Anna Zaks67221552011-07-28 19:51:27 +00002451 << From->getSourceRange() << 0;
John McCallf85e1932011-06-15 23:02:42 +00002452
Douglas Gregor926df6c2011-06-11 01:09:30 +00002453 if (From->getType()->isObjCObjectPointerType() &&
2454 ToType->isObjCObjectPointerType())
2455 EmitRelatedResultTypeNote(From);
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002456 }
2457 else if (getLangOptions().ObjCAutoRefCount &&
2458 !CheckObjCARCUnavailableWeakConversion(ToType,
2459 From->getType())) {
John McCall7f3a6d32011-09-09 06:12:06 +00002460 if (Action == AA_Initializing)
2461 Diag(From->getSourceRange().getBegin(),
2462 diag::err_arc_weak_unavailable_assign);
2463 else
2464 Diag(From->getSourceRange().getBegin(),
2465 diag::err_arc_convesion_of_weak_unavailable)
2466 << (Action == AA_Casting) << From->getType() << ToType
2467 << From->getSourceRange();
2468 }
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002469
John McCalldaa8e4e2010-11-15 09:13:47 +00002470 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002471 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002472 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002473 return ExprError();
John McCalldc05b112011-09-10 01:16:55 +00002474
2475 // Make sure we extend blocks if necessary.
2476 // FIXME: doing this here is really ugly.
2477 if (Kind == CK_BlockPointerToObjCPointerCast) {
2478 ExprResult E = From;
2479 (void) PrepareCastToObjCObjectPointer(E);
2480 From = E.take();
2481 }
2482
Richard Smithc8d7f582011-11-29 22:48:16 +00002483 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2484 .take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002485 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00002486 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002487
Anders Carlsson61faec12009-09-12 04:46:44 +00002488 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002489 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002490 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002491 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002492 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002493 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002494 return ExprError();
Richard Smithc8d7f582011-11-29 22:48:16 +00002495 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2496 .take();
Anders Carlsson61faec12009-09-12 04:46:44 +00002497 break;
2498 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002499
Abramo Bagnara737d5442011-04-07 09:26:19 +00002500 case ICK_Boolean_Conversion:
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00002501 // Perform half-to-boolean conversion via float.
2502 if (From->getType()->isHalfType()) {
2503 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take();
2504 FromType = Context.FloatTy;
2505 }
2506
Richard Smithc8d7f582011-11-29 22:48:16 +00002507 From = ImpCastExprToType(From, Context.BoolTy,
2508 ScalarTypeToBooleanCastKind(FromType),
2509 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002510 break;
2511
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002512 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002513 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002514 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002515 ToType.getNonReferenceType(),
2516 From->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002517 From->getSourceRange(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002518 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002519 CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002520 return ExprError();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002521
Richard Smithc8d7f582011-11-29 22:48:16 +00002522 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2523 CK_DerivedToBase, From->getValueKind(),
2524 &BasePath, CCK).take();
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002525 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002526 }
2527
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002528 case ICK_Vector_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002529 From = ImpCastExprToType(From, ToType, CK_BitCast,
2530 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002531 break;
2532
2533 case ICK_Vector_Splat:
Richard Smithc8d7f582011-11-29 22:48:16 +00002534 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2535 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002536 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002537
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002538 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002539 // Case 1. x -> _Complex y
2540 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2541 QualType ElType = ToComplex->getElementType();
2542 bool isFloatingComplex = ElType->isRealFloatingType();
2543
2544 // x -> y
2545 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2546 // do nothing
2547 } else if (From->getType()->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002548 From = ImpCastExprToType(From, ElType,
2549 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002550 } else {
2551 assert(From->getType()->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002552 From = ImpCastExprToType(From, ElType,
2553 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002554 }
2555 // y -> _Complex y
Richard Smithc8d7f582011-11-29 22:48:16 +00002556 From = ImpCastExprToType(From, ToType,
2557 isFloatingComplex ? CK_FloatingRealToComplex
2558 : CK_IntegralRealToComplex).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002559
2560 // Case 2. _Complex x -> y
2561 } else {
2562 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2563 assert(FromComplex);
2564
2565 QualType ElType = FromComplex->getElementType();
2566 bool isFloatingComplex = ElType->isRealFloatingType();
2567
2568 // _Complex x -> x
Richard Smithc8d7f582011-11-29 22:48:16 +00002569 From = ImpCastExprToType(From, ElType,
2570 isFloatingComplex ? CK_FloatingComplexToReal
2571 : CK_IntegralComplexToReal,
2572 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002573
2574 // x -> y
2575 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2576 // do nothing
2577 } else if (ToType->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002578 From = ImpCastExprToType(From, ToType,
2579 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2580 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002581 } else {
2582 assert(ToType->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002583 From = ImpCastExprToType(From, ToType,
2584 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2585 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002586 }
2587 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002588 break;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002589
2590 case ICK_Block_Pointer_Conversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002591 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2592 VK_RValue, /*BasePath=*/0, CCK).take();
John McCallf85e1932011-06-15 23:02:42 +00002593 break;
2594 }
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002595
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002596 case ICK_TransparentUnionConversion: {
John Wiegley429bb272011-04-08 18:41:53 +00002597 ExprResult FromRes = Owned(From);
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002598 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002599 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2600 if (FromRes.isInvalid())
2601 return ExprError();
2602 From = FromRes.take();
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002603 assert ((ConvTy == Sema::Compatible) &&
2604 "Improper transparent union conversion");
2605 (void)ConvTy;
2606 break;
2607 }
2608
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002609 case ICK_Lvalue_To_Rvalue:
2610 case ICK_Array_To_Pointer:
2611 case ICK_Function_To_Pointer:
2612 case ICK_Qualification:
2613 case ICK_Num_Conversion_Kinds:
David Blaikieb219cfc2011-09-23 05:06:16 +00002614 llvm_unreachable("Improper second standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002615 }
2616
2617 switch (SCS.Third) {
2618 case ICK_Identity:
2619 // Nothing to do.
2620 break;
2621
Sebastian Redl906082e2010-07-20 04:20:21 +00002622 case ICK_Qualification: {
2623 // The qualification keeps the category of the inner expression, unless the
2624 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002625 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002626 From->getValueKind() : VK_RValue;
Richard Smithc8d7f582011-11-29 22:48:16 +00002627 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2628 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
Douglas Gregora9bff302010-02-28 18:30:25 +00002629
Douglas Gregor069a6da2011-03-14 16:13:32 +00002630 if (SCS.DeprecatedStringLiteralToCharPtr &&
2631 !getLangOptions().WritableStrings)
Douglas Gregora9bff302010-02-28 18:30:25 +00002632 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2633 << ToType.getNonReferenceType();
2634
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002635 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002636 }
2637
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002638 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002639 llvm_unreachable("Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002640 }
2641
John Wiegley429bb272011-04-08 18:41:53 +00002642 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002643}
2644
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002645ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002646 SourceLocation KWLoc,
2647 ParsedType Ty,
2648 SourceLocation RParen) {
2649 TypeSourceInfo *TSInfo;
2650 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002651
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002652 if (!TSInfo)
2653 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002654 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002655}
2656
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002657/// \brief Check the completeness of a type in a unary type trait.
2658///
2659/// If the particular type trait requires a complete type, tries to complete
2660/// it. If completing the type fails, a diagnostic is emitted and false
2661/// returned. If completing the type succeeds or no completion was required,
2662/// returns true.
2663static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2664 UnaryTypeTrait UTT,
2665 SourceLocation Loc,
2666 QualType ArgTy) {
2667 // C++0x [meta.unary.prop]p3:
2668 // For all of the class templates X declared in this Clause, instantiating
2669 // that template with a template argument that is a class template
2670 // specialization may result in the implicit instantiation of the template
2671 // argument if and only if the semantics of X require that the argument
2672 // must be a complete type.
2673 // We apply this rule to all the type trait expressions used to implement
2674 // these class templates. We also try to follow any GCC documented behavior
2675 // in these expressions to ensure portability of standard libraries.
2676 switch (UTT) {
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002677 // is_complete_type somewhat obviously cannot require a complete type.
2678 case UTT_IsCompleteType:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002679 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002680
2681 // These traits are modeled on the type predicates in C++0x
2682 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2683 // requiring a complete type, as whether or not they return true cannot be
2684 // impacted by the completeness of the type.
2685 case UTT_IsVoid:
2686 case UTT_IsIntegral:
2687 case UTT_IsFloatingPoint:
2688 case UTT_IsArray:
2689 case UTT_IsPointer:
2690 case UTT_IsLvalueReference:
2691 case UTT_IsRvalueReference:
2692 case UTT_IsMemberFunctionPointer:
2693 case UTT_IsMemberObjectPointer:
2694 case UTT_IsEnum:
2695 case UTT_IsUnion:
2696 case UTT_IsClass:
2697 case UTT_IsFunction:
2698 case UTT_IsReference:
2699 case UTT_IsArithmetic:
2700 case UTT_IsFundamental:
2701 case UTT_IsObject:
2702 case UTT_IsScalar:
2703 case UTT_IsCompound:
2704 case UTT_IsMemberPointer:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002705 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002706
2707 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2708 // which requires some of its traits to have the complete type. However,
2709 // the completeness of the type cannot impact these traits' semantics, and
2710 // so they don't require it. This matches the comments on these traits in
2711 // Table 49.
2712 case UTT_IsConst:
2713 case UTT_IsVolatile:
2714 case UTT_IsSigned:
2715 case UTT_IsUnsigned:
2716 return true;
2717
2718 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002719 // applied to a complete type.
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002720 case UTT_IsTrivial:
Sean Huntfeb375d2011-05-13 00:31:07 +00002721 case UTT_IsTriviallyCopyable:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002722 case UTT_IsStandardLayout:
2723 case UTT_IsPOD:
2724 case UTT_IsLiteral:
2725 case UTT_IsEmpty:
2726 case UTT_IsPolymorphic:
2727 case UTT_IsAbstract:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002728 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002729
Douglas Gregor5e9392b2011-12-03 18:14:24 +00002730 // These traits require a complete type.
2731 case UTT_IsFinal:
2732
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002733 // These trait expressions are designed to help implement predicates in
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002734 // [meta.unary.prop] despite not being named the same. They are specified
2735 // by both GCC and the Embarcadero C++ compiler, and require the complete
2736 // type due to the overarching C++0x type predicates being implemented
2737 // requiring the complete type.
2738 case UTT_HasNothrowAssign:
2739 case UTT_HasNothrowConstructor:
2740 case UTT_HasNothrowCopy:
2741 case UTT_HasTrivialAssign:
Sean Hunt023df372011-05-09 18:22:59 +00002742 case UTT_HasTrivialDefaultConstructor:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002743 case UTT_HasTrivialCopy:
2744 case UTT_HasTrivialDestructor:
2745 case UTT_HasVirtualDestructor:
2746 // Arrays of unknown bound are expressly allowed.
2747 QualType ElTy = ArgTy;
2748 if (ArgTy->isIncompleteArrayType())
2749 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2750
2751 // The void type is expressly allowed.
2752 if (ElTy->isVoidType())
2753 return true;
2754
2755 return !S.RequireCompleteType(
2756 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleycf566412011-04-28 02:06:46 +00002757 }
Chandler Carruth73e0a912011-05-01 07:23:17 +00002758 llvm_unreachable("Type trait not handled by switch");
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002759}
2760
2761static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2762 SourceLocation KeyLoc, QualType T) {
Chandler Carruthd064c702011-05-01 08:41:10 +00002763 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleycf566412011-04-28 02:06:46 +00002764
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002765 ASTContext &C = Self.Context;
2766 switch(UTT) {
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002767 // Type trait expressions corresponding to the primary type category
2768 // predicates in C++0x [meta.unary.cat].
2769 case UTT_IsVoid:
2770 return T->isVoidType();
2771 case UTT_IsIntegral:
2772 return T->isIntegralType(C);
2773 case UTT_IsFloatingPoint:
2774 return T->isFloatingType();
2775 case UTT_IsArray:
2776 return T->isArrayType();
2777 case UTT_IsPointer:
2778 return T->isPointerType();
2779 case UTT_IsLvalueReference:
2780 return T->isLValueReferenceType();
2781 case UTT_IsRvalueReference:
2782 return T->isRValueReferenceType();
2783 case UTT_IsMemberFunctionPointer:
2784 return T->isMemberFunctionPointerType();
2785 case UTT_IsMemberObjectPointer:
2786 return T->isMemberDataPointerType();
2787 case UTT_IsEnum:
2788 return T->isEnumeralType();
Chandler Carruth28eeb382011-05-01 06:11:03 +00002789 case UTT_IsUnion:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002790 return T->isUnionType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002791 case UTT_IsClass:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002792 return T->isClassType() || T->isStructureType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002793 case UTT_IsFunction:
2794 return T->isFunctionType();
2795
2796 // Type trait expressions which correspond to the convenient composition
2797 // predicates in C++0x [meta.unary.comp].
2798 case UTT_IsReference:
2799 return T->isReferenceType();
2800 case UTT_IsArithmetic:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002801 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002802 case UTT_IsFundamental:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002803 return T->isFundamentalType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002804 case UTT_IsObject:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002805 return T->isObjectType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002806 case UTT_IsScalar:
John McCallf85e1932011-06-15 23:02:42 +00002807 // Note: semantic analysis depends on Objective-C lifetime types to be
2808 // considered scalar types. However, such types do not actually behave
2809 // like scalar types at run time (since they may require retain/release
2810 // operations), so we report them as non-scalar.
2811 if (T->isObjCLifetimeType()) {
2812 switch (T.getObjCLifetime()) {
2813 case Qualifiers::OCL_None:
2814 case Qualifiers::OCL_ExplicitNone:
2815 return true;
2816
2817 case Qualifiers::OCL_Strong:
2818 case Qualifiers::OCL_Weak:
2819 case Qualifiers::OCL_Autoreleasing:
2820 return false;
2821 }
2822 }
2823
Chandler Carruthcec0ced2011-05-01 09:29:55 +00002824 return T->isScalarType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002825 case UTT_IsCompound:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002826 return T->isCompoundType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002827 case UTT_IsMemberPointer:
2828 return T->isMemberPointerType();
2829
2830 // Type trait expressions which correspond to the type property predicates
2831 // in C++0x [meta.unary.prop].
2832 case UTT_IsConst:
2833 return T.isConstQualified();
2834 case UTT_IsVolatile:
2835 return T.isVolatileQualified();
2836 case UTT_IsTrivial:
John McCallf85e1932011-06-15 23:02:42 +00002837 return T.isTrivialType(Self.Context);
Sean Huntfeb375d2011-05-13 00:31:07 +00002838 case UTT_IsTriviallyCopyable:
John McCallf85e1932011-06-15 23:02:42 +00002839 return T.isTriviallyCopyableType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002840 case UTT_IsStandardLayout:
2841 return T->isStandardLayoutType();
2842 case UTT_IsPOD:
John McCallf85e1932011-06-15 23:02:42 +00002843 return T.isPODType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002844 case UTT_IsLiteral:
2845 return T->isLiteralType();
2846 case UTT_IsEmpty:
2847 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2848 return !RD->isUnion() && RD->isEmpty();
2849 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002850 case UTT_IsPolymorphic:
Chandler Carruth28eeb382011-05-01 06:11:03 +00002851 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2852 return RD->isPolymorphic();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002853 return false;
2854 case UTT_IsAbstract:
Chandler Carruth28eeb382011-05-01 06:11:03 +00002855 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2856 return RD->isAbstract();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002857 return false;
Douglas Gregor5e9392b2011-12-03 18:14:24 +00002858 case UTT_IsFinal:
2859 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2860 return RD->hasAttr<FinalAttr>();
2861 return false;
John Wiegley20c0da72011-04-27 23:09:49 +00002862 case UTT_IsSigned:
2863 return T->isSignedIntegerType();
John Wiegley20c0da72011-04-27 23:09:49 +00002864 case UTT_IsUnsigned:
2865 return T->isUnsignedIntegerType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002866
2867 // Type trait expressions which query classes regarding their construction,
2868 // destruction, and copying. Rather than being based directly on the
2869 // related type predicates in the standard, they are specified by both
2870 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
2871 // specifications.
2872 //
2873 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
2874 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Sean Hunt023df372011-05-09 18:22:59 +00002875 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002876 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2877 // If __is_pod (type) is true then the trait is true, else if type is
2878 // a cv class or union type (or array thereof) with a trivial default
2879 // constructor ([class.ctor]) then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002880 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002881 return true;
2882 if (const RecordType *RT =
2883 C.getBaseElementType(T)->getAs<RecordType>())
Sean Hunt023df372011-05-09 18:22:59 +00002884 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002885 return false;
2886 case UTT_HasTrivialCopy:
2887 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2888 // If __is_pod (type) is true or type is a reference type then
2889 // the trait is true, else if type is a cv class or union type
2890 // with a trivial copy constructor ([class.copy]) then the trait
2891 // is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002892 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002893 return true;
2894 if (const RecordType *RT = T->getAs<RecordType>())
2895 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2896 return false;
2897 case UTT_HasTrivialAssign:
2898 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2899 // If type is const qualified or is a reference type then the
2900 // trait is false. Otherwise if __is_pod (type) is true then the
2901 // trait is true, else if type is a cv class or union type with
2902 // a trivial copy assignment ([class.copy]) then the trait is
2903 // true, else it is false.
2904 // Note: the const and reference restrictions are interesting,
2905 // given that const and reference members don't prevent a class
2906 // from having a trivial copy assignment operator (but do cause
2907 // errors if the copy assignment operator is actually used, q.v.
2908 // [class.copy]p12).
2909
2910 if (C.getBaseElementType(T).isConstQualified())
2911 return false;
John McCallf85e1932011-06-15 23:02:42 +00002912 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002913 return true;
2914 if (const RecordType *RT = T->getAs<RecordType>())
2915 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2916 return false;
2917 case UTT_HasTrivialDestructor:
2918 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2919 // If __is_pod (type) is true or type is a reference type
2920 // then the trait is true, else if type is a cv class or union
2921 // type (or array thereof) with a trivial destructor
2922 // ([class.dtor]) then the trait is true, else it is
2923 // false.
John McCallf85e1932011-06-15 23:02:42 +00002924 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002925 return true;
John McCallf85e1932011-06-15 23:02:42 +00002926
2927 // Objective-C++ ARC: autorelease types don't require destruction.
2928 if (T->isObjCLifetimeType() &&
2929 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
2930 return true;
2931
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002932 if (const RecordType *RT =
2933 C.getBaseElementType(T)->getAs<RecordType>())
2934 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2935 return false;
2936 // TODO: Propagate nothrowness for implicitly declared special members.
2937 case UTT_HasNothrowAssign:
2938 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2939 // If type is const qualified or is a reference type then the
2940 // trait is false. Otherwise if __has_trivial_assign (type)
2941 // is true then the trait is true, else if type is a cv class
2942 // or union type with copy assignment operators that are known
2943 // not to throw an exception then the trait is true, else it is
2944 // false.
2945 if (C.getBaseElementType(T).isConstQualified())
2946 return false;
2947 if (T->isReferenceType())
2948 return false;
John McCallf85e1932011-06-15 23:02:42 +00002949 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
2950 return true;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002951 if (const RecordType *RT = T->getAs<RecordType>()) {
2952 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2953 if (RD->hasTrivialCopyAssignment())
2954 return true;
2955
2956 bool FoundAssign = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002957 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00002958 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2959 Sema::LookupOrdinaryName);
2960 if (Self.LookupQualifiedName(Res, RD)) {
Douglas Gregord41679d2011-10-12 15:40:49 +00002961 Res.suppressDiagnostics();
Sebastian Redlf8aca862010-09-14 23:40:14 +00002962 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2963 Op != OpEnd; ++Op) {
Douglas Gregord41679d2011-10-12 15:40:49 +00002964 if (isa<FunctionTemplateDecl>(*Op))
2965 continue;
2966
Sebastian Redlf8aca862010-09-14 23:40:14 +00002967 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2968 if (Operator->isCopyAssignmentOperator()) {
2969 FoundAssign = true;
2970 const FunctionProtoType *CPT
2971 = Operator->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00002972 if (CPT->getExceptionSpecType() == EST_Delayed)
2973 return false;
2974 if (!CPT->isNothrow(Self.Context))
2975 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002976 }
2977 }
2978 }
Douglas Gregord41679d2011-10-12 15:40:49 +00002979
Richard Smith7a614d82011-06-11 17:19:42 +00002980 return FoundAssign;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002981 }
2982 return false;
2983 case UTT_HasNothrowCopy:
2984 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2985 // If __has_trivial_copy (type) is true then the trait is true, else
2986 // if type is a cv class or union type with copy constructors that are
2987 // known not to throw an exception then the trait is true, else it is
2988 // false.
John McCallf85e1932011-06-15 23:02:42 +00002989 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002990 return true;
2991 if (const RecordType *RT = T->getAs<RecordType>()) {
2992 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2993 if (RD->hasTrivialCopyConstructor())
2994 return true;
2995
2996 bool FoundConstructor = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002997 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002998 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00002999 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003000 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00003001 // A template constructor is never a copy constructor.
3002 // FIXME: However, it may actually be selected at the actual overload
3003 // resolution point.
3004 if (isa<FunctionTemplateDecl>(*Con))
3005 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003006 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3007 if (Constructor->isCopyConstructor(FoundTQs)) {
3008 FoundConstructor = true;
3009 const FunctionProtoType *CPT
3010 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00003011 if (CPT->getExceptionSpecType() == EST_Delayed)
3012 return false;
Sebastian Redl60618fa2011-03-12 11:50:43 +00003013 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redl751025d2010-09-13 22:02:47 +00003014 // For now, we'll be conservative and assume that they can throw.
Richard Smith7a614d82011-06-11 17:19:42 +00003015 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
3016 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003017 }
3018 }
3019
Richard Smith7a614d82011-06-11 17:19:42 +00003020 return FoundConstructor;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003021 }
3022 return false;
3023 case UTT_HasNothrowConstructor:
3024 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3025 // If __has_trivial_constructor (type) is true then the trait is
3026 // true, else if type is a cv class or union type (or array
3027 // thereof) with a default constructor that is known not to
3028 // throw an exception then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00003029 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003030 return true;
3031 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
3032 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Hunt023df372011-05-09 18:22:59 +00003033 if (RD->hasTrivialDefaultConstructor())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003034 return true;
3035
Sebastian Redl751025d2010-09-13 22:02:47 +00003036 DeclContext::lookup_const_iterator Con, ConEnd;
3037 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
3038 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00003039 // FIXME: In C++0x, a constructor template can be a default constructor.
3040 if (isa<FunctionTemplateDecl>(*Con))
3041 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00003042 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3043 if (Constructor->isDefaultConstructor()) {
3044 const FunctionProtoType *CPT
3045 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00003046 if (CPT->getExceptionSpecType() == EST_Delayed)
3047 return false;
Sebastian Redl751025d2010-09-13 22:02:47 +00003048 // TODO: check whether evaluating default arguments can throw.
3049 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00003050 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
Sebastian Redl751025d2010-09-13 22:02:47 +00003051 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003052 }
3053 }
3054 return false;
3055 case UTT_HasVirtualDestructor:
3056 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3057 // If type is a class type with a virtual destructor ([class.dtor])
3058 // then the trait is true, else it is false.
3059 if (const RecordType *Record = T->getAs<RecordType>()) {
3060 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00003061 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003062 return Destructor->isVirtual();
3063 }
3064 return false;
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003065
3066 // These type trait expressions are modeled on the specifications for the
3067 // Embarcadero C++0x type trait functions:
3068 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3069 case UTT_IsCompleteType:
3070 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3071 // Returns True if and only if T is a complete type at the point of the
3072 // function call.
3073 return !T->isIncompleteType();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003074 }
Chandler Carruth83f563c2011-05-01 07:44:17 +00003075 llvm_unreachable("Type trait not covered by switch");
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003076}
3077
3078ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00003079 SourceLocation KWLoc,
3080 TypeSourceInfo *TSInfo,
3081 SourceLocation RParen) {
3082 QualType T = TSInfo->getType();
Chandler Carrutheb65a102011-04-30 10:07:32 +00003083 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
3084 return ExprError();
Sebastian Redl64b45f72009-01-05 20:52:13 +00003085
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003086 bool Value = false;
3087 if (!T->isDependentType())
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00003088 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003089
3090 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00003091 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00003092}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003093
Francois Pichet6ad6f282010-12-07 00:08:36 +00003094ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
3095 SourceLocation KWLoc,
3096 ParsedType LhsTy,
3097 ParsedType RhsTy,
3098 SourceLocation RParen) {
3099 TypeSourceInfo *LhsTSInfo;
3100 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3101 if (!LhsTSInfo)
3102 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3103
3104 TypeSourceInfo *RhsTSInfo;
3105 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3106 if (!RhsTSInfo)
3107 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3108
3109 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3110}
3111
3112static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3113 QualType LhsT, QualType RhsT,
3114 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003115 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3116 "Cannot evaluate traits of dependent types");
Francois Pichet6ad6f282010-12-07 00:08:36 +00003117
3118 switch(BTT) {
John McCalld89d30f2011-01-28 22:02:36 +00003119 case BTT_IsBaseOf: {
Francois Pichet6ad6f282010-12-07 00:08:36 +00003120 // C++0x [meta.rel]p2
John McCalld89d30f2011-01-28 22:02:36 +00003121 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet6ad6f282010-12-07 00:08:36 +00003122 // Base and Derived are not unions and name the same class type without
3123 // regard to cv-qualifiers.
Francois Pichet6ad6f282010-12-07 00:08:36 +00003124
John McCalld89d30f2011-01-28 22:02:36 +00003125 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3126 if (!lhsRecord) return false;
3127
3128 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3129 if (!rhsRecord) return false;
3130
3131 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3132 == (lhsRecord == rhsRecord));
3133
3134 if (lhsRecord == rhsRecord)
3135 return !lhsRecord->getDecl()->isUnion();
3136
3137 // C++0x [meta.rel]p2:
3138 // If Base and Derived are class types and are different types
3139 // (ignoring possible cv-qualifiers) then Derived shall be a
3140 // complete type.
3141 if (Self.RequireCompleteType(KeyLoc, RhsT,
3142 diag::err_incomplete_type_used_in_type_trait_expr))
3143 return false;
3144
3145 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3146 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3147 }
John Wiegley20c0da72011-04-27 23:09:49 +00003148 case BTT_IsSame:
3149 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichetf1872372010-12-08 22:35:30 +00003150 case BTT_TypeCompatible:
3151 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3152 RhsT.getUnqualifiedType());
John Wiegley20c0da72011-04-27 23:09:49 +00003153 case BTT_IsConvertible:
Douglas Gregor9f361132011-01-27 20:28:01 +00003154 case BTT_IsConvertibleTo: {
3155 // C++0x [meta.rel]p4:
3156 // Given the following function prototype:
3157 //
3158 // template <class T>
3159 // typename add_rvalue_reference<T>::type create();
3160 //
3161 // the predicate condition for a template specialization
3162 // is_convertible<From, To> shall be satisfied if and only if
3163 // the return expression in the following code would be
3164 // well-formed, including any implicit conversions to the return
3165 // type of the function:
3166 //
3167 // To test() {
3168 // return create<From>();
3169 // }
3170 //
3171 // Access checking is performed as if in a context unrelated to To and
3172 // From. Only the validity of the immediate context of the expression
3173 // of the return-statement (including conversions to the return type)
3174 // is considered.
3175 //
3176 // We model the initialization as a copy-initialization of a temporary
3177 // of the appropriate type, which for this expression is identical to the
3178 // return statement (since NRVO doesn't apply).
3179 if (LhsT->isObjectType() || LhsT->isFunctionType())
3180 LhsT = Self.Context.getRValueReferenceType(LhsT);
3181
3182 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorb608b982011-01-28 02:26:04 +00003183 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor9f361132011-01-27 20:28:01 +00003184 Expr::getValueKindForType(LhsT));
3185 Expr *FromPtr = &From;
3186 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3187 SourceLocation()));
3188
Eli Friedman3add9f02012-01-25 01:05:57 +00003189 // Perform the initialization in an unevaluated context within a SFINAE
3190 // trap at translation unit scope.
3191 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003192 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3193 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor9f361132011-01-27 20:28:01 +00003194 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003195 if (Init.Failed())
Douglas Gregor9f361132011-01-27 20:28:01 +00003196 return false;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003197
Douglas Gregor9f361132011-01-27 20:28:01 +00003198 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
3199 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3200 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003201 }
3202 llvm_unreachable("Unknown type trait or not implemented");
3203}
3204
3205ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3206 SourceLocation KWLoc,
3207 TypeSourceInfo *LhsTSInfo,
3208 TypeSourceInfo *RhsTSInfo,
3209 SourceLocation RParen) {
3210 QualType LhsT = LhsTSInfo->getType();
3211 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003212
John McCalld89d30f2011-01-28 22:02:36 +00003213 if (BTT == BTT_TypeCompatible) {
Francois Pichetf1872372010-12-08 22:35:30 +00003214 if (getLangOptions().CPlusPlus) {
3215 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3216 << SourceRange(KWLoc, RParen);
3217 return ExprError();
3218 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003219 }
3220
3221 bool Value = false;
3222 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3223 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3224
Francois Pichetf1872372010-12-08 22:35:30 +00003225 // Select trait result type.
3226 QualType ResultType;
3227 switch (BTT) {
Francois Pichetf1872372010-12-08 22:35:30 +00003228 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
John Wiegley20c0da72011-04-27 23:09:49 +00003229 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3230 case BTT_IsSame: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003231 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor9f361132011-01-27 20:28:01 +00003232 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003233 }
3234
Francois Pichet6ad6f282010-12-07 00:08:36 +00003235 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3236 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00003237 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00003238}
3239
John Wiegley21ff2e52011-04-28 00:16:57 +00003240ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3241 SourceLocation KWLoc,
3242 ParsedType Ty,
3243 Expr* DimExpr,
3244 SourceLocation RParen) {
3245 TypeSourceInfo *TSInfo;
3246 QualType T = GetTypeFromParser(Ty, &TSInfo);
3247 if (!TSInfo)
3248 TSInfo = Context.getTrivialTypeSourceInfo(T);
3249
3250 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3251}
3252
3253static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3254 QualType T, Expr *DimExpr,
3255 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003256 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley21ff2e52011-04-28 00:16:57 +00003257
3258 switch(ATT) {
3259 case ATT_ArrayRank:
3260 if (T->isArrayType()) {
3261 unsigned Dim = 0;
3262 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3263 ++Dim;
3264 T = AT->getElementType();
3265 }
3266 return Dim;
John Wiegley21ff2e52011-04-28 00:16:57 +00003267 }
John Wiegleycf566412011-04-28 02:06:46 +00003268 return 0;
3269
John Wiegley21ff2e52011-04-28 00:16:57 +00003270 case ATT_ArrayExtent: {
3271 llvm::APSInt Value;
3272 uint64_t Dim;
Richard Smith282e7e62012-02-04 09:53:13 +00003273 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
3274 Self.PDiag(diag::err_dimension_expr_not_constant_integer),
3275 false).isInvalid())
3276 return 0;
3277 if (Value.isSigned() && Value.isNegative()) {
3278 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer),
John Wiegleycf566412011-04-28 02:06:46 +00003279 DimExpr->getSourceRange();
Richard Smith282e7e62012-02-04 09:53:13 +00003280 return 0;
John Wiegleycf566412011-04-28 02:06:46 +00003281 }
Richard Smith282e7e62012-02-04 09:53:13 +00003282 Dim = Value.getLimitedValue();
John Wiegley21ff2e52011-04-28 00:16:57 +00003283
3284 if (T->isArrayType()) {
3285 unsigned D = 0;
3286 bool Matched = false;
3287 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3288 if (Dim == D) {
3289 Matched = true;
3290 break;
3291 }
3292 ++D;
3293 T = AT->getElementType();
3294 }
3295
John Wiegleycf566412011-04-28 02:06:46 +00003296 if (Matched && T->isArrayType()) {
3297 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3298 return CAT->getSize().getLimitedValue();
3299 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003300 }
John Wiegleycf566412011-04-28 02:06:46 +00003301 return 0;
John Wiegley21ff2e52011-04-28 00:16:57 +00003302 }
3303 }
3304 llvm_unreachable("Unknown type trait or not implemented");
3305}
3306
3307ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3308 SourceLocation KWLoc,
3309 TypeSourceInfo *TSInfo,
3310 Expr* DimExpr,
3311 SourceLocation RParen) {
3312 QualType T = TSInfo->getType();
John Wiegley21ff2e52011-04-28 00:16:57 +00003313
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003314 // FIXME: This should likely be tracked as an APInt to remove any host
3315 // assumptions about the width of size_t on the target.
Chandler Carruthd064c702011-05-01 08:41:10 +00003316 uint64_t Value = 0;
3317 if (!T->isDependentType())
3318 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3319
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003320 // While the specification for these traits from the Embarcadero C++
3321 // compiler's documentation says the return type is 'unsigned int', Clang
3322 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3323 // compiler, there is no difference. On several other platforms this is an
3324 // important distinction.
John Wiegley21ff2e52011-04-28 00:16:57 +00003325 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
Chandler Carruth06207f62011-05-01 07:49:26 +00003326 DimExpr, RParen,
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003327 Context.getSizeType()));
John Wiegley21ff2e52011-04-28 00:16:57 +00003328}
3329
John Wiegley55262202011-04-25 06:54:41 +00003330ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003331 SourceLocation KWLoc,
3332 Expr *Queried,
3333 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003334 // If error parsing the expression, ignore.
3335 if (!Queried)
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003336 return ExprError();
John Wiegley55262202011-04-25 06:54:41 +00003337
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003338 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegley55262202011-04-25 06:54:41 +00003339
3340 return move(Result);
3341}
3342
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003343static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3344 switch (ET) {
3345 case ET_IsLValueExpr: return E->isLValue();
3346 case ET_IsRValueExpr: return E->isRValue();
3347 }
3348 llvm_unreachable("Expression trait not covered by switch");
3349}
3350
John Wiegley55262202011-04-25 06:54:41 +00003351ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003352 SourceLocation KWLoc,
3353 Expr *Queried,
3354 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003355 if (Queried->isTypeDependent()) {
3356 // Delay type-checking for type-dependent expressions.
3357 } else if (Queried->getType()->isPlaceholderType()) {
3358 ExprResult PE = CheckPlaceholderExpr(Queried);
3359 if (PE.isInvalid()) return ExprError();
3360 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3361 }
3362
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003363 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf7ef0002011-05-01 08:48:19 +00003364
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003365 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3366 RParen, Context.BoolTy));
John Wiegley55262202011-04-25 06:54:41 +00003367}
3368
Richard Trieudd225092011-09-15 21:56:47 +00003369QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCallf89e55a2010-11-18 06:31:45 +00003370 ExprValueKind &VK,
3371 SourceLocation Loc,
3372 bool isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003373 assert(!LHS.get()->getType()->isPlaceholderType() &&
3374 !RHS.get()->getType()->isPlaceholderType() &&
John McCallea4aba02011-06-30 17:15:34 +00003375 "placeholders should have been weeded out by now");
3376
3377 // The LHS undergoes lvalue conversions if this is ->*.
3378 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003379 LHS = DefaultLvalueConversion(LHS.take());
3380 if (LHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003381 }
3382
3383 // The RHS always undergoes lvalue conversions.
Richard Trieudd225092011-09-15 21:56:47 +00003384 RHS = DefaultLvalueConversion(RHS.take());
3385 if (RHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003386
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003387 const char *OpSpelling = isIndirect ? "->*" : ".*";
3388 // C++ 5.5p2
3389 // The binary operator .* [p3: ->*] binds its second operand, which shall
3390 // be of type "pointer to member of T" (where T is a completely-defined
3391 // class type) [...]
Richard Trieudd225092011-09-15 21:56:47 +00003392 QualType RHSType = RHS.get()->getType();
3393 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00003394 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003395 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieudd225092011-09-15 21:56:47 +00003396 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003397 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00003398 }
Douglas Gregore7450f52009-03-24 19:52:54 +00003399
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003400 QualType Class(MemPtr->getClass(), 0);
3401
Douglas Gregor7d520ba2010-10-13 20:41:14 +00003402 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3403 // member pointer points must be completely-defined. However, there is no
3404 // reason for this semantic distinction, and the rule is not enforced by
3405 // other compilers. Therefore, we do not check this property, as it is
3406 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00003407
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003408 // C++ 5.5p2
3409 // [...] to its first operand, which shall be of class T or of a class of
3410 // which T is an unambiguous and accessible base class. [p3: a pointer to
3411 // such a class]
Richard Trieudd225092011-09-15 21:56:47 +00003412 QualType LHSType = LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003413 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003414 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
3415 LHSType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003416 else {
3417 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieudd225092011-09-15 21:56:47 +00003418 << OpSpelling << 1 << LHSType
Douglas Gregor849b2432010-03-31 17:46:05 +00003419 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003420 return QualType();
3421 }
3422 }
3423
Richard Trieudd225092011-09-15 21:56:47 +00003424 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00003425 // If we want to check the hierarchy, we need a complete type.
Richard Trieudd225092011-09-15 21:56:47 +00003426 if (RequireCompleteType(Loc, LHSType, PDiag(diag::err_bad_memptr_lhs)
Sebastian Redl17e1d352010-04-23 17:18:26 +00003427 << OpSpelling << (int)isIndirect)) {
3428 return QualType();
3429 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003430 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00003431 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00003432 // FIXME: Would it be useful to print full ambiguity paths, or is that
3433 // overkill?
Richard Trieudd225092011-09-15 21:56:47 +00003434 if (!IsDerivedFrom(LHSType, Class, Paths) ||
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003435 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3436 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieudd225092011-09-15 21:56:47 +00003437 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003438 return QualType();
3439 }
Eli Friedman3005efe2010-01-16 00:00:48 +00003440 // Cast LHS to type of use.
3441 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00003442 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00003443
John McCallf871d0c2010-08-07 06:22:56 +00003444 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003445 BuildBasePathArray(Paths, BasePath);
Richard Trieudd225092011-09-15 21:56:47 +00003446 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
3447 &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003448 }
3449
Richard Trieudd225092011-09-15 21:56:47 +00003450 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00003451 // Diagnose use of pointer-to-member type which when used as
3452 // the functional cast in a pointer-to-member expression.
3453 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3454 return QualType();
3455 }
John McCallf89e55a2010-11-18 06:31:45 +00003456
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003457 // C++ 5.5p2
3458 // The result is an object or a function of the type specified by the
3459 // second operand.
3460 // The cv qualifiers are the union of those in the pointer and the left side,
3461 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003462 QualType Result = MemPtr->getPointeeType();
Richard Trieudd225092011-09-15 21:56:47 +00003463 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00003464
Douglas Gregor6b4df912011-01-26 16:40:18 +00003465 // C++0x [expr.mptr.oper]p6:
3466 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003467 // ill-formed if the second operand is a pointer to member function with
3468 // ref-qualifier &. In a ->* expression or in a .* expression whose object
3469 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor6b4df912011-01-26 16:40:18 +00003470 // is a pointer to member function with ref-qualifier &&.
3471 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3472 switch (Proto->getRefQualifier()) {
3473 case RQ_None:
3474 // Do nothing
3475 break;
3476
3477 case RQ_LValue:
Richard Trieudd225092011-09-15 21:56:47 +00003478 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003479 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003480 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003481 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003482
Douglas Gregor6b4df912011-01-26 16:40:18 +00003483 case RQ_RValue:
Richard Trieudd225092011-09-15 21:56:47 +00003484 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003485 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003486 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003487 break;
3488 }
3489 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003490
John McCallf89e55a2010-11-18 06:31:45 +00003491 // C++ [expr.mptr.oper]p6:
3492 // The result of a .* expression whose second operand is a pointer
3493 // to a data member is of the same value category as its
3494 // first operand. The result of a .* expression whose second
3495 // operand is a pointer to a member function is a prvalue. The
3496 // result of an ->* expression is an lvalue if its second operand
3497 // is a pointer to data member and a prvalue otherwise.
John McCall864c0412011-04-26 20:42:42 +00003498 if (Result->isFunctionType()) {
John McCallf89e55a2010-11-18 06:31:45 +00003499 VK = VK_RValue;
John McCall864c0412011-04-26 20:42:42 +00003500 return Context.BoundMemberTy;
3501 } else if (isIndirect) {
John McCallf89e55a2010-11-18 06:31:45 +00003502 VK = VK_LValue;
John McCall864c0412011-04-26 20:42:42 +00003503 } else {
Richard Trieudd225092011-09-15 21:56:47 +00003504 VK = LHS.get()->getValueKind();
John McCall864c0412011-04-26 20:42:42 +00003505 }
John McCallf89e55a2010-11-18 06:31:45 +00003506
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003507 return Result;
3508}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003509
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003510/// \brief Try to convert a type to another according to C++0x 5.16p3.
3511///
3512/// This is part of the parameter validation for the ? operator. If either
3513/// value operand is a class type, the two operands are attempted to be
3514/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003515/// It returns true if the program is ill-formed and has already been diagnosed
3516/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003517static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3518 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00003519 bool &HaveConversion,
3520 QualType &ToType) {
3521 HaveConversion = false;
3522 ToType = To->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003523
3524 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003525 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003526 // C++0x 5.16p3
3527 // The process for determining whether an operand expression E1 of type T1
3528 // can be converted to match an operand expression E2 of type T2 is defined
3529 // as follows:
3530 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00003531 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003532 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003533 // E1 can be converted to match E2 if E1 can be implicitly converted to
3534 // type "lvalue reference to T2", subject to the constraint that in the
3535 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003536 QualType T = Self.Context.getLValueReferenceType(ToType);
3537 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003538
Douglas Gregorb70cf442010-03-26 20:14:36 +00003539 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3540 if (InitSeq.isDirectReferenceBinding()) {
3541 ToType = T;
3542 HaveConversion = true;
3543 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003544 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003545
Douglas Gregorb70cf442010-03-26 20:14:36 +00003546 if (InitSeq.isAmbiguous())
3547 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003548 }
John McCallb1bdc622010-02-25 01:37:24 +00003549
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003550 // -- If E2 is an rvalue, or if the conversion above cannot be done:
3551 // -- if E1 and E2 have class type, and the underlying class types are
3552 // the same or one is a base class of the other:
3553 QualType FTy = From->getType();
3554 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003555 const RecordType *FRec = FTy->getAs<RecordType>();
3556 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003557 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003558 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003559 if (FRec && TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003560 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003561 // E1 can be converted to match E2 if the class of T2 is the
3562 // same type as, or a base class of, the class of T1, and
3563 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00003564 if (FRec == TRec || FDerivedFromT) {
3565 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003566 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3567 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003568 if (InitSeq) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003569 HaveConversion = true;
3570 return false;
3571 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003572
Douglas Gregorb70cf442010-03-26 20:14:36 +00003573 if (InitSeq.isAmbiguous())
3574 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003575 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003576 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003577
Douglas Gregorb70cf442010-03-26 20:14:36 +00003578 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003579 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003580
Douglas Gregorb70cf442010-03-26 20:14:36 +00003581 // -- Otherwise: E1 can be converted to match E2 if E1 can be
3582 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003583 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003584 // an rvalue).
3585 //
3586 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3587 // to the array-to-pointer or function-to-pointer conversions.
3588 if (!TTy->getAs<TagType>())
3589 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003590
Douglas Gregorb70cf442010-03-26 20:14:36 +00003591 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3592 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003593 HaveConversion = !InitSeq.Failed();
Douglas Gregorb70cf442010-03-26 20:14:36 +00003594 ToType = TTy;
3595 if (InitSeq.isAmbiguous())
3596 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3597
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003598 return false;
3599}
3600
3601/// \brief Try to find a common type for two according to C++0x 5.16p5.
3602///
3603/// This is part of the parameter validation for the ? operator. If either
3604/// value operand is a class type, overload resolution is used to find a
3605/// conversion to a common type.
John Wiegley429bb272011-04-08 18:41:53 +00003606static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth82214a82011-02-18 23:54:50 +00003607 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00003608 Expr *Args[2] = { LHS.get(), RHS.get() };
Chandler Carruth82214a82011-02-18 23:54:50 +00003609 OverloadCandidateSet CandidateSet(QuestionLoc);
3610 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3611 CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003612
3613 OverloadCandidateSet::iterator Best;
Chandler Carruth82214a82011-02-18 23:54:50 +00003614 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley429bb272011-04-08 18:41:53 +00003615 case OR_Success: {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003616 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley429bb272011-04-08 18:41:53 +00003617 ExprResult LHSRes =
3618 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3619 Best->Conversions[0], Sema::AA_Converting);
3620 if (LHSRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003621 break;
John Wiegley429bb272011-04-08 18:41:53 +00003622 LHS = move(LHSRes);
3623
3624 ExprResult RHSRes =
3625 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3626 Best->Conversions[1], Sema::AA_Converting);
3627 if (RHSRes.isInvalid())
3628 break;
3629 RHS = move(RHSRes);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003630 if (Best->Function)
Eli Friedman5f2987c2012-02-02 03:46:19 +00003631 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003632 return false;
John Wiegley429bb272011-04-08 18:41:53 +00003633 }
3634
Douglas Gregor20093b42009-12-09 23:02:17 +00003635 case OR_No_Viable_Function:
Chandler Carruth82214a82011-02-18 23:54:50 +00003636
3637 // Emit a better diagnostic if one of the expressions is a null pointer
3638 // constant and the other is a pointer type. In this case, the user most
3639 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00003640 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00003641 return true;
3642
3643 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003644 << LHS.get()->getType() << RHS.get()->getType()
3645 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003646 return true;
3647
Douglas Gregor20093b42009-12-09 23:02:17 +00003648 case OR_Ambiguous:
Chandler Carruth82214a82011-02-18 23:54:50 +00003649 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley429bb272011-04-08 18:41:53 +00003650 << LHS.get()->getType() << RHS.get()->getType()
3651 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00003652 // FIXME: Print the possible common types by printing the return types of
3653 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003654 break;
3655
Douglas Gregor20093b42009-12-09 23:02:17 +00003656 case OR_Deleted:
David Blaikieb219cfc2011-09-23 05:06:16 +00003657 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003658 }
3659 return true;
3660}
3661
Sebastian Redl76458502009-04-17 16:30:52 +00003662/// \brief Perform an "extended" implicit conversion as returned by
3663/// TryClassUnification.
John Wiegley429bb272011-04-08 18:41:53 +00003664static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003665 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley429bb272011-04-08 18:41:53 +00003666 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003667 SourceLocation());
John Wiegley429bb272011-04-08 18:41:53 +00003668 Expr *Arg = E.take();
3669 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
3670 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00003671 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00003672 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003673
John Wiegley429bb272011-04-08 18:41:53 +00003674 E = Result;
Sebastian Redl76458502009-04-17 16:30:52 +00003675 return false;
3676}
3677
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003678/// \brief Check the operands of ?: under C++ semantics.
3679///
3680/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
3681/// extension. In this case, LHS == Cond. (But they're not aliases.)
John Wiegley429bb272011-04-08 18:41:53 +00003682QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCall56ca35d2011-02-17 10:25:35 +00003683 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003684 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00003685 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
3686 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003687
3688 // C++0x 5.16p1
3689 // The first expression is contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00003690 if (!Cond.get()->isTypeDependent()) {
3691 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
3692 if (CondRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003693 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003694 Cond = move(CondRes);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003695 }
3696
John McCallf89e55a2010-11-18 06:31:45 +00003697 // Assume r-value.
3698 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00003699 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00003700
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003701 // Either of the arguments dependent?
John Wiegley429bb272011-04-08 18:41:53 +00003702 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003703 return Context.DependentTy;
3704
3705 // C++0x 5.16p2
3706 // If either the second or the third operand has type (cv) void, ...
John Wiegley429bb272011-04-08 18:41:53 +00003707 QualType LTy = LHS.get()->getType();
3708 QualType RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003709 bool LVoid = LTy->isVoidType();
3710 bool RVoid = RTy->isVoidType();
3711 if (LVoid || RVoid) {
3712 // ... then the [l2r] conversions are performed on the second and third
3713 // operands ...
John Wiegley429bb272011-04-08 18:41:53 +00003714 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3715 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3716 if (LHS.isInvalid() || RHS.isInvalid())
3717 return QualType();
3718 LTy = LHS.get()->getType();
3719 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003720
3721 // ... and one of the following shall hold:
3722 // -- The second or the third operand (but not both) is a throw-
3723 // expression; the result is of the type of the other and is an rvalue.
John Wiegley429bb272011-04-08 18:41:53 +00003724 bool LThrow = isa<CXXThrowExpr>(LHS.get());
3725 bool RThrow = isa<CXXThrowExpr>(RHS.get());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003726 if (LThrow && !RThrow)
3727 return RTy;
3728 if (RThrow && !LThrow)
3729 return LTy;
3730
3731 // -- Both the second and third operands have type void; the result is of
3732 // type void and is an rvalue.
3733 if (LVoid && RVoid)
3734 return Context.VoidTy;
3735
3736 // Neither holds, error.
3737 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3738 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley429bb272011-04-08 18:41:53 +00003739 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003740 return QualType();
3741 }
3742
3743 // Neither is void.
3744
3745 // C++0x 5.16p3
3746 // Otherwise, if the second and third operand have different types, and
3747 // either has (cv) class type, and attempt is made to convert each of those
3748 // operands to the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003749 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003750 (LTy->isRecordType() || RTy->isRecordType())) {
3751 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3752 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003753 QualType L2RType, R2LType;
3754 bool HaveL2R, HaveR2L;
John Wiegley429bb272011-04-08 18:41:53 +00003755 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003756 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003757 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003758 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003759
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003760 // If both can be converted, [...] the program is ill-formed.
3761 if (HaveL2R && HaveR2L) {
3762 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley429bb272011-04-08 18:41:53 +00003763 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003764 return QualType();
3765 }
3766
3767 // If exactly one conversion is possible, that conversion is applied to
3768 // the chosen operand and the converted operands are used in place of the
3769 // original operands for the remainder of this section.
3770 if (HaveL2R) {
John Wiegley429bb272011-04-08 18:41:53 +00003771 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003772 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003773 LTy = LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003774 } else if (HaveR2L) {
John Wiegley429bb272011-04-08 18:41:53 +00003775 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003776 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003777 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003778 }
3779 }
3780
3781 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00003782 // If the second and third operands are glvalues of the same value
3783 // category and have the same type, the result is of that type and
3784 // value category and it is a bit-field if the second or the third
3785 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00003786 // We only extend this to bitfields, not to the crazy other kinds of
3787 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003788 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00003789 if (Same &&
John Wiegley429bb272011-04-08 18:41:53 +00003790 LHS.get()->isGLValue() &&
3791 LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
3792 LHS.get()->isOrdinaryOrBitFieldObject() &&
3793 RHS.get()->isOrdinaryOrBitFieldObject()) {
3794 VK = LHS.get()->getValueKind();
3795 if (LHS.get()->getObjectKind() == OK_BitField ||
3796 RHS.get()->getObjectKind() == OK_BitField)
John McCall09431682010-11-18 19:01:18 +00003797 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00003798 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00003799 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003800
3801 // C++0x 5.16p5
3802 // Otherwise, the result is an rvalue. If the second and third operands
3803 // do not have the same type, and either has (cv) class type, ...
3804 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3805 // ... overload resolution is used to determine the conversions (if any)
3806 // to be applied to the operands. If the overload resolution fails, the
3807 // program is ill-formed.
3808 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3809 return QualType();
3810 }
3811
3812 // C++0x 5.16p6
3813 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3814 // conversions are performed on the second and third operands.
John Wiegley429bb272011-04-08 18:41:53 +00003815 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3816 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3817 if (LHS.isInvalid() || RHS.isInvalid())
3818 return QualType();
3819 LTy = LHS.get()->getType();
3820 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003821
3822 // After those conversions, one of the following shall hold:
3823 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00003824 // is of that type. If the operands have class type, the result
3825 // is a prvalue temporary of the result type, which is
3826 // copy-initialized from either the second operand or the third
3827 // operand depending on the value of the first operand.
3828 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3829 if (LTy->isRecordType()) {
3830 // The operands have class type. Make a temporary copy.
3831 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003832 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3833 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00003834 LHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00003835 if (LHSCopy.isInvalid())
3836 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003837
3838 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3839 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00003840 RHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00003841 if (RHSCopy.isInvalid())
3842 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003843
John Wiegley429bb272011-04-08 18:41:53 +00003844 LHS = LHSCopy;
3845 RHS = RHSCopy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003846 }
3847
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003848 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003849 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003850
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003851 // Extension: conditional operator involving vector types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003852 if (LTy->isVectorType() || RTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00003853 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003854
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003855 // -- The second and third operands have arithmetic or enumeration type;
3856 // the usual arithmetic conversions are performed to bring them to a
3857 // common type, and the result is of that type.
3858 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3859 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00003860 if (LHS.isInvalid() || RHS.isInvalid())
3861 return QualType();
3862 return LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003863 }
3864
3865 // -- The second and third operands have pointer type, or one has pointer
3866 // type and the other is a null pointer constant; pointer conversions
3867 // and qualification conversions are performed to bring them to their
3868 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00003869 // -- The second and third operands have pointer to member type, or one has
3870 // pointer to member type and the other is a null pointer constant;
3871 // pointer to member conversions and qualification conversions are
3872 // performed to bring them to a common type, whose cv-qualification
3873 // shall match the cv-qualification of either the second or the third
3874 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003875 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003876 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003877 isSFINAEContext()? 0 : &NonStandardCompositeType);
3878 if (!Composite.isNull()) {
3879 if (NonStandardCompositeType)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003880 Diag(QuestionLoc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003881 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3882 << LTy << RTy << Composite
John Wiegley429bb272011-04-08 18:41:53 +00003883 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003884
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003885 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003886 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003887
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003888 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00003889 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3890 if (!Composite.isNull())
3891 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003892
Chandler Carruth7ef93242011-02-19 00:13:59 +00003893 // Check if we are using a null with a non-pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00003894 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth7ef93242011-02-19 00:13:59 +00003895 return QualType();
3896
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003897 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003898 << LHS.get()->getType() << RHS.get()->getType()
3899 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003900 return QualType();
3901}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003902
3903/// \brief Find a merged pointer type and convert the two expressions to it.
3904///
Douglas Gregor20b3e992009-08-24 17:42:35 +00003905/// This finds the composite pointer type (or member pointer type) for @p E1
3906/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3907/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003908/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003909///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003910/// \param Loc The location of the operator requiring these two expressions to
3911/// be converted to the composite pointer type.
3912///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003913/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3914/// a non-standard (but still sane) composite type to which both expressions
3915/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3916/// will be set true.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003917QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003918 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003919 bool *NonStandardCompositeType) {
3920 if (NonStandardCompositeType)
3921 *NonStandardCompositeType = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003922
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003923 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3924 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003925
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00003926 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3927 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00003928 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003929
3930 // C++0x 5.9p2
3931 // Pointer conversions and qualification conversions are performed on
3932 // pointer operands to bring them to their composite pointer type. If
3933 // one operand is a null pointer constant, the composite pointer type is
3934 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00003935 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003936 if (T2->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00003937 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003938 else
John Wiegley429bb272011-04-08 18:41:53 +00003939 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003940 return T2;
3941 }
Douglas Gregorce940492009-09-25 04:25:58 +00003942 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003943 if (T1->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00003944 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003945 else
John Wiegley429bb272011-04-08 18:41:53 +00003946 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003947 return T1;
3948 }
Mike Stump1eb44332009-09-09 15:08:12 +00003949
Douglas Gregor20b3e992009-08-24 17:42:35 +00003950 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00003951 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3952 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003953 return QualType();
3954
3955 // Otherwise, of one of the operands has type "pointer to cv1 void," then
3956 // the other has type "pointer to cv2 T" and the composite pointer type is
3957 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3958 // Otherwise, the composite pointer type is a pointer type similar to the
3959 // type of one of the operands, with a cv-qualification signature that is
3960 // the union of the cv-qualification signatures of the operand types.
3961 // In practice, the first part here is redundant; it's subsumed by the second.
3962 // What we do here is, we build the two possible composite types, and try the
3963 // conversions in both directions. If only one works, or if the two composite
3964 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00003965 // FIXME: extended qualifiers?
Chris Lattner5f9e2722011-07-23 10:55:15 +00003966 typedef SmallVector<unsigned, 4> QualifierVector;
Sebastian Redla439e6f2009-11-16 21:03:45 +00003967 QualifierVector QualifierUnion;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003968 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
Sebastian Redla439e6f2009-11-16 21:03:45 +00003969 ContainingClassVector;
3970 ContainingClassVector MemberOfClass;
3971 QualType Composite1 = Context.getCanonicalType(T1),
3972 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003973 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00003974 do {
3975 const PointerType *Ptr1, *Ptr2;
3976 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3977 (Ptr2 = Composite2->getAs<PointerType>())) {
3978 Composite1 = Ptr1->getPointeeType();
3979 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003980
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003981 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003982 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003983 if (NonStandardCompositeType &&
3984 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3985 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003986
Douglas Gregor20b3e992009-08-24 17:42:35 +00003987 QualifierUnion.push_back(
3988 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3989 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3990 continue;
3991 }
Mike Stump1eb44332009-09-09 15:08:12 +00003992
Douglas Gregor20b3e992009-08-24 17:42:35 +00003993 const MemberPointerType *MemPtr1, *MemPtr2;
3994 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3995 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3996 Composite1 = MemPtr1->getPointeeType();
3997 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003998
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003999 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004000 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004001 if (NonStandardCompositeType &&
4002 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4003 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004004
Douglas Gregor20b3e992009-08-24 17:42:35 +00004005 QualifierUnion.push_back(
4006 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4007 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
4008 MemPtr2->getClass()));
4009 continue;
4010 }
Mike Stump1eb44332009-09-09 15:08:12 +00004011
Douglas Gregor20b3e992009-08-24 17:42:35 +00004012 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00004013
Douglas Gregor20b3e992009-08-24 17:42:35 +00004014 // Cannot unwrap any more types.
4015 break;
4016 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00004017
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004018 if (NeedConstBefore && NonStandardCompositeType) {
4019 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004020 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004021 // requirements of C++ [conv.qual]p4 bullet 3.
4022 for (unsigned I = 0; I != NeedConstBefore; ++I) {
4023 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
4024 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
4025 *NonStandardCompositeType = true;
4026 }
4027 }
4028 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004029
Douglas Gregor20b3e992009-08-24 17:42:35 +00004030 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00004031 ContainingClassVector::reverse_iterator MOC
4032 = MemberOfClass.rbegin();
4033 for (QualifierVector::reverse_iterator
4034 I = QualifierUnion.rbegin(),
4035 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00004036 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00004037 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004038 if (MOC->first && MOC->second) {
4039 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00004040 Composite1 = Context.getMemberPointerType(
4041 Context.getQualifiedType(Composite1, Quals),
4042 MOC->first);
4043 Composite2 = Context.getMemberPointerType(
4044 Context.getQualifiedType(Composite2, Quals),
4045 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004046 } else {
4047 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00004048 Composite1
4049 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
4050 Composite2
4051 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00004052 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004053 }
4054
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004055 // Try to convert to the first composite pointer type.
4056 InitializedEntity Entity1
4057 = InitializedEntity::InitializeTemporary(Composite1);
4058 InitializationKind Kind
4059 = InitializationKind::CreateCopy(Loc, SourceLocation());
4060 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
4061 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00004062
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004063 if (E1ToC1 && E2ToC1) {
4064 // Conversion to Composite1 is viable.
4065 if (!Context.hasSameType(Composite1, Composite2)) {
4066 // Composite2 is a different type from Composite1. Check whether
4067 // Composite2 is also viable.
4068 InitializedEntity Entity2
4069 = InitializedEntity::InitializeTemporary(Composite2);
4070 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4071 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4072 if (E1ToC2 && E2ToC2) {
4073 // Both Composite1 and Composite2 are viable and are different;
4074 // this is an ambiguity.
4075 return QualType();
4076 }
4077 }
4078
4079 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004080 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004081 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004082 if (E1Result.isInvalid())
4083 return QualType();
4084 E1 = E1Result.takeAs<Expr>();
4085
4086 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004087 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004088 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004089 if (E2Result.isInvalid())
4090 return QualType();
4091 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004092
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004093 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004094 }
4095
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004096 // Check whether Composite2 is viable.
4097 InitializedEntity Entity2
4098 = InitializedEntity::InitializeTemporary(Composite2);
4099 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4100 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4101 if (!E1ToC2 || !E2ToC2)
4102 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004103
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004104 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004105 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004106 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004107 if (E1Result.isInvalid())
4108 return QualType();
4109 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004110
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004111 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004112 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004113 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004114 if (E2Result.isInvalid())
4115 return QualType();
4116 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004117
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004118 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004119}
Anders Carlsson165a0a02009-05-17 18:41:29 +00004120
John McCall60d7b3a2010-08-24 06:29:42 +00004121ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00004122 if (!E)
4123 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004124
John McCallf85e1932011-06-15 23:02:42 +00004125 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4126
4127 // If the result is a glvalue, we shouldn't bind it.
4128 if (!E->isRValue())
Anders Carlsson089c2602009-08-15 23:41:35 +00004129 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004130
John McCallf85e1932011-06-15 23:02:42 +00004131 // In ARC, calls that return a retainable type can return retained,
4132 // in which case we have to insert a consuming cast.
4133 if (getLangOptions().ObjCAutoRefCount &&
4134 E->getType()->isObjCRetainableType()) {
4135
4136 bool ReturnsRetained;
4137
4138 // For actual calls, we compute this by examining the type of the
4139 // called value.
4140 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4141 Expr *Callee = Call->getCallee()->IgnoreParens();
4142 QualType T = Callee->getType();
4143
4144 if (T == Context.BoundMemberTy) {
4145 // Handle pointer-to-members.
4146 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4147 T = BinOp->getRHS()->getType();
4148 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4149 T = Mem->getMemberDecl()->getType();
4150 }
4151
4152 if (const PointerType *Ptr = T->getAs<PointerType>())
4153 T = Ptr->getPointeeType();
4154 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4155 T = Ptr->getPointeeType();
4156 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4157 T = MemPtr->getPointeeType();
4158
4159 const FunctionType *FTy = T->getAs<FunctionType>();
4160 assert(FTy && "call to value not of function type?");
4161 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4162
4163 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4164 // type always produce a +1 object.
4165 } else if (isa<StmtExpr>(E)) {
4166 ReturnsRetained = true;
4167
4168 // For message sends and property references, we try to find an
4169 // actual method. FIXME: we should infer retention by selector in
4170 // cases where we don't have an actual method.
4171 } else {
John McCallfc4b1912011-08-03 07:02:44 +00004172 ObjCMethodDecl *D = 0;
John McCallf85e1932011-06-15 23:02:42 +00004173 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4174 D = Send->getMethodDecl();
John McCallf85e1932011-06-15 23:02:42 +00004175 }
4176
4177 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCallfc4b1912011-08-03 07:02:44 +00004178
4179 // Don't do reclaims on performSelector calls; despite their
4180 // return type, the invoked method doesn't necessarily actually
4181 // return an object.
4182 if (!ReturnsRetained &&
4183 D && D->getMethodFamily() == OMF_performSelector)
4184 return Owned(E);
John McCallf85e1932011-06-15 23:02:42 +00004185 }
4186
John McCall567c5862011-11-14 19:53:16 +00004187 // Don't reclaim an object of Class type.
4188 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4189 return Owned(E);
4190
John McCall7e5e5f42011-07-07 06:58:02 +00004191 ExprNeedsCleanups = true;
4192
John McCall33e56f32011-09-10 06:18:15 +00004193 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4194 : CK_ARCReclaimReturnedObject);
John McCall7e5e5f42011-07-07 06:58:02 +00004195 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4196 VK_RValue));
John McCallf85e1932011-06-15 23:02:42 +00004197 }
4198
4199 if (!getLangOptions().CPlusPlus)
4200 return Owned(E);
Douglas Gregor51326552009-12-24 18:51:59 +00004201
Peter Collingbourneb4ab8432012-01-26 03:33:51 +00004202 // Search for the base element type (cf. ASTContext::getBaseElementType) with
4203 // a fast path for the common case that the type is directly a RecordType.
4204 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
4205 const RecordType *RT = 0;
4206 while (!RT) {
4207 switch (T->getTypeClass()) {
4208 case Type::Record:
4209 RT = cast<RecordType>(T);
4210 break;
4211 case Type::ConstantArray:
4212 case Type::IncompleteArray:
4213 case Type::VariableArray:
4214 case Type::DependentSizedArray:
4215 T = cast<ArrayType>(T)->getElementType().getTypePtr();
4216 break;
4217 default:
4218 return Owned(E);
4219 }
4220 }
Mike Stump1eb44332009-09-09 15:08:12 +00004221
John McCall86ff3082010-02-04 22:26:26 +00004222 // That should be enough to guarantee that this type is complete.
4223 // If it has a trivial destructor, we can avoid the extra copy.
Jeffrey Yasskinb7ee2e52011-01-27 19:17:54 +00004224 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall507384f2010-08-12 02:40:37 +00004225 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00004226 return Owned(E);
4227
John McCallf85e1932011-06-15 23:02:42 +00004228 CXXDestructorDecl *Destructor = LookupDestructor(RD);
4229
4230 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
4231 if (Destructor) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00004232 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00004233 CheckDestructorAccess(E->getExprLoc(), Destructor,
4234 PDiag(diag::err_access_dtor_temp)
4235 << E->getType());
John McCallf85e1932011-06-15 23:02:42 +00004236
John McCall80ee6e82011-11-10 05:35:25 +00004237 // We need a cleanup, but we don't need to remember the temporary.
John McCallf85e1932011-06-15 23:02:42 +00004238 ExprNeedsCleanups = true;
John McCallc91cc662010-04-07 00:41:46 +00004239 }
Anders Carlssondef11992009-05-30 20:36:53 +00004240 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
4241}
4242
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004243ExprResult
John McCall4765fa02010-12-06 08:20:24 +00004244Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004245 if (SubExpr.isInvalid())
4246 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004247
John McCall4765fa02010-12-06 08:20:24 +00004248 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00004249}
4250
John McCall80ee6e82011-11-10 05:35:25 +00004251Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
4252 assert(SubExpr && "sub expression can't be null!");
4253
Eli Friedmand2cce132012-02-02 23:15:15 +00004254 CleanupVarDeclMarking();
4255
John McCall80ee6e82011-11-10 05:35:25 +00004256 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
4257 assert(ExprCleanupObjects.size() >= FirstCleanup);
4258 assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
4259 if (!ExprNeedsCleanups)
4260 return SubExpr;
4261
4262 ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
4263 = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
4264 ExprCleanupObjects.size() - FirstCleanup);
4265
4266 Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
4267 DiscardCleanupsInEvaluationContext();
4268
4269 return E;
4270}
4271
John McCall4765fa02010-12-06 08:20:24 +00004272Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004273 assert(SubStmt && "sub statement can't be null!");
4274
Eli Friedmand2cce132012-02-02 23:15:15 +00004275 CleanupVarDeclMarking();
4276
John McCallf85e1932011-06-15 23:02:42 +00004277 if (!ExprNeedsCleanups)
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004278 return SubStmt;
4279
4280 // FIXME: In order to attach the temporaries, wrap the statement into
4281 // a StmtExpr; currently this is only used for asm statements.
4282 // This is hacky, either create a new CXXStmtWithTemporaries statement or
4283 // a new AsmStmtWithTemporaries.
4284 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
4285 SourceLocation(),
4286 SourceLocation());
4287 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
4288 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00004289 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004290}
4291
John McCall60d7b3a2010-08-24 06:29:42 +00004292ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004293Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00004294 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00004295 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004296 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004297 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004298 if (Result.isInvalid()) return ExprError();
4299 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004300
John McCall3c3b7f92011-10-25 17:37:35 +00004301 Result = CheckPlaceholderExpr(Base);
4302 if (Result.isInvalid()) return ExprError();
4303 Base = Result.take();
4304
John McCall9ae2f072010-08-23 23:25:46 +00004305 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004306 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004307 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00004308 // If we have a pointer to a dependent type and are using the -> operator,
4309 // the object type is the type that the pointer points to. We might still
4310 // have enough information about that type to do something useful.
4311 if (OpKind == tok::arrow)
4312 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4313 BaseType = Ptr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004314
John McCallb3d87482010-08-24 05:47:05 +00004315 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00004316 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004317 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004318 }
Mike Stump1eb44332009-09-09 15:08:12 +00004319
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004320 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00004321 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004322 // returned, with the original second operand.
4323 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00004324 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00004325 llvm::SmallPtrSet<CanQualType,8> CTypes;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004326 SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00004327 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004328
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004329 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00004330 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
4331 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004332 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00004333 Base = Result.get();
4334 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00004335 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00004336 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00004337 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00004338 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004339 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00004340 for (unsigned i = 0; i < Locations.size(); i++)
4341 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004342 return ExprError();
4343 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004344 }
Mike Stump1eb44332009-09-09 15:08:12 +00004345
Douglas Gregor1d7049a2012-01-12 16:11:24 +00004346 if (BaseType->isPointerType() || BaseType->isObjCObjectPointerType())
Douglas Gregor31658df2009-11-20 19:58:21 +00004347 BaseType = BaseType->getPointeeType();
4348 }
Mike Stump1eb44332009-09-09 15:08:12 +00004349
Douglas Gregor1d7049a2012-01-12 16:11:24 +00004350 // Objective-C properties allow "." access on Objective-C pointer types,
4351 // so adjust the base type to the object type itself.
4352 if (BaseType->isObjCObjectPointerType())
4353 BaseType = BaseType->getPointeeType();
4354
4355 // C++ [basic.lookup.classref]p2:
4356 // [...] If the type of the object expression is of pointer to scalar
4357 // type, the unqualified-id is looked up in the context of the complete
4358 // postfix-expression.
4359 //
4360 // This also indicates that we could be parsing a pseudo-destructor-name.
4361 // Note that Objective-C class and object types can be pseudo-destructor
4362 // expressions or normal member (ivar or property) access expressions.
4363 if (BaseType->isObjCObjectOrInterfaceType()) {
4364 MayBePseudoDestructor = true;
4365 } else if (!BaseType->isRecordType()) {
John McCallb3d87482010-08-24 05:47:05 +00004366 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004367 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004368 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00004369 }
Mike Stump1eb44332009-09-09 15:08:12 +00004370
Douglas Gregor03c57052009-11-17 05:17:33 +00004371 // The object type must be complete (or dependent).
4372 if (!BaseType->isDependentType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004373 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor03c57052009-11-17 05:17:33 +00004374 PDiag(diag::err_incomplete_member_access)))
4375 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004376
Douglas Gregorc68afe22009-09-03 21:38:09 +00004377 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004378 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00004379 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00004380 // type C (or of pointer to a class type C), the unqualified-id is looked
4381 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00004382 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00004383 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004384}
4385
John McCall60d7b3a2010-08-24 06:29:42 +00004386ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00004387 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00004388 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00004389 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
4390 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00004391 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004392
Douglas Gregor77549082010-02-24 21:29:12 +00004393 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00004394 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00004395 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00004396 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00004397 /*RPLoc*/ ExpectedLParenLoc);
4398}
Douglas Gregord4dca082010-02-24 18:44:31 +00004399
Eli Friedmane0dbedf2012-01-25 04:29:24 +00004400static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie91ec7892011-12-16 16:03:09 +00004401 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedmane0dbedf2012-01-25 04:29:24 +00004402 if (Base->hasPlaceholderType()) {
4403 ExprResult result = S.CheckPlaceholderExpr(Base);
4404 if (result.isInvalid()) return true;
4405 Base = result.take();
4406 }
4407 ObjectType = Base->getType();
4408
David Blaikie91ec7892011-12-16 16:03:09 +00004409 // C++ [expr.pseudo]p2:
4410 // The left-hand side of the dot operator shall be of scalar type. The
4411 // left-hand side of the arrow operator shall be of pointer to scalar type.
4412 // This scalar type is the object type.
Eli Friedmane0dbedf2012-01-25 04:29:24 +00004413 // Note that this is rather different from the normal handling for the
4414 // arrow operator.
David Blaikie91ec7892011-12-16 16:03:09 +00004415 if (OpKind == tok::arrow) {
4416 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4417 ObjectType = Ptr->getPointeeType();
4418 } else if (!Base->isTypeDependent()) {
4419 // The user wrote "p->" when she probably meant "p."; fix it.
4420 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4421 << ObjectType << true
4422 << FixItHint::CreateReplacement(OpLoc, ".");
4423 if (S.isSFINAEContext())
4424 return true;
4425
4426 OpKind = tok::period;
4427 }
4428 }
4429
4430 return false;
4431}
4432
John McCall60d7b3a2010-08-24 06:29:42 +00004433ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004434 SourceLocation OpLoc,
4435 tok::TokenKind OpKind,
4436 const CXXScopeSpec &SS,
4437 TypeSourceInfo *ScopeTypeInfo,
4438 SourceLocation CCLoc,
4439 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004440 PseudoDestructorTypeStorage Destructed,
John McCall2d9f5fa2011-02-25 05:21:17 +00004441 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004442 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004443
Eli Friedman8c9fe202012-01-25 04:35:06 +00004444 QualType ObjectType;
David Blaikie91ec7892011-12-16 16:03:09 +00004445 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4446 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004447
Douglas Gregorb57fb492010-02-24 22:38:50 +00004448 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
Nico Weberdf1be862012-01-23 05:50:57 +00004449 if (getLangOptions().MicrosoftMode && ObjectType->isVoidType())
Nico Weber2d757ec2012-01-23 06:08:16 +00004450 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Nico Weberdf1be862012-01-23 05:50:57 +00004451 else
4452 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
4453 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00004454 return ExprError();
4455 }
4456
4457 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004458 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb57fb492010-02-24 22:38:50 +00004459 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004460 if (DestructedTypeInfo) {
4461 QualType DestructedType = DestructedTypeInfo->getType();
4462 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004463 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCallf85e1932011-06-15 23:02:42 +00004464 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
4465 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
4466 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
4467 << ObjectType << DestructedType << Base->getSourceRange()
4468 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004469
John McCallf85e1932011-06-15 23:02:42 +00004470 // Recover by setting the destructed type to the object type.
4471 DestructedType = ObjectType;
4472 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004473 DestructedTypeStart);
John McCallf85e1932011-06-15 23:02:42 +00004474 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4475 } else if (DestructedType.getObjCLifetime() !=
4476 ObjectType.getObjCLifetime()) {
4477
4478 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
4479 // Okay: just pretend that the user provided the correctly-qualified
4480 // type.
4481 } else {
4482 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
4483 << ObjectType << DestructedType << Base->getSourceRange()
4484 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4485 }
4486
4487 // Recover by setting the destructed type to the object type.
4488 DestructedType = ObjectType;
4489 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4490 DestructedTypeStart);
4491 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4492 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004493 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00004494 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004495
Douglas Gregorb57fb492010-02-24 22:38:50 +00004496 // C++ [expr.pseudo]p2:
4497 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4498 // form
4499 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004500 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb57fb492010-02-24 22:38:50 +00004501 //
4502 // shall designate the same scalar type.
4503 if (ScopeTypeInfo) {
4504 QualType ScopeType = ScopeTypeInfo->getType();
4505 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00004506 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004507
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004508 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00004509 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00004510 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004511 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004512
Douglas Gregorb57fb492010-02-24 22:38:50 +00004513 ScopeType = QualType();
4514 ScopeTypeInfo = 0;
4515 }
4516 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004517
John McCall9ae2f072010-08-23 23:25:46 +00004518 Expr *Result
4519 = new (Context) CXXPseudoDestructorExpr(Context, Base,
4520 OpKind == tok::arrow, OpLoc,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004521 SS.getWithLocInContext(Context),
John McCall9ae2f072010-08-23 23:25:46 +00004522 ScopeTypeInfo,
4523 CCLoc,
4524 TildeLoc,
4525 Destructed);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004526
Douglas Gregorb57fb492010-02-24 22:38:50 +00004527 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00004528 return Owned(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004529
John McCall9ae2f072010-08-23 23:25:46 +00004530 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00004531}
4532
John McCall60d7b3a2010-08-24 06:29:42 +00004533ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004534 SourceLocation OpLoc,
4535 tok::TokenKind OpKind,
4536 CXXScopeSpec &SS,
4537 UnqualifiedId &FirstTypeName,
4538 SourceLocation CCLoc,
4539 SourceLocation TildeLoc,
4540 UnqualifiedId &SecondTypeName,
4541 bool HasTrailingLParen) {
Douglas Gregor77549082010-02-24 21:29:12 +00004542 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4543 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4544 "Invalid first type name in pseudo-destructor");
4545 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4546 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4547 "Invalid second type name in pseudo-destructor");
4548
Eli Friedman8c9fe202012-01-25 04:35:06 +00004549 QualType ObjectType;
David Blaikie91ec7892011-12-16 16:03:09 +00004550 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4551 return ExprError();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004552
4553 // Compute the object type that we should use for name lookup purposes. Only
4554 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00004555 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004556 if (!SS.isSet()) {
John McCall2d9f5fa2011-02-25 05:21:17 +00004557 if (ObjectType->isRecordType())
4558 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallb3d87482010-08-24 05:47:05 +00004559 else if (ObjectType->isDependentType())
4560 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004561 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004562
4563 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb57fb492010-02-24 22:38:50 +00004564 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00004565 QualType DestructedType;
4566 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004567 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00004568 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004569 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00004570 SecondTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00004571 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004572 if (!T &&
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004573 ((SS.isSet() && !computeDeclContext(SS, false)) ||
4574 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004575 // The name of the type being destroyed is a dependent name, and we
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004576 // couldn't find anything useful in scope. Just store the identifier and
4577 // it's location, and we'll perform (qualified) name lookup again at
4578 // template instantiation time.
4579 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
4580 SecondTypeName.StartLocation);
4581 } else if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004582 Diag(SecondTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00004583 diag::err_pseudo_dtor_destructor_non_type)
4584 << SecondTypeName.Identifier << ObjectType;
4585 if (isSFINAEContext())
4586 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004587
Douglas Gregor77549082010-02-24 21:29:12 +00004588 // Recover by assuming we had the right type all along.
4589 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004590 } else
Douglas Gregor77549082010-02-24 21:29:12 +00004591 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004592 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004593 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00004594 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004595 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4596 TemplateId->getTemplateArgs(),
4597 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00004598 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara55d23c92012-02-06 14:41:24 +00004599 TemplateId->TemplateKWLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +00004600 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004601 TemplateId->TemplateNameLoc,
4602 TemplateId->LAngleLoc,
4603 TemplateArgsPtr,
4604 TemplateId->RAngleLoc);
4605 if (T.isInvalid() || !T.get()) {
4606 // Recover by assuming we had the right type all along.
4607 DestructedType = ObjectType;
4608 } else
4609 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004610 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004611
4612 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb57fb492010-02-24 22:38:50 +00004613 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004614 if (!DestructedType.isNull()) {
4615 if (!DestructedTypeInfo)
4616 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004617 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004618 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4619 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004620
Douglas Gregorb57fb492010-02-24 22:38:50 +00004621 // Convert the name of the scope type (the type prior to '::') into a type.
4622 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00004623 QualType ScopeType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004624 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor77549082010-02-24 21:29:12 +00004625 FirstTypeName.Identifier) {
4626 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004627 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00004628 FirstTypeName.StartLocation,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004629 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00004630 if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004631 Diag(FirstTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00004632 diag::err_pseudo_dtor_destructor_non_type)
4633 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004634
Douglas Gregorb57fb492010-02-24 22:38:50 +00004635 if (isSFINAEContext())
4636 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004637
Douglas Gregorb57fb492010-02-24 22:38:50 +00004638 // Just drop this type. It's unnecessary anyway.
4639 ScopeType = QualType();
4640 } else
4641 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004642 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004643 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00004644 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004645 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4646 TemplateId->getTemplateArgs(),
4647 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00004648 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara55d23c92012-02-06 14:41:24 +00004649 TemplateId->TemplateKWLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +00004650 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004651 TemplateId->TemplateNameLoc,
4652 TemplateId->LAngleLoc,
4653 TemplateArgsPtr,
4654 TemplateId->RAngleLoc);
4655 if (T.isInvalid() || !T.get()) {
4656 // Recover by dropping this type.
4657 ScopeType = QualType();
4658 } else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004659 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004660 }
4661 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004662
Douglas Gregorb4a418f2010-02-24 23:02:30 +00004663 if (!ScopeType.isNull() && !ScopeTypeInfo)
4664 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
4665 FirstTypeName.StartLocation);
4666
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004667
John McCall9ae2f072010-08-23 23:25:46 +00004668 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00004669 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004670 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00004671}
4672
David Blaikie91ec7892011-12-16 16:03:09 +00004673ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4674 SourceLocation OpLoc,
4675 tok::TokenKind OpKind,
4676 SourceLocation TildeLoc,
4677 const DeclSpec& DS,
4678 bool HasTrailingLParen) {
Eli Friedman8c9fe202012-01-25 04:35:06 +00004679 QualType ObjectType;
David Blaikie91ec7892011-12-16 16:03:09 +00004680 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4681 return ExprError();
4682
4683 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4684
4685 TypeLocBuilder TLB;
4686 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
4687 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
4688 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
4689 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
4690
4691 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
4692 0, SourceLocation(), TildeLoc,
4693 Destructed, HasTrailingLParen);
4694}
4695
John Wiegley429bb272011-04-08 18:41:53 +00004696ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004697 CXXMethodDecl *Method,
4698 bool HadMultipleCandidates) {
John Wiegley429bb272011-04-08 18:41:53 +00004699 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
4700 FoundDecl, Method);
4701 if (Exp.isInvalid())
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004702 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00004703
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004704 MemberExpr *ME =
John Wiegley429bb272011-04-08 18:41:53 +00004705 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
Abramo Bagnara960809e2011-11-16 22:46:05 +00004706 SourceLocation(), Context.BoundMemberTy,
John McCallf89e55a2010-11-18 06:31:45 +00004707 VK_RValue, OK_Ordinary);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004708 if (HadMultipleCandidates)
4709 ME->setHadMultipleCandidates(true);
4710
John McCallf89e55a2010-11-18 06:31:45 +00004711 QualType ResultType = Method->getResultType();
4712 ExprValueKind VK = Expr::getValueKindForType(ResultType);
4713 ResultType = ResultType.getNonLValueExprType(Context);
4714
Eli Friedman5f2987c2012-02-02 03:46:19 +00004715 MarkFunctionReferenced(Exp.get()->getLocStart(), Method);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004716 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00004717 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
John Wiegley429bb272011-04-08 18:41:53 +00004718 Exp.get()->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00004719 return CE;
4720}
4721
Sebastian Redl2e156222010-09-10 20:55:43 +00004722ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4723 SourceLocation RParen) {
Sebastian Redl2e156222010-09-10 20:55:43 +00004724 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
4725 Operand->CanThrow(Context),
4726 KeyLoc, RParen));
4727}
4728
4729ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
4730 Expr *Operand, SourceLocation RParen) {
4731 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00004732}
4733
John McCallf6a16482010-12-04 03:47:34 +00004734/// Perform the conversions required for an expression used in a
4735/// context that ignores the result.
John Wiegley429bb272011-04-08 18:41:53 +00004736ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall3c3b7f92011-10-25 17:37:35 +00004737 if (E->hasPlaceholderType()) {
4738 ExprResult result = CheckPlaceholderExpr(E);
4739 if (result.isInvalid()) return Owned(E);
4740 E = result.take();
4741 }
4742
John McCalla878cda2010-12-02 02:07:15 +00004743 // C99 6.3.2.1:
4744 // [Except in specific positions,] an lvalue that does not have
4745 // array type is converted to the value stored in the
4746 // designated object (and is no longer an lvalue).
John McCalle6d134b2011-06-27 21:24:11 +00004747 if (E->isRValue()) {
4748 // In C, function designators (i.e. expressions of function type)
4749 // are r-values, but we still want to do function-to-pointer decay
4750 // on them. This is both technically correct and convenient for
4751 // some clients.
4752 if (!getLangOptions().CPlusPlus && E->getType()->isFunctionType())
4753 return DefaultFunctionArrayConversion(E);
4754
4755 return Owned(E);
4756 }
John McCalla878cda2010-12-02 02:07:15 +00004757
John McCallf6a16482010-12-04 03:47:34 +00004758 // Otherwise, this rule does not apply in C++, at least not for the moment.
John Wiegley429bb272011-04-08 18:41:53 +00004759 if (getLangOptions().CPlusPlus) return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004760
4761 // GCC seems to also exclude expressions of incomplete enum type.
4762 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
4763 if (!T->getDecl()->isComplete()) {
4764 // FIXME: stupid workaround for a codegen bug!
John Wiegley429bb272011-04-08 18:41:53 +00004765 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
4766 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004767 }
4768 }
4769
John Wiegley429bb272011-04-08 18:41:53 +00004770 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
4771 if (Res.isInvalid())
4772 return Owned(E);
4773 E = Res.take();
4774
John McCall85515d62010-12-04 12:29:11 +00004775 if (!E->getType()->isVoidType())
4776 RequireCompleteType(E->getExprLoc(), E->getType(),
4777 diag::err_incomplete_type);
John Wiegley429bb272011-04-08 18:41:53 +00004778 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004779}
4780
John Wiegley429bb272011-04-08 18:41:53 +00004781ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
4782 ExprResult FullExpr = Owned(FE);
4783
4784 if (!FullExpr.get())
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00004785 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00004786
John Wiegley429bb272011-04-08 18:41:53 +00004787 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregord0937222010-12-13 22:49:22 +00004788 return ExprError();
4789
Douglas Gregor5e3a8be2011-12-15 00:53:32 +00004790 // Top-level message sends default to 'id' when we're in a debugger.
Sean Callanan50a9a122012-02-04 01:29:37 +00004791 if (getLangOptions().DebuggerCastResultToId &&
Douglas Gregor5e3a8be2011-12-15 00:53:32 +00004792 FullExpr.get()->getType() == Context.UnknownAnyTy &&
4793 isa<ObjCMessageExpr>(FullExpr.get())) {
4794 FullExpr = forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdType());
4795 if (FullExpr.isInvalid())
4796 return ExprError();
4797 }
4798
John McCallfb8721c2011-04-10 19:13:55 +00004799 FullExpr = CheckPlaceholderExpr(FullExpr.take());
4800 if (FullExpr.isInvalid())
4801 return ExprError();
Douglas Gregor353ee242011-03-07 02:05:23 +00004802
John Wiegley429bb272011-04-08 18:41:53 +00004803 FullExpr = IgnoredValueConversions(FullExpr.take());
4804 if (FullExpr.isInvalid())
4805 return ExprError();
4806
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004807 CheckImplicitConversions(FullExpr.get(), FullExpr.get()->getExprLoc());
John McCall4765fa02010-12-06 08:20:24 +00004808 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00004809}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004810
4811StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
4812 if (!FullStmt) return StmtError();
4813
John McCall4765fa02010-12-06 08:20:24 +00004814 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004815}
Francois Pichet1e862692011-05-06 20:48:22 +00004816
Douglas Gregorba0513d2011-10-25 01:33:02 +00004817Sema::IfExistsResult
4818Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
4819 CXXScopeSpec &SS,
4820 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet1e862692011-05-06 20:48:22 +00004821 DeclarationName TargetName = TargetNameInfo.getName();
4822 if (!TargetName)
Douglas Gregor3896fc52011-10-24 22:31:10 +00004823 return IER_DoesNotExist;
Douglas Gregorba0513d2011-10-25 01:33:02 +00004824
Douglas Gregor3896fc52011-10-24 22:31:10 +00004825 // If the name itself is dependent, then the result is dependent.
4826 if (TargetName.isDependentName())
4827 return IER_Dependent;
Douglas Gregorba0513d2011-10-25 01:33:02 +00004828
Francois Pichet1e862692011-05-06 20:48:22 +00004829 // Do the redeclaration lookup in the current scope.
4830 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
4831 Sema::NotForRedeclaration);
Douglas Gregor3896fc52011-10-24 22:31:10 +00004832 LookupParsedName(R, S, &SS);
Francois Pichet1e862692011-05-06 20:48:22 +00004833 R.suppressDiagnostics();
Douglas Gregor3896fc52011-10-24 22:31:10 +00004834
4835 switch (R.getResultKind()) {
4836 case LookupResult::Found:
4837 case LookupResult::FoundOverloaded:
4838 case LookupResult::FoundUnresolvedValue:
4839 case LookupResult::Ambiguous:
4840 return IER_Exists;
4841
4842 case LookupResult::NotFound:
4843 return IER_DoesNotExist;
4844
4845 case LookupResult::NotFoundInCurrentInstantiation:
4846 return IER_Dependent;
4847 }
David Blaikie7530c032012-01-17 06:56:22 +00004848
4849 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet1e862692011-05-06 20:48:22 +00004850}
Douglas Gregorba0513d2011-10-25 01:33:02 +00004851
Douglas Gregor65019ac2011-10-25 03:44:56 +00004852Sema::IfExistsResult
4853Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4854 bool IsIfExists, CXXScopeSpec &SS,
4855 UnqualifiedId &Name) {
Douglas Gregorba0513d2011-10-25 01:33:02 +00004856 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Douglas Gregor65019ac2011-10-25 03:44:56 +00004857
4858 // Check for unexpanded parameter packs.
4859 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
4860 collectUnexpandedParameterPacks(SS, Unexpanded);
4861 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
4862 if (!Unexpanded.empty()) {
4863 DiagnoseUnexpandedParameterPacks(KeywordLoc,
4864 IsIfExists? UPPC_IfExists
4865 : UPPC_IfNotExists,
4866 Unexpanded);
4867 return IER_Error;
4868 }
4869
Douglas Gregorba0513d2011-10-25 01:33:02 +00004870 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
4871}