blob: 4ffdb3e5c1543ac0fc857f6c747c4b0ee40ac5aa [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]);
Eli Friedman668165a2012-02-11 02:51:16 +0000710 Expr *ThisExpr = 0;
711 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
712 // For lambda expressions, build a field and an initializing expression.
713 QualType ThisTy = getCurrentThisType();
714 CXXRecordDecl *Lambda = LSI->Lambda;
715 FieldDecl *Field
716 = FieldDecl::Create(Context, Lambda, Loc, Loc, 0, ThisTy,
717 Context.getTrivialTypeSourceInfo(ThisTy, Loc),
718 0, false, false);
719 Field->setImplicit(true);
720 Field->setAccess(AS_private);
721 Lambda->addDecl(Field);
722 ThisExpr = new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/true);
723 }
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000724 bool isNested = NumClosures > 1;
Eli Friedman668165a2012-02-11 02:51:16 +0000725 CSI->AddThisCapture(isNested, Loc, ThisExpr);
Eli Friedman72899c32012-01-07 04:59:52 +0000726 }
727}
728
Richard Smith7a614d82011-06-11 17:19:42 +0000729ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCall5808ce42011-02-03 08:15:49 +0000730 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
731 /// is a non-lvalue expression whose value is the address of the object for
732 /// which the function is called.
733
Douglas Gregor341350e2011-10-18 16:47:30 +0000734 QualType ThisTy = getCurrentThisType();
Richard Smith7a614d82011-06-11 17:19:42 +0000735 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCall5808ce42011-02-03 08:15:49 +0000736
Eli Friedman72899c32012-01-07 04:59:52 +0000737 CheckCXXThisCapture(Loc);
Richard Smith7a614d82011-06-11 17:19:42 +0000738 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000739}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000740
John McCall60d7b3a2010-08-24 06:29:42 +0000741ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000742Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000743 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000744 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000745 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000746 if (!TypeRep)
747 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000748
John McCall9d125032010-01-15 18:39:57 +0000749 TypeSourceInfo *TInfo;
750 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
751 if (!TInfo)
752 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000753
754 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
755}
756
757/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
758/// Can be interpreted either as function-style casting ("int(x)")
759/// or class type construction ("ClassType(x,y,z)")
760/// or creation of a value-initialized type ("int()").
761ExprResult
762Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
763 SourceLocation LParenLoc,
764 MultiExprArg exprs,
765 SourceLocation RParenLoc) {
766 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000767 unsigned NumExprs = exprs.size();
768 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000769 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000770
Sebastian Redlf53597f2009-03-15 17:47:39 +0000771 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000772 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000773 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000774
Douglas Gregorab6677e2010-09-08 00:15:04 +0000775 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000776 LParenLoc,
777 Exprs, NumExprs,
778 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000779 }
780
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000781 bool ListInitialization = LParenLoc.isInvalid();
782 assert((!ListInitialization || (NumExprs == 1 && isa<InitListExpr>(Exprs[0])))
783 && "List initialization must have initializer list as expression.");
784 SourceRange FullRange = SourceRange(TyBeginLoc,
785 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
786
Anders Carlssonbb60a502009-08-27 03:53:50 +0000787 if (Ty->isArrayType())
788 return ExprError(Diag(TyBeginLoc,
789 diag::err_value_init_for_array_type) << FullRange);
790 if (!Ty->isVoidType() &&
791 RequireCompleteType(TyBeginLoc, Ty,
792 PDiag(diag::err_invalid_incomplete_type_use)
793 << FullRange))
794 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000795
Anders Carlssonbb60a502009-08-27 03:53:50 +0000796 if (RequireNonAbstractType(TyBeginLoc, Ty,
797 diag::err_allocation_of_abstract_type))
798 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000799
800
Douglas Gregor506ae412009-01-16 18:33:17 +0000801 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000802 // If the expression list is a single expression, the type conversion
803 // expression is equivalent (in definedness, and if defined in meaning) to the
804 // corresponding cast expression.
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000805 if (NumExprs == 1 && !ListInitialization) {
John McCallb45ae252011-10-05 07:41:44 +0000806 Expr *Arg = Exprs[0];
Anders Carlsson0aebc812009-09-09 21:33:21 +0000807 exprs.release();
John McCallb45ae252011-10-05 07:41:44 +0000808 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000809 }
810
Douglas Gregor19311e72010-09-08 21:40:08 +0000811 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
812 InitializationKind Kind
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000813 = NumExprs ? ListInitialization
814 ? InitializationKind::CreateDirectList(TyBeginLoc)
815 : InitializationKind::CreateDirect(TyBeginLoc,
816 LParenLoc, RParenLoc)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000817 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor19311e72010-09-08 21:40:08 +0000818 LParenLoc, RParenLoc);
819 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
820 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000821
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000822 if (!Result.isInvalid() && ListInitialization &&
823 isa<InitListExpr>(Result.get())) {
824 // If the list-initialization doesn't involve a constructor call, we'll get
825 // the initializer-list (with corrected type) back, but that's not what we
826 // want, since it will be treated as an initializer list in further
827 // processing. Explicitly insert a cast here.
828 InitListExpr *List = cast<InitListExpr>(Result.take());
829 Result = Owned(CXXFunctionalCastExpr::Create(Context, List->getType(),
830 Expr::getValueKindForType(TInfo->getType()),
831 TInfo, TyBeginLoc, CK_NoOp,
832 List, /*Path=*/0, RParenLoc));
833 }
834
Douglas Gregor19311e72010-09-08 21:40:08 +0000835 // FIXME: Improve AST representation?
836 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000837}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000838
John McCall6ec278d2011-01-27 09:37:56 +0000839/// doesUsualArrayDeleteWantSize - Answers whether the usual
840/// operator delete[] for the given type has a size_t parameter.
841static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
842 QualType allocType) {
843 const RecordType *record =
844 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
845 if (!record) return false;
846
847 // Try to find an operator delete[] in class scope.
848
849 DeclarationName deleteName =
850 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
851 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
852 S.LookupQualifiedName(ops, record->getDecl());
853
854 // We're just doing this for information.
855 ops.suppressDiagnostics();
856
857 // Very likely: there's no operator delete[].
858 if (ops.empty()) return false;
859
860 // If it's ambiguous, it should be illegal to call operator delete[]
861 // on this thing, so it doesn't matter if we allocate extra space or not.
862 if (ops.isAmbiguous()) return false;
863
864 LookupResult::Filter filter = ops.makeFilter();
865 while (filter.hasNext()) {
866 NamedDecl *del = filter.next()->getUnderlyingDecl();
867
868 // C++0x [basic.stc.dynamic.deallocation]p2:
869 // A template instance is never a usual deallocation function,
870 // regardless of its signature.
871 if (isa<FunctionTemplateDecl>(del)) {
872 filter.erase();
873 continue;
874 }
875
876 // C++0x [basic.stc.dynamic.deallocation]p2:
877 // If class T does not declare [an operator delete[] with one
878 // parameter] but does declare a member deallocation function
879 // named operator delete[] with exactly two parameters, the
880 // second of which has type std::size_t, then this function
881 // is a usual deallocation function.
882 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
883 filter.erase();
884 continue;
885 }
886 }
887 filter.done();
888
889 if (!ops.isSingleResult()) return false;
890
891 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
892 return (del->getNumParams() == 2);
893}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000894
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000895/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
896
897/// E.g.:
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000898/// @code new (memory) int[size][4] @endcode
899/// or
900/// @code ::new Foo(23, "hello") @endcode
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000901///
902/// \param StartLoc The first location of the expression.
903/// \param UseGlobal True if 'new' was prefixed with '::'.
904/// \param PlacementLParen Opening paren of the placement arguments.
905/// \param PlacementArgs Placement new arguments.
906/// \param PlacementRParen Closing paren of the placement arguments.
907/// \param TypeIdParens If the type is in parens, the source range.
908/// \param D The type to be allocated, as well as array dimensions.
909/// \param ConstructorLParen Opening paren of the constructor args, empty if
910/// initializer-list syntax is used.
911/// \param ConstructorArgs Constructor/initialization arguments.
912/// \param ConstructorRParen Closing paren of the constructor args.
John McCall60d7b3a2010-08-24 06:29:42 +0000913ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000914Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000915 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000916 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000917 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000918 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000919 SourceLocation ConstructorRParen) {
Richard Smith34b41d92011-02-20 03:19:35 +0000920 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
921
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000922 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000923 // If the specified type is an array, unwrap it and save the expression.
924 if (D.getNumTypeObjects() > 0 &&
925 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
926 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith34b41d92011-02-20 03:19:35 +0000927 if (TypeContainsAuto)
928 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
929 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000930 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000931 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
932 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000933 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000934 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
935 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000936
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000937 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000938 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000939 }
940
Douglas Gregor043cad22009-09-11 00:18:58 +0000941 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000942 if (ArraySize) {
943 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000944 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
945 break;
946
947 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
948 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smith282e7e62012-02-04 09:53:13 +0000949 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
950 Array.NumElts = VerifyIntegerConstantExpression(NumElts, 0,
951 PDiag(diag::err_new_array_nonconst)).take();
952 if (!Array.NumElts)
953 return ExprError();
Douglas Gregor043cad22009-09-11 00:18:58 +0000954 }
955 }
956 }
957 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000958
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +0000959 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
John McCallbf1a0282010-06-04 23:28:52 +0000960 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000961 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000962 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000963
Mike Stump1eb44332009-09-09 15:08:12 +0000964 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000965 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000966 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000967 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000968 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +0000969 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000970 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000971 ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000972 ConstructorLParen,
973 move(ConstructorArgs),
Richard Smith34b41d92011-02-20 03:19:35 +0000974 ConstructorRParen,
975 TypeContainsAuto);
Douglas Gregor3433cf72009-05-21 00:00:09 +0000976}
977
John McCall60d7b3a2010-08-24 06:29:42 +0000978ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000979Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
980 SourceLocation PlacementLParen,
981 MultiExprArg PlacementArgs,
982 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +0000983 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000984 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000985 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +0000986 Expr *ArraySize,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000987 SourceLocation ConstructorLParen,
988 MultiExprArg ConstructorArgs,
Richard Smith34b41d92011-02-20 03:19:35 +0000989 SourceLocation ConstructorRParen,
990 bool TypeMayContainAuto) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000991 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000992
Richard Smith34b41d92011-02-20 03:19:35 +0000993 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
994 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
995 if (ConstructorArgs.size() == 0)
996 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
997 << AllocType << TypeRange);
998 if (ConstructorArgs.size() != 1) {
999 Expr *FirstBad = ConstructorArgs.get()[1];
1000 return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
1001 diag::err_auto_new_ctor_multiple_expressions)
1002 << AllocType << TypeRange);
1003 }
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001004 Expr *Deduce = ConstructorArgs.get()[0];
1005 if (ConstructorLParen.isInvalid()) {
1006 return ExprError(Diag(Deduce->getSourceRange().getBegin(),
1007 diag::err_auto_new_requires_parens)
1008 << AllocType << TypeRange);
1009 }
Richard Smitha085da82011-03-17 16:11:59 +00001010 TypeSourceInfo *DeducedType = 0;
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001011 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) ==
Sebastian Redlb832f6d2012-01-23 22:09:39 +00001012 DAR_Failed)
Richard Smith34b41d92011-02-20 03:19:35 +00001013 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001014 << AllocType << Deduce->getType()
1015 << TypeRange << Deduce->getSourceRange());
Richard Smitha085da82011-03-17 16:11:59 +00001016 if (!DeducedType)
1017 return ExprError();
Richard Smith34b41d92011-02-20 03:19:35 +00001018
Richard Smitha085da82011-03-17 16:11:59 +00001019 AllocTypeInfo = DeducedType;
1020 AllocType = AllocTypeInfo->getType();
Richard Smith34b41d92011-02-20 03:19:35 +00001021 }
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001022
Douglas Gregor3caf04e2010-05-16 16:01:03 +00001023 // Per C++0x [expr.new]p5, the type being constructed may be a
1024 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +00001025 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +00001026 if (const ConstantArrayType *Array
1027 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001028 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1029 Context.getSizeType(),
1030 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +00001031 AllocType = Array->getElementType();
1032 }
1033 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001034
Douglas Gregora0750762010-10-06 16:00:31 +00001035 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1036 return ExprError();
1037
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001038 bool ListInitialization = ConstructorLParen.isInvalid() &&
1039 ConstructorArgs.size() > 0;
1040 assert((!ListInitialization || (ConstructorArgs.size() == 1 &&
1041 isa<InitListExpr>(ConstructorArgs.get()[0])))
1042 && "List initialization means a braced-init-list for arguments.");
1043 if (ListInitialization && isStdInitializerList(AllocType, 0)) {
1044 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1045 diag::warn_dangling_std_initializer_list)
1046 << /*at end of FE*/0 << ConstructorArgs.get()[0]->getSourceRange();
1047 }
1048
John McCallf85e1932011-06-15 23:02:42 +00001049 // In ARC, infer 'retaining' for the allocated
1050 if (getLangOptions().ObjCAutoRefCount &&
1051 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1052 AllocType->isObjCLifetimeType()) {
1053 AllocType = Context.getLifetimeQualifiedType(AllocType,
1054 AllocType->getObjCARCImplicitLifetime());
1055 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001056
John McCallf85e1932011-06-15 23:02:42 +00001057 QualType ResultType = Context.getPointerType(AllocType);
1058
Richard Smithf39aec12012-02-04 07:07:42 +00001059 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1060 // integral or enumeration type with a non-negative value."
1061 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1062 // enumeration type, or a class type for which a single non-explicit
1063 // conversion function to integral or unscoped enumeration type exists.
Sebastian Redl28507842009-02-26 14:39:58 +00001064 if (ArraySize && !ArraySize->isTypeDependent()) {
Eli Friedmanceccab92012-01-26 00:26:18 +00001065 ExprResult ConvertedSize = ConvertToIntegralOrEnumerationType(
Richard Smithebaf0e62011-10-18 20:49:44 +00001066 StartLoc, ArraySize,
Richard Smithf39aec12012-02-04 07:07:42 +00001067 PDiag(diag::err_array_size_not_integral) << getLangOptions().CPlusPlus0x,
Richard Smithebaf0e62011-10-18 20:49:44 +00001068 PDiag(diag::err_array_size_incomplete_type)
1069 << ArraySize->getSourceRange(),
1070 PDiag(diag::err_array_size_explicit_conversion),
1071 PDiag(diag::note_array_size_conversion),
1072 PDiag(diag::err_array_size_ambiguous_conversion),
1073 PDiag(diag::note_array_size_conversion),
1074 PDiag(getLangOptions().CPlusPlus0x ?
1075 diag::warn_cxx98_compat_array_size_conversion :
Richard Smithf39aec12012-02-04 07:07:42 +00001076 diag::ext_array_size_conversion),
1077 /*AllowScopedEnumerations*/ false);
Douglas Gregor6bc574d2010-06-30 00:20:43 +00001078 if (ConvertedSize.isInvalid())
1079 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001080
John McCall9ae2f072010-08-23 23:25:46 +00001081 ArraySize = ConvertedSize.take();
John McCall806054d2012-01-11 00:14:46 +00001082 QualType SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001083 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +00001084 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001085
Richard Smith0b458fd2012-02-04 05:35:53 +00001086 // C++98 [expr.new]p7:
1087 // The expression in a direct-new-declarator shall have integral type
1088 // with a non-negative value.
1089 //
1090 // Let's see if this is a constant < 0. If so, we reject it out of
1091 // hand. Otherwise, if it's not a constant, we must have an unparenthesized
1092 // array type.
1093 //
1094 // Note: such a construct has well-defined semantics in C++11: it throws
1095 // std::bad_array_new_length.
Sebastian Redl28507842009-02-26 14:39:58 +00001096 if (!ArraySize->isValueDependent()) {
1097 llvm::APSInt Value;
Richard Smith282e7e62012-02-04 09:53:13 +00001098 // We've already performed any required implicit conversion to integer or
1099 // unscoped enumeration type.
Richard Smith0b458fd2012-02-04 05:35:53 +00001100 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Sebastian Redl28507842009-02-26 14:39:58 +00001101 if (Value < llvm::APSInt(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001102 llvm::APInt::getNullValue(Value.getBitWidth()),
Richard Smith0b458fd2012-02-04 05:35:53 +00001103 Value.isUnsigned())) {
1104 if (getLangOptions().CPlusPlus0x)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001105 Diag(ArraySize->getSourceRange().getBegin(),
Richard Smith0b458fd2012-02-04 05:35:53 +00001106 diag::warn_typecheck_negative_array_new_size)
Douglas Gregor2767ce22010-08-18 00:39:00 +00001107 << ArraySize->getSourceRange();
Richard Smith0b458fd2012-02-04 05:35:53 +00001108 else
1109 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
1110 diag::err_typecheck_negative_array_size)
1111 << ArraySize->getSourceRange());
1112 } else if (!AllocType->isDependentType()) {
1113 unsigned ActiveSizeBits =
1114 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1115 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
1116 if (getLangOptions().CPlusPlus0x)
1117 Diag(ArraySize->getSourceRange().getBegin(),
1118 diag::warn_array_new_too_large)
1119 << Value.toString(10)
1120 << ArraySize->getSourceRange();
1121 else
1122 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
1123 diag::err_array_too_large)
1124 << Value.toString(10)
1125 << ArraySize->getSourceRange());
Douglas Gregor2767ce22010-08-18 00:39:00 +00001126 }
1127 }
Douglas Gregor4bd40312010-07-13 15:54:32 +00001128 } else if (TypeIdParens.isValid()) {
1129 // Can't have dynamic array size when the type-id is in parentheses.
1130 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1131 << ArraySize->getSourceRange()
1132 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1133 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001134
Douglas Gregor4bd40312010-07-13 15:54:32 +00001135 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +00001136 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001137 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001138
John McCallf85e1932011-06-15 23:02:42 +00001139 // ARC: warn about ABI issues.
1140 if (getLangOptions().ObjCAutoRefCount) {
1141 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1142 if (BaseAllocType.hasStrongOrWeakObjCLifetime())
1143 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1144 << 0 << BaseAllocType;
1145 }
1146
John McCall7d166272011-05-15 07:14:44 +00001147 // Note that we do *not* convert the argument in any way. It can
1148 // be signed, larger than size_t, whatever.
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001149 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001150
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001151 FunctionDecl *OperatorNew = 0;
1152 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001153 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
1154 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001155
Sebastian Redl28507842009-02-26 14:39:58 +00001156 if (!AllocType->isDependentType() &&
1157 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
1158 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +00001159 SourceRange(PlacementLParen, PlacementRParen),
1160 UseGlobal, AllocType, ArraySize, PlaceArgs,
1161 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +00001162 return ExprError();
John McCall6ec278d2011-01-27 09:37:56 +00001163
1164 // If this is an array allocation, compute whether the usual array
1165 // deallocation function for the type has a size_t parameter.
1166 bool UsualArrayDeleteWantsSize = false;
1167 if (ArraySize && !AllocType->isDependentType())
1168 UsualArrayDeleteWantsSize
1169 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1170
Chris Lattner5f9e2722011-07-23 10:55:15 +00001171 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001172 if (OperatorNew) {
1173 // Add default arguments, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001174 const FunctionProtoType *Proto =
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001175 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001176 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00001177 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001178
Anders Carlsson28e94832010-05-03 02:07:56 +00001179 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001180 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlsson28e94832010-05-03 02:07:56 +00001181 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001182 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001183
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001184 NumPlaceArgs = AllPlaceArgs.size();
1185 if (NumPlaceArgs > 0)
1186 PlaceArgs = &AllPlaceArgs[0];
1187 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001188
Nick Lewyckyfca84b22012-01-24 21:15:41 +00001189 // Warn if the type is over-aligned and is being allocated by global operator
1190 // new.
Nick Lewycky507a8a32012-02-04 03:30:14 +00001191 if (NumPlaceArgs == 0 && OperatorNew &&
Nick Lewyckyfca84b22012-01-24 21:15:41 +00001192 (OperatorNew->isImplicit() ||
1193 getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) {
1194 if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
1195 unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
1196 if (Align > SuitableAlign)
1197 Diag(StartLoc, diag::warn_overaligned_type)
1198 << AllocType
1199 << unsigned(Align / Context.getCharWidth())
1200 << unsigned(SuitableAlign / Context.getCharWidth());
1201 }
1202 }
1203
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001204 bool Init = ConstructorLParen.isValid() || ConstructorArgs.size() > 0;
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001205 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001206 CXXConstructorDecl *Constructor = 0;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001207 bool HadMultipleCandidates = false;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001208 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
1209 unsigned NumConsArgs = ConstructorArgs.size();
John McCallca0408f2010-08-23 06:44:23 +00001210 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
Eli Friedmana8ce9ec2009-11-08 22:15:39 +00001211
Anders Carlsson48c95012010-05-03 15:45:23 +00001212 // Array 'new' can't have any initializers.
Anders Carlsson55cbd6e2010-05-16 16:24:20 +00001213 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlsson48c95012010-05-03 15:45:23 +00001214 SourceRange InitRange(ConsArgs[0]->getLocStart(),
1215 ConsArgs[NumConsArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001216
Anders Carlsson48c95012010-05-03 15:45:23 +00001217 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1218 return ExprError();
1219 }
1220
Douglas Gregor99a2e602009-12-16 01:38:02 +00001221 if (!AllocType->isDependentType() &&
1222 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001223 // C++11 [expr.new]p15:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001224 // A new-expression that creates an object of type T initializes that
1225 // object as follows:
1226 InitializationKind Kind
1227 // - If the new-initializer is omitted, the object is default-
1228 // initialized (8.5); if no initialization is performed,
1229 // the object has indeterminate value
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001230 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001231 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor99a2e602009-12-16 01:38:02 +00001232 // initialization rules of 8.5 for direct-initialization.
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001233 : ListInitialization ? InitializationKind::CreateDirectList(
1234 TypeRange.getBegin())
1235 : InitializationKind::CreateDirect(
1236 TypeRange.getBegin(),
1237 ConstructorLParen,
1238 ConstructorRParen);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001239
Douglas Gregor99a2e602009-12-16 01:38:02 +00001240 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00001241 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001242 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001243 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor99a2e602009-12-16 01:38:02 +00001244 move(ConstructorArgs));
1245 if (FullInit.isInvalid())
1246 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001247
1248 // FullInit is our initializer; walk through it to determine if it's a
Douglas Gregor99a2e602009-12-16 01:38:02 +00001249 // constructor call, which CXXNewExpr handles directly.
1250 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1251 if (CXXBindTemporaryExpr *Binder
1252 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1253 FullInitExpr = Binder->getSubExpr();
1254 if (CXXConstructExpr *Construct
1255 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1256 Constructor = Construct->getConstructor();
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001257 HadMultipleCandidates = Construct->hadMultipleCandidates();
Douglas Gregor99a2e602009-12-16 01:38:02 +00001258 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1259 AEnd = Construct->arg_end();
1260 A != AEnd; ++A)
John McCall3fa5cae2010-10-26 07:05:15 +00001261 ConvertedConstructorArgs.push_back(*A);
Douglas Gregor99a2e602009-12-16 01:38:02 +00001262 } else {
1263 // Take the converted initializer.
1264 ConvertedConstructorArgs.push_back(FullInit.release());
1265 }
1266 } else {
1267 // No initialization required.
1268 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001269
Douglas Gregor99a2e602009-12-16 01:38:02 +00001270 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001271 NumConsArgs = ConvertedConstructorArgs.size();
1272 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001273 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001274
Douglas Gregor6d908702010-02-26 05:06:18 +00001275 // Mark the new and delete operators as referenced.
1276 if (OperatorNew)
Eli Friedman5f2987c2012-02-02 03:46:19 +00001277 MarkFunctionReferenced(StartLoc, OperatorNew);
Douglas Gregor6d908702010-02-26 05:06:18 +00001278 if (OperatorDelete)
Eli Friedman5f2987c2012-02-02 03:46:19 +00001279 MarkFunctionReferenced(StartLoc, OperatorDelete);
Douglas Gregor6d908702010-02-26 05:06:18 +00001280
John McCall84ff0fc2011-07-13 20:12:57 +00001281 // C++0x [expr.new]p17:
1282 // If the new expression creates an array of objects of class type,
1283 // access and ambiguity control are done for the destructor.
1284 if (ArraySize && Constructor) {
1285 if (CXXDestructorDecl *dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00001286 MarkFunctionReferenced(StartLoc, dtor);
John McCall84ff0fc2011-07-13 20:12:57 +00001287 CheckDestructorAccess(StartLoc, dtor,
1288 PDiag(diag::err_access_dtor)
1289 << Context.getBaseElementType(AllocType));
1290 }
1291 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001292
Sebastian Redlf53597f2009-03-15 17:47:39 +00001293 PlacementArgs.release();
1294 ConstructorArgs.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001295
Ted Kremenekad7fe862010-02-11 22:51:03 +00001296 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001297 PlaceArgs, NumPlaceArgs, TypeIdParens,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001298 ArraySize, Constructor, Init,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001299 ConsArgs, NumConsArgs,
1300 HadMultipleCandidates,
1301 OperatorDelete,
John McCall6ec278d2011-01-27 09:37:56 +00001302 UsualArrayDeleteWantsSize,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001303 ResultType, AllocTypeInfo,
1304 StartLoc,
Ted Kremenekad7fe862010-02-11 22:51:03 +00001305 Init ? ConstructorRParen :
Chandler Carruth428edaf2010-10-25 08:47:36 +00001306 TypeRange.getEnd(),
1307 ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001308}
1309
1310/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1311/// in a new-expression.
1312/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +00001313bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00001314 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001315 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1316 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +00001317 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001318 return Diag(Loc, diag::err_bad_new_type)
1319 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001320 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001321 return Diag(Loc, diag::err_bad_new_type)
1322 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001323 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +00001324 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001325 PDiag(diag::err_new_incomplete_type)
1326 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001327 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +00001328 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +00001329 diag::err_allocation_of_abstract_type))
1330 return true;
Douglas Gregora0750762010-10-06 16:00:31 +00001331 else if (AllocType->isVariablyModifiedType())
1332 return Diag(Loc, diag::err_variably_modified_new_type)
1333 << AllocType;
Douglas Gregor5666d362011-04-15 19:46:20 +00001334 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1335 return Diag(Loc, diag::err_address_space_qualified_new)
1336 << AllocType.getUnqualifiedType() << AddressSpace;
John McCallf85e1932011-06-15 23:02:42 +00001337 else if (getLangOptions().ObjCAutoRefCount) {
1338 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1339 QualType BaseAllocType = Context.getBaseElementType(AT);
1340 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1341 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001342 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001343 << BaseAllocType;
1344 }
1345 }
Douglas Gregor5666d362011-04-15 19:46:20 +00001346
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001347 return false;
1348}
1349
Douglas Gregor6d908702010-02-26 05:06:18 +00001350/// \brief Determine whether the given function is a non-placement
1351/// deallocation function.
1352static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1353 if (FD->isInvalidDecl())
1354 return false;
1355
1356 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1357 return Method->isUsualDeallocationFunction();
1358
1359 return ((FD->getOverloadedOperator() == OO_Delete ||
1360 FD->getOverloadedOperator() == OO_Array_Delete) &&
1361 FD->getNumParams() == 1);
1362}
1363
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001364/// FindAllocationFunctions - Finds the overloads of operator new and delete
1365/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001366bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1367 bool UseGlobal, QualType AllocType,
1368 bool IsArray, Expr **PlaceArgs,
1369 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001370 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +00001371 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001372 // --- Choosing an allocation function ---
1373 // C++ 5.3.4p8 - 14 & 18
1374 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1375 // in the scope of the allocated class.
1376 // 2) If an array size is given, look for operator new[], else look for
1377 // operator new.
1378 // 3) The first argument is always size_t. Append the arguments from the
1379 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001380
Chris Lattner5f9e2722011-07-23 10:55:15 +00001381 SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001382 // We don't care about the actual value of this argument.
1383 // FIXME: Should the Sema create the expression and embed it in the syntax
1384 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001385 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001386 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssond67c4c32009-08-16 20:29:29 +00001387 Context.getSizeType(),
1388 SourceLocation());
1389 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001390 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1391
Douglas Gregor6d908702010-02-26 05:06:18 +00001392 // C++ [expr.new]p8:
1393 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001394 // function's name is operator new and the deallocation function's
Douglas Gregor6d908702010-02-26 05:06:18 +00001395 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001396 // type, the allocation function's name is operator new[] and the
1397 // deallocation function's name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001398 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1399 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001400 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1401 IsArray ? OO_Array_Delete : OO_Delete);
1402
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001403 QualType AllocElemType = Context.getBaseElementType(AllocType);
1404
1405 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001406 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001407 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001408 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001409 AllocArgs.size(), Record, /*AllowMissing=*/true,
1410 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001411 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001412 }
1413 if (!OperatorNew) {
1414 // Didn't find a member overload. Look for a global one.
1415 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001416 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001417 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001418 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1419 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001420 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001421 }
1422
John McCall9c82afc2010-04-20 02:18:25 +00001423 // We don't need an operator delete if we're running under
1424 // -fno-exceptions.
1425 if (!getLangOptions().Exceptions) {
1426 OperatorDelete = 0;
1427 return false;
1428 }
1429
Anders Carlssond9583892009-05-31 20:26:12 +00001430 // FindAllocationOverload can change the passed in arguments, so we need to
1431 // copy them back.
1432 if (NumPlaceArgs > 0)
1433 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001434
Douglas Gregor6d908702010-02-26 05:06:18 +00001435 // C++ [expr.new]p19:
1436 //
1437 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001438 // deallocation function's name is looked up in the global
Douglas Gregor6d908702010-02-26 05:06:18 +00001439 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001440 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6d908702010-02-26 05:06:18 +00001441 // the scope of T. If this lookup fails to find the name, or if
1442 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001443 // deallocation function's name is looked up in the global scope.
Douglas Gregor6d908702010-02-26 05:06:18 +00001444 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001445 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001446 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001447 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001448 LookupQualifiedName(FoundDelete, RD);
1449 }
John McCall90c8c572010-03-18 08:19:33 +00001450 if (FoundDelete.isAmbiguous())
1451 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001452
1453 if (FoundDelete.empty()) {
1454 DeclareGlobalNewDelete();
1455 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1456 }
1457
1458 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001459
Chris Lattner5f9e2722011-07-23 10:55:15 +00001460 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCall9aa472c2010-03-19 07:35:19 +00001461
John McCalledeb6c92010-09-14 21:34:24 +00001462 // Whether we're looking for a placement operator delete is dictated
1463 // by whether we selected a placement operator new, not by whether
1464 // we had explicit placement arguments. This matters for things like
1465 // struct A { void *operator new(size_t, int = 0); ... };
1466 // A *a = new A()
1467 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1468
1469 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001470 // C++ [expr.new]p20:
1471 // A declaration of a placement deallocation function matches the
1472 // declaration of a placement allocation function if it has the
1473 // same number of parameters and, after parameter transformations
1474 // (8.3.5), all parameter types except the first are
1475 // identical. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001476 //
Douglas Gregor6d908702010-02-26 05:06:18 +00001477 // To perform this comparison, we compute the function type that
1478 // the deallocation function should have, and use that type both
1479 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001480 //
1481 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001482 QualType ExpectedFunctionType;
1483 {
1484 const FunctionProtoType *Proto
1485 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001486
Chris Lattner5f9e2722011-07-23 10:55:15 +00001487 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001488 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6d908702010-02-26 05:06:18 +00001489 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1490 ArgTypes.push_back(Proto->getArgType(I));
1491
John McCalle23cf432010-12-14 08:05:40 +00001492 FunctionProtoType::ExtProtoInfo EPI;
1493 EPI.Variadic = Proto->isVariadic();
1494
Douglas Gregor6d908702010-02-26 05:06:18 +00001495 ExpectedFunctionType
1496 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalle23cf432010-12-14 08:05:40 +00001497 ArgTypes.size(), EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001498 }
1499
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001500 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001501 DEnd = FoundDelete.end();
1502 D != DEnd; ++D) {
1503 FunctionDecl *Fn = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001504 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6d908702010-02-26 05:06:18 +00001505 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1506 // Perform template argument deduction to try to match the
1507 // expected function type.
1508 TemplateDeductionInfo Info(Context, StartLoc);
1509 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1510 continue;
1511 } else
1512 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1513
1514 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001515 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001516 }
1517 } else {
1518 // C++ [expr.new]p20:
1519 // [...] Any non-placement deallocation function matches a
1520 // non-placement allocation function. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001521 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001522 DEnd = FoundDelete.end();
1523 D != DEnd; ++D) {
1524 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1525 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001526 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001527 }
1528 }
1529
1530 // C++ [expr.new]p20:
1531 // [...] If the lookup finds a single matching deallocation
1532 // function, that function will be called; otherwise, no
1533 // deallocation function will be called.
1534 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001535 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001536
1537 // C++0x [expr.new]p20:
1538 // If the lookup finds the two-parameter form of a usual
1539 // deallocation function (3.7.4.2) and that function, considered
1540 // as a placement deallocation function, would have been
1541 // selected as a match for the allocation function, the program
1542 // is ill-formed.
1543 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1544 isNonPlacementDeallocationFunction(OperatorDelete)) {
1545 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001546 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001547 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1548 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1549 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001550 } else {
1551 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001552 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001553 }
1554 }
1555
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001556 return false;
1557}
1558
Sebastian Redl7f662392008-12-04 22:20:51 +00001559/// FindAllocationOverload - Find an fitting overload for the allocation
1560/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001561bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1562 DeclarationName Name, Expr** Args,
1563 unsigned NumArgs, DeclContext *Ctx,
Sean Hunt2be7e902011-05-12 22:46:29 +00001564 bool AllowMissing, FunctionDecl *&Operator,
1565 bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001566 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1567 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001568 if (R.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001569 if (AllowMissing || !Diagnose)
Sebastian Redl7f662392008-12-04 22:20:51 +00001570 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001571 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001572 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001573 }
1574
John McCall90c8c572010-03-18 08:19:33 +00001575 if (R.isAmbiguous())
1576 return true;
1577
1578 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001579
John McCall5769d612010-02-08 23:07:23 +00001580 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001581 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001582 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001583 // Even member operator new/delete are implicitly treated as
1584 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001585 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001586
John McCall9aa472c2010-03-19 07:35:19 +00001587 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1588 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001589 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1590 Candidates,
1591 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001592 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001593 }
1594
John McCall9aa472c2010-03-19 07:35:19 +00001595 FunctionDecl *Fn = cast<FunctionDecl>(D);
1596 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001597 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001598 }
1599
1600 // Do the resolution.
1601 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001602 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001603 case OR_Success: {
1604 // Got one!
1605 FunctionDecl *FnDecl = Best->Function;
Eli Friedman5f2987c2012-02-02 03:46:19 +00001606 MarkFunctionReferenced(StartLoc, FnDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001607 // The first argument is size_t, and the first parameter must be size_t,
1608 // too. This is checked on declaration and can be assumed. (It can't be
1609 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001610 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001611 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1612 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001613 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1614 FnDecl->getParamDecl(i));
1615
1616 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1617 return true;
1618
John McCall60d7b3a2010-08-24 06:29:42 +00001619 ExprResult Result
Sean Hunt2be7e902011-05-12 22:46:29 +00001620 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001621 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001622 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001623
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001624 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001625 }
1626 Operator = FnDecl;
Sean Hunt2be7e902011-05-12 22:46:29 +00001627 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl,
1628 Diagnose);
Sebastian Redl7f662392008-12-04 22:20:51 +00001629 return false;
1630 }
1631
1632 case OR_No_Viable_Function:
Chandler Carruth361d3802011-06-08 10:26:03 +00001633 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001634 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1635 << Name << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001636 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1637 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001638 return true;
1639
1640 case OR_Ambiguous:
Chandler Carruth361d3802011-06-08 10:26:03 +00001641 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001642 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1643 << Name << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001644 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
1645 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001646 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001647
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001648 case OR_Deleted: {
Chandler Carruth361d3802011-06-08 10:26:03 +00001649 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001650 Diag(StartLoc, diag::err_ovl_deleted_call)
1651 << Best->Function->isDeleted()
1652 << Name
1653 << getDeletedOrUnavailableSuffix(Best->Function)
1654 << Range;
Chandler Carruth361d3802011-06-08 10:26:03 +00001655 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1656 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001657 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001658 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001659 }
David Blaikieb219cfc2011-09-23 05:06:16 +00001660 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Sebastian Redl7f662392008-12-04 22:20:51 +00001661}
1662
1663
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001664/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1665/// delete. These are:
1666/// @code
Sebastian Redl8999fe12011-03-14 18:08:30 +00001667/// // C++03:
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001668/// void* operator new(std::size_t) throw(std::bad_alloc);
1669/// void* operator new[](std::size_t) throw(std::bad_alloc);
1670/// void operator delete(void *) throw();
1671/// void operator delete[](void *) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001672/// // C++0x:
1673/// void* operator new(std::size_t);
1674/// void* operator new[](std::size_t);
1675/// void operator delete(void *);
1676/// void operator delete[](void *);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001677/// @endcode
Sebastian Redl8999fe12011-03-14 18:08:30 +00001678/// C++0x operator delete is implicitly noexcept.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001679/// Note that the placement and nothrow forms of new are *not* implicitly
1680/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001681void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001682 if (GlobalNewDeleteDeclared)
1683 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001684
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001685 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001686 // [...] The following allocation and deallocation functions (18.4) are
1687 // implicitly declared in global scope in each translation unit of a
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001688 // program
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001689 //
Sebastian Redl8999fe12011-03-14 18:08:30 +00001690 // C++03:
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001691 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001692 // void* operator new[](std::size_t) throw(std::bad_alloc);
1693 // void operator delete(void*) throw();
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001694 // void operator delete[](void*) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001695 // C++0x:
1696 // void* operator new(std::size_t);
1697 // void* operator new[](std::size_t);
1698 // void operator delete(void*);
1699 // void operator delete[](void*);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001700 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001701 // These implicit declarations introduce only the function names operator
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001702 // new, operator new[], operator delete, operator delete[].
1703 //
1704 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1705 // "std" or "bad_alloc" as necessary to form the exception specification.
1706 // However, we do not make these implicit declarations visible to name
1707 // lookup.
Sebastian Redl8999fe12011-03-14 18:08:30 +00001708 // Note that the C++0x versions of operator delete are deallocation functions,
1709 // and thus are implicitly noexcept.
1710 if (!StdBadAlloc && !getLangOptions().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001711 // The "std::bad_alloc" class has not yet been declared, so build it
1712 // implicitly.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001713 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1714 getOrCreateStdNamespace(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001715 SourceLocation(), SourceLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001716 &PP.getIdentifierTable().get("bad_alloc"),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001717 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001718 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001719 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001720
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001721 GlobalNewDeleteDeclared = true;
1722
1723 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1724 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001725 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001726
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001727 DeclareGlobalAllocationFunction(
1728 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001729 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001730 DeclareGlobalAllocationFunction(
1731 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001732 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001733 DeclareGlobalAllocationFunction(
1734 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1735 Context.VoidTy, VoidPtr);
1736 DeclareGlobalAllocationFunction(
1737 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1738 Context.VoidTy, VoidPtr);
1739}
1740
1741/// DeclareGlobalAllocationFunction - Declares a single implicit global
1742/// allocation function if it doesn't already exist.
1743void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001744 QualType Return, QualType Argument,
1745 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001746 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1747
1748 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001749 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001750 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001751 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001752 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001753 // Only look at non-template functions, as it is the predefined,
1754 // non-templated allocation function we are trying to declare here.
1755 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1756 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001757 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001758 Func->getParamDecl(0)->getType().getUnqualifiedType());
1759 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001760 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1761 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001762 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001763 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001764 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001765 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001766 }
1767 }
1768
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001769 QualType BadAllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001770 bool HasBadAllocExceptionSpec
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001771 = (Name.getCXXOverloadedOperator() == OO_New ||
1772 Name.getCXXOverloadedOperator() == OO_Array_New);
Sebastian Redl8999fe12011-03-14 18:08:30 +00001773 if (HasBadAllocExceptionSpec && !getLangOptions().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001774 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001775 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001776 }
John McCalle23cf432010-12-14 08:05:40 +00001777
1778 FunctionProtoType::ExtProtoInfo EPI;
John McCalle23cf432010-12-14 08:05:40 +00001779 if (HasBadAllocExceptionSpec) {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001780 if (!getLangOptions().CPlusPlus0x) {
1781 EPI.ExceptionSpecType = EST_Dynamic;
1782 EPI.NumExceptions = 1;
1783 EPI.Exceptions = &BadAllocType;
1784 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00001785 } else {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001786 EPI.ExceptionSpecType = getLangOptions().CPlusPlus0x ?
1787 EST_BasicNoexcept : EST_DynamicNone;
John McCalle23cf432010-12-14 08:05:40 +00001788 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001789
John McCalle23cf432010-12-14 08:05:40 +00001790 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001791 FunctionDecl *Alloc =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001792 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1793 SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001794 FnType, /*TInfo=*/0, SC_None,
1795 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001796 Alloc->setImplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001797
Nuno Lopesfc284482009-12-16 16:59:22 +00001798 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001799 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001800
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001801 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001802 SourceLocation(), 0,
1803 Argument, /*TInfo=*/0,
1804 SC_None, SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00001805 Alloc->setParams(Param);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001806
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001807 // FIXME: Also add this declaration to the IdentifierResolver, but
1808 // make sure it is at the end of the chain to coincide with the
1809 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001810 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001811}
1812
Anders Carlsson78f74552009-11-15 18:45:20 +00001813bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1814 DeclarationName Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001815 FunctionDecl* &Operator, bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001816 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001817 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001818 LookupQualifiedName(Found, RD);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001819
John McCalla24dc2e2009-11-17 02:14:36 +00001820 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001821 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001822
Chandler Carruth23893242010-06-28 00:30:51 +00001823 Found.suppressDiagnostics();
1824
Chris Lattner5f9e2722011-07-23 10:55:15 +00001825 SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001826 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1827 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001828 NamedDecl *ND = (*F)->getUnderlyingDecl();
1829
1830 // Ignore template operator delete members from the check for a usual
1831 // deallocation function.
1832 if (isa<FunctionTemplateDecl>(ND))
1833 continue;
1834
1835 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001836 Matches.push_back(F.getPair());
1837 }
1838
1839 // There's exactly one suitable operator; pick it.
1840 if (Matches.size() == 1) {
1841 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
Sean Hunt2be7e902011-05-12 22:46:29 +00001842
1843 if (Operator->isDeleted()) {
1844 if (Diagnose) {
1845 Diag(StartLoc, diag::err_deleted_function_use);
1846 Diag(Operator->getLocation(), diag::note_unavailable_here) << true;
1847 }
1848 return true;
1849 }
1850
John McCall046a7462010-08-04 00:31:26 +00001851 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Sean Hunt2be7e902011-05-12 22:46:29 +00001852 Matches[0], Diagnose);
John McCall046a7462010-08-04 00:31:26 +00001853 return false;
1854
1855 // We found multiple suitable operators; complain about the ambiguity.
1856 } else if (!Matches.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001857 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001858 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1859 << Name << RD;
John McCall046a7462010-08-04 00:31:26 +00001860
Chris Lattner5f9e2722011-07-23 10:55:15 +00001861 for (SmallVectorImpl<DeclAccessPair>::iterator
Sean Huntcb45a0f2011-05-12 22:46:25 +00001862 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1863 Diag((*F)->getUnderlyingDecl()->getLocation(),
1864 diag::note_member_declared_here) << Name;
1865 }
John McCall046a7462010-08-04 00:31:26 +00001866 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001867 }
1868
1869 // We did find operator delete/operator delete[] declarations, but
1870 // none of them were suitable.
1871 if (!Found.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001872 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001873 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1874 << Name << RD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001875
Sean Huntcb45a0f2011-05-12 22:46:25 +00001876 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1877 F != FEnd; ++F)
1878 Diag((*F)->getUnderlyingDecl()->getLocation(),
1879 diag::note_member_declared_here) << Name;
1880 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001881 return true;
1882 }
1883
1884 // Look for a global declaration.
1885 DeclareGlobalNewDelete();
1886 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001887
Anders Carlsson78f74552009-11-15 18:45:20 +00001888 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1889 Expr* DeallocArgs[1];
1890 DeallocArgs[0] = &Null;
1891 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001892 DeallocArgs, 1, TUDecl, !Diagnose,
1893 Operator, Diagnose))
Anders Carlsson78f74552009-11-15 18:45:20 +00001894 return true;
1895
1896 assert(Operator && "Did not find a deallocation function!");
1897 return false;
1898}
1899
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001900/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1901/// @code ::delete ptr; @endcode
1902/// or
1903/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001904ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001905Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley429bb272011-04-08 18:41:53 +00001906 bool ArrayForm, Expr *ExE) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001907 // C++ [expr.delete]p1:
1908 // The operand shall have a pointer type, or a class type having a single
1909 // conversion function to a pointer type. The result has type void.
1910 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001911 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1912
John Wiegley429bb272011-04-08 18:41:53 +00001913 ExprResult Ex = Owned(ExE);
Anders Carlssond67c4c32009-08-16 20:29:29 +00001914 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00001915 bool ArrayFormAsWritten = ArrayForm;
John McCall6ec278d2011-01-27 09:37:56 +00001916 bool UsualArrayDeleteWantsSize = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001917
John Wiegley429bb272011-04-08 18:41:53 +00001918 if (!Ex.get()->isTypeDependent()) {
1919 QualType Type = Ex.get()->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001920
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001921 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001922 if (RequireCompleteType(StartLoc, Type,
Douglas Gregor254a9422010-07-29 14:44:35 +00001923 PDiag(diag::err_delete_incomplete_class_type)))
1924 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001925
Chris Lattner5f9e2722011-07-23 10:55:15 +00001926 SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
John McCall32daa422010-03-31 01:36:47 +00001927
Fariborz Jahanian53462782009-09-11 21:44:33 +00001928 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001929 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001930 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001931 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001932 NamedDecl *D = I.getDecl();
1933 if (isa<UsingShadowDecl>(D))
1934 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1935
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001936 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001937 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001938 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001939
John McCall32daa422010-03-31 01:36:47 +00001940 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001941
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001942 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1943 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00001944 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001945 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001946 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001947 if (ObjectPtrConversions.size() == 1) {
1948 // We have a single conversion to a pointer-to-object type. Perform
1949 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001950 // TODO: don't redo the conversion calculation.
John Wiegley429bb272011-04-08 18:41:53 +00001951 ExprResult Res =
1952 PerformImplicitConversion(Ex.get(),
John McCall32daa422010-03-31 01:36:47 +00001953 ObjectPtrConversions.front()->getConversionType(),
John Wiegley429bb272011-04-08 18:41:53 +00001954 AA_Converting);
1955 if (Res.isUsable()) {
1956 Ex = move(Res);
1957 Type = Ex.get()->getType();
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001958 }
1959 }
1960 else if (ObjectPtrConversions.size() > 1) {
1961 Diag(StartLoc, diag::err_ambiguous_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001962 << Type << Ex.get()->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001963 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1964 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001965 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001966 }
Sebastian Redl28507842009-02-26 14:39:58 +00001967 }
1968
Sebastian Redlf53597f2009-03-15 17:47:39 +00001969 if (!Type->isPointerType())
1970 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001971 << Type << Ex.get()->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001972
Ted Kremenek6217b802009-07-29 21:53:49 +00001973 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmane52c9142011-07-26 22:25:31 +00001974 QualType PointeeElem = Context.getBaseElementType(Pointee);
1975
1976 if (unsigned AddressSpace = Pointee.getAddressSpace())
1977 return Diag(Ex.get()->getLocStart(),
1978 diag::err_address_space_qualified_delete)
1979 << Pointee.getUnqualifiedType() << AddressSpace;
1980
1981 CXXRecordDecl *PointeeRD = 0;
Douglas Gregor94a61572010-05-24 17:01:56 +00001982 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001983 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregor94a61572010-05-24 17:01:56 +00001984 // effectively bans deletion of "void*". However, most compilers support
1985 // this, so we treat it as a warning unless we're in a SFINAE context.
1986 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001987 << Type << Ex.get()->getSourceRange();
Eli Friedmane52c9142011-07-26 22:25:31 +00001988 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00001989 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00001990 << Type << Ex.get()->getSourceRange());
Eli Friedmane52c9142011-07-26 22:25:31 +00001991 } else if (!Pointee->isDependentType()) {
1992 if (!RequireCompleteType(StartLoc, Pointee,
1993 PDiag(diag::warn_delete_incomplete)
1994 << Ex.get()->getSourceRange())) {
1995 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
1996 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
1997 }
1998 }
1999
Abramo Bagnara30bb4202011-11-16 15:42:13 +00002000 // Perform lvalue-to-rvalue cast, if needed.
2001 Ex = DefaultLvalueConversion(Ex.take());
2002
Douglas Gregor1070c9f2009-09-29 21:38:53 +00002003 // C++ [expr.delete]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002004 // [Note: a pointer to a const type can be the operand of a
2005 // delete-expression; it is not necessary to cast away the constness
2006 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor1070c9f2009-09-29 21:38:53 +00002007 // of the delete-expression. ]
John McCallf85e1932011-06-15 23:02:42 +00002008 if (!Context.hasSameType(Ex.get()->getType(), Context.VoidPtrTy))
Abramo Bagnara30bb4202011-11-16 15:42:13 +00002009 Ex = Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy,
2010 CK_BitCast, Ex.take(), 0, VK_RValue));
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00002011
2012 if (Pointee->isArrayType() && !ArrayForm) {
2013 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley429bb272011-04-08 18:41:53 +00002014 << Type << Ex.get()->getSourceRange()
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00002015 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
2016 ArrayForm = true;
2017 }
2018
Anders Carlssond67c4c32009-08-16 20:29:29 +00002019 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2020 ArrayForm ? OO_Array_Delete : OO_Delete);
2021
Eli Friedmane52c9142011-07-26 22:25:31 +00002022 if (PointeeRD) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002023 if (!UseGlobal &&
Eli Friedmane52c9142011-07-26 22:25:31 +00002024 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
2025 OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00002026 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002027
John McCall6ec278d2011-01-27 09:37:56 +00002028 // If we're allocating an array of records, check whether the
2029 // usual operator delete[] has a size_t parameter.
2030 if (ArrayForm) {
2031 // If the user specifically asked to use the global allocator,
2032 // we'll need to do the lookup into the class.
2033 if (UseGlobal)
2034 UsualArrayDeleteWantsSize =
2035 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
2036
2037 // Otherwise, the usual operator delete[] should be the
2038 // function we just found.
2039 else if (isa<CXXMethodDecl>(OperatorDelete))
2040 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
2041 }
2042
Eli Friedmane52c9142011-07-26 22:25:31 +00002043 if (!PointeeRD->hasTrivialDestructor())
2044 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002045 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002046 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00002047 DiagnoseUseOfDecl(Dtor, StartLoc);
2048 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00002049
2050 // C++ [expr.delete]p3:
2051 // In the first alternative (delete object), if the static type of the
2052 // object to be deleted is different from its dynamic type, the static
2053 // type shall be a base class of the dynamic type of the object to be
2054 // deleted and the static type shall have a virtual destructor or the
2055 // behavior is undefined.
2056 //
2057 // Note: a final class cannot be derived from, no issue there
Eli Friedmanef8c79c2011-07-26 23:27:24 +00002058 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
Eli Friedmane52c9142011-07-26 22:25:31 +00002059 CXXDestructorDecl *dtor = PointeeRD->getDestructor();
Eli Friedmanef8c79c2011-07-26 23:27:24 +00002060 if (dtor && !dtor->isVirtual()) {
2061 if (PointeeRD->isAbstract()) {
2062 // If the class is abstract, we warn by default, because we're
2063 // sure the code has undefined behavior.
2064 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
2065 << PointeeElem;
2066 } else if (!ArrayForm) {
2067 // Otherwise, if this is not an array delete, it's a bit suspect,
2068 // but not necessarily wrong.
2069 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
2070 }
2071 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00002072 }
John McCallf85e1932011-06-15 23:02:42 +00002073
2074 } else if (getLangOptions().ObjCAutoRefCount &&
2075 PointeeElem->isObjCLifetimeType() &&
2076 (PointeeElem.getObjCLifetime() == Qualifiers::OCL_Strong ||
2077 PointeeElem.getObjCLifetime() == Qualifiers::OCL_Weak) &&
2078 ArrayForm) {
2079 Diag(StartLoc, diag::warn_err_new_delete_object_array)
2080 << 1 << PointeeElem;
Anders Carlssond67c4c32009-08-16 20:29:29 +00002081 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002082
Anders Carlssond67c4c32009-08-16 20:29:29 +00002083 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00002084 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00002085 DeclareGlobalNewDelete();
2086 DeclContext *TUDecl = Context.getTranslationUnitDecl();
John Wiegley429bb272011-04-08 18:41:53 +00002087 Expr *Arg = Ex.get();
Mike Stump1eb44332009-09-09 15:08:12 +00002088 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
John Wiegley429bb272011-04-08 18:41:53 +00002089 &Arg, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00002090 OperatorDelete))
2091 return ExprError();
2092 }
Mike Stump1eb44332009-09-09 15:08:12 +00002093
Eli Friedman5f2987c2012-02-02 03:46:19 +00002094 MarkFunctionReferenced(StartLoc, OperatorDelete);
John McCall6ec278d2011-01-27 09:37:56 +00002095
Douglas Gregord880f522011-02-01 15:50:11 +00002096 // Check access and ambiguity of operator delete and destructor.
Eli Friedmane52c9142011-07-26 22:25:31 +00002097 if (PointeeRD) {
2098 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
John Wiegley429bb272011-04-08 18:41:53 +00002099 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregord880f522011-02-01 15:50:11 +00002100 PDiag(diag::err_access_dtor) << PointeeElem);
2101 }
2102 }
2103
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002104 }
2105
Sebastian Redlf53597f2009-03-15 17:47:39 +00002106 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall6ec278d2011-01-27 09:37:56 +00002107 ArrayFormAsWritten,
2108 UsualArrayDeleteWantsSize,
John Wiegley429bb272011-04-08 18:41:53 +00002109 OperatorDelete, Ex.take(), StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002110}
2111
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002112/// \brief Check the use of the given variable as a C++ condition in an if,
2113/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00002114ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00002115 SourceLocation StmtLoc,
2116 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002117 QualType T = ConditionVar->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002118
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002119 // C++ [stmt.select]p2:
2120 // The declarator shall not specify a function or an array.
2121 if (T->isFunctionType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002122 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002123 diag::err_invalid_use_of_function_type)
2124 << ConditionVar->getSourceRange());
2125 else if (T->isArrayType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002126 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002127 diag::err_invalid_use_of_array_type)
2128 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00002129
John Wiegley429bb272011-04-08 18:41:53 +00002130 ExprResult Condition =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002131 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2132 SourceLocation(),
2133 ConditionVar,
2134 ConditionVar->getLocation(),
2135 ConditionVar->getType().getNonReferenceType(),
John Wiegley429bb272011-04-08 18:41:53 +00002136 VK_LValue));
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002137
Eli Friedman5f2987c2012-02-02 03:46:19 +00002138 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002139
John Wiegley429bb272011-04-08 18:41:53 +00002140 if (ConvertToBoolean) {
2141 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
2142 if (Condition.isInvalid())
2143 return ExprError();
2144 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002145
John Wiegley429bb272011-04-08 18:41:53 +00002146 return move(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002147}
2148
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002149/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley429bb272011-04-08 18:41:53 +00002150ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002151 // C++ 6.4p4:
2152 // The value of a condition that is an initialized declaration in a statement
2153 // other than a switch statement is the value of the declared variable
2154 // implicitly converted to type bool. If that conversion is ill-formed, the
2155 // program is ill-formed.
2156 // The value of a condition that is an expression is the value of the
2157 // expression, implicitly converted to bool.
2158 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002159 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002160}
Douglas Gregor77a52232008-09-12 00:47:35 +00002161
2162/// Helper function to determine whether this is the (deprecated) C++
2163/// conversion from a string literal to a pointer to non-const char or
2164/// non-const wchar_t (for narrow and wide string literals,
2165/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00002166bool
Douglas Gregor77a52232008-09-12 00:47:35 +00002167Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2168 // Look inside the implicit cast, if it exists.
2169 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2170 From = Cast->getSubExpr();
2171
2172 // A string literal (2.13.4) that is not a wide string literal can
2173 // be converted to an rvalue of type "pointer to char"; a wide
2174 // string literal can be converted to an rvalue of type "pointer
2175 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00002176 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00002177 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00002178 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00002179 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00002180 // This conversion is considered only when there is an
2181 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregor5cee1192011-07-27 05:40:30 +00002182 if (!ToPtrType->getPointeeType().hasQualifiers()) {
2183 switch (StrLit->getKind()) {
2184 case StringLiteral::UTF8:
2185 case StringLiteral::UTF16:
2186 case StringLiteral::UTF32:
2187 // We don't allow UTF literals to be implicitly converted
2188 break;
2189 case StringLiteral::Ascii:
2190 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2191 ToPointeeType->getKind() == BuiltinType::Char_S);
2192 case StringLiteral::Wide:
2193 return ToPointeeType->isWideCharType();
2194 }
2195 }
Douglas Gregor77a52232008-09-12 00:47:35 +00002196 }
2197
2198 return false;
2199}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002200
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002201static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00002202 SourceLocation CastLoc,
2203 QualType Ty,
2204 CastKind Kind,
2205 CXXMethodDecl *Method,
John McCallca82a822011-09-21 08:36:56 +00002206 DeclAccessPair FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002207 bool HadMultipleCandidates,
John McCall2de56d12010-08-25 11:45:40 +00002208 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002209 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002210 default: llvm_unreachable("Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00002211 case CK_ConstructorConversion: {
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002212 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
John McCallca0408f2010-08-23 06:44:23 +00002213 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002214
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002215 if (S.CompleteConstructorCall(Constructor,
John McCallf312b1e2010-08-26 23:41:50 +00002216 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00002217 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00002218 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002219
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002220 S.CheckConstructorAccess(CastLoc, Constructor, Constructor->getAccess(),
2221 S.PDiag(diag::err_access_ctor));
2222
2223 ExprResult Result
2224 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2225 move_arg(ConstructorArgs),
2226 HadMultipleCandidates, /*ZeroInit*/ false,
2227 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002228 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00002229 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002230
Douglas Gregorba70ab62010-04-16 22:17:36 +00002231 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2232 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002233
John McCall2de56d12010-08-25 11:45:40 +00002234 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002235 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002236
Douglas Gregorba70ab62010-04-16 22:17:36 +00002237 // Create an implicit call expr that calls it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002238 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method,
2239 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002240 if (Result.isInvalid())
2241 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00002242 // Record usage of conversion in an implicit cast.
2243 Result = S.Owned(ImplicitCastExpr::Create(S.Context,
2244 Result.get()->getType(),
2245 CK_UserDefinedConversion,
2246 Result.get(), 0,
2247 Result.get()->getValueKind()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002248
John McCallca82a822011-09-21 08:36:56 +00002249 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2250
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002251 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002252 }
2253 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002254}
Douglas Gregorba70ab62010-04-16 22:17:36 +00002255
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002256/// PerformImplicitConversion - Perform an implicit conversion of the
2257/// expression From to the type ToType using the pre-computed implicit
John Wiegley429bb272011-04-08 18:41:53 +00002258/// conversion sequence ICS. Returns the converted
Douglas Gregor68647482009-12-16 03:45:30 +00002259/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002260/// used in the error message.
John Wiegley429bb272011-04-08 18:41:53 +00002261ExprResult
2262Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002263 const ImplicitConversionSequence &ICS,
John McCallf85e1932011-06-15 23:02:42 +00002264 AssignmentAction Action,
2265 CheckedConversionKind CCK) {
John McCall1d318332010-01-12 00:44:57 +00002266 switch (ICS.getKind()) {
John Wiegley429bb272011-04-08 18:41:53 +00002267 case ImplicitConversionSequence::StandardConversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002268 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2269 Action, CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002270 if (Res.isInvalid())
2271 return ExprError();
2272 From = Res.take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002273 break;
John Wiegley429bb272011-04-08 18:41:53 +00002274 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002275
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002276 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002277
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00002278 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00002279 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002280 QualType BeforeToType;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00002281 assert(FD && "FIXME: aggregate initialization from init list");
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002282 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00002283 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002284
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002285 // If the user-defined conversion is specified by a conversion function,
2286 // the initial standard conversion sequence converts the source type to
2287 // the implicit object parameter of the conversion function.
2288 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00002289 } else {
2290 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00002291 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002292 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00002293 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002294 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002295 // initial standard conversion sequence converts the source type to the
2296 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00002297 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2298 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002299 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00002300 // Watch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00002301 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley429bb272011-04-08 18:41:53 +00002302 ExprResult Res =
Richard Smithc8d7f582011-11-29 22:48:16 +00002303 PerformImplicitConversion(From, BeforeToType,
2304 ICS.UserDefined.Before, AA_Converting,
2305 CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002306 if (Res.isInvalid())
2307 return ExprError();
2308 From = Res.take();
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002309 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002310
2311 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00002312 = BuildCXXCastArgument(*this,
2313 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00002314 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002315 CastKind, cast<CXXMethodDecl>(FD),
2316 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002317 ICS.UserDefined.HadMultipleCandidates,
John McCall9ae2f072010-08-23 23:25:46 +00002318 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002319
2320 if (CastArg.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00002321 return ExprError();
Eli Friedmand8889622009-11-27 04:41:50 +00002322
John Wiegley429bb272011-04-08 18:41:53 +00002323 From = CastArg.take();
Eli Friedmand8889622009-11-27 04:41:50 +00002324
Richard Smithc8d7f582011-11-29 22:48:16 +00002325 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2326 AA_Converting, CCK);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00002327 }
John McCall1d318332010-01-12 00:44:57 +00002328
2329 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00002330 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00002331 PDiag(diag::err_typecheck_ambiguous_condition)
2332 << From->getSourceRange());
John Wiegley429bb272011-04-08 18:41:53 +00002333 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002334
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002335 case ImplicitConversionSequence::EllipsisConversion:
David Blaikieb219cfc2011-09-23 05:06:16 +00002336 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002337
2338 case ImplicitConversionSequence::BadConversion:
John Wiegley429bb272011-04-08 18:41:53 +00002339 return ExprError();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002340 }
2341
2342 // Everything went well.
John Wiegley429bb272011-04-08 18:41:53 +00002343 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002344}
2345
Richard Smithc8d7f582011-11-29 22:48:16 +00002346/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002347/// expression From to the type ToType by following the standard
John Wiegley429bb272011-04-08 18:41:53 +00002348/// conversion sequence SCS. Returns the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00002349/// expression. Flavor is the context in which we're performing this
2350/// conversion, for use in error messages.
John Wiegley429bb272011-04-08 18:41:53 +00002351ExprResult
Richard Smithc8d7f582011-11-29 22:48:16 +00002352Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00002353 const StandardConversionSequence& SCS,
John McCallf85e1932011-06-15 23:02:42 +00002354 AssignmentAction Action,
2355 CheckedConversionKind CCK) {
2356 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2357
Mike Stump390b4cc2009-05-16 07:39:55 +00002358 // Overall FIXME: we are recomputing too many types here and doing far too
2359 // much extra work. What this means is that we need to keep track of more
2360 // information that is computed when we try the implicit conversion initially,
2361 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002362 QualType FromType = From->getType();
John McCallf85e1932011-06-15 23:02:42 +00002363
Douglas Gregor225c41e2008-11-03 19:09:14 +00002364 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00002365 // FIXME: When can ToType be a reference type?
2366 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002367 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00002368 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002369 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00002370 MultiExprArg(*this, &From, 1),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002371 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002372 ConstructorArgs))
John Wiegley429bb272011-04-08 18:41:53 +00002373 return ExprError();
2374 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2375 ToType, SCS.CopyConstructor,
2376 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002377 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002378 /*ZeroInit*/ false,
2379 CXXConstructExpr::CK_Complete,
2380 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002381 }
John Wiegley429bb272011-04-08 18:41:53 +00002382 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2383 ToType, SCS.CopyConstructor,
2384 MultiExprArg(*this, &From, 1),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002385 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002386 /*ZeroInit*/ false,
2387 CXXConstructExpr::CK_Complete,
2388 SourceRange());
Douglas Gregor225c41e2008-11-03 19:09:14 +00002389 }
2390
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002391 // Resolve overloaded function references.
2392 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2393 DeclAccessPair Found;
2394 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2395 true, Found);
2396 if (!Fn)
John Wiegley429bb272011-04-08 18:41:53 +00002397 return ExprError();
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002398
2399 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
John Wiegley429bb272011-04-08 18:41:53 +00002400 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002401
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002402 From = FixOverloadedFunctionReference(From, Found, Fn);
2403 FromType = From->getType();
2404 }
2405
Richard Smithc8d7f582011-11-29 22:48:16 +00002406 // Perform the first implicit conversion.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002407 switch (SCS.First) {
2408 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002409 // Nothing to do.
2410 break;
2411
Eli Friedmand814eaf2012-01-24 22:51:26 +00002412 case ICK_Lvalue_To_Rvalue: {
John McCall3c3b7f92011-10-25 17:37:35 +00002413 assert(From->getObjectKind() != OK_ObjCProperty);
John McCallf6a16482010-12-04 03:47:34 +00002414 FromType = FromType.getUnqualifiedType();
Eli Friedmand814eaf2012-01-24 22:51:26 +00002415 ExprResult FromRes = DefaultLvalueConversion(From);
2416 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
2417 From = FromRes.take();
John McCallf6a16482010-12-04 03:47:34 +00002418 break;
Eli Friedmand814eaf2012-01-24 22:51:26 +00002419 }
John McCallf6a16482010-12-04 03:47:34 +00002420
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002421 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002422 FromType = Context.getArrayDecayedType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002423 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2424 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002425 break;
2426
2427 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002428 FromType = Context.getPointerType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002429 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2430 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002431 break;
2432
2433 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002434 llvm_unreachable("Improper first standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002435 }
2436
Richard Smithc8d7f582011-11-29 22:48:16 +00002437 // Perform the second implicit conversion
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002438 switch (SCS.Second) {
2439 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002440 // If both sides are functions (or pointers/references to them), there could
2441 // be incompatible exception declarations.
2442 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002443 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002444 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002445 break;
2446
Douglas Gregor43c79c22009-12-09 00:47:37 +00002447 case ICK_NoReturn_Adjustment:
2448 // If both sides are functions (or pointers/references to them), there could
2449 // be incompatible exception declarations.
2450 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002451 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002452
Richard Smithc8d7f582011-11-29 22:48:16 +00002453 From = ImpCastExprToType(From, ToType, CK_NoOp,
2454 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor43c79c22009-12-09 00:47:37 +00002455 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002456
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002457 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002458 case ICK_Integral_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002459 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2460 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002461 break;
2462
2463 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002464 case ICK_Floating_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002465 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2466 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002467 break;
2468
2469 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00002470 case ICK_Complex_Conversion: {
2471 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2472 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2473 CastKind CK;
2474 if (FromEl->isRealFloatingType()) {
2475 if (ToEl->isRealFloatingType())
2476 CK = CK_FloatingComplexCast;
2477 else
2478 CK = CK_FloatingComplexToIntegralComplex;
2479 } else if (ToEl->isRealFloatingType()) {
2480 CK = CK_IntegralComplexToFloatingComplex;
2481 } else {
2482 CK = CK_IntegralComplexCast;
2483 }
Richard Smithc8d7f582011-11-29 22:48:16 +00002484 From = ImpCastExprToType(From, ToType, CK,
2485 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002486 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00002487 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002488
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002489 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002490 if (ToType->isRealFloatingType())
Richard Smithc8d7f582011-11-29 22:48:16 +00002491 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2492 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002493 else
Richard Smithc8d7f582011-11-29 22:48:16 +00002494 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2495 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002496 break;
2497
Douglas Gregorf9201e02009-02-11 23:02:49 +00002498 case ICK_Compatible_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002499 From = ImpCastExprToType(From, ToType, CK_NoOp,
2500 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002501 break;
2502
John McCallf85e1932011-06-15 23:02:42 +00002503 case ICK_Writeback_Conversion:
Anders Carlsson61faec12009-09-12 04:46:44 +00002504 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00002505 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002506 // Diagnose incompatible Objective-C conversions
Douglas Gregor8cf0d222011-06-11 04:42:12 +00002507 if (Action == AA_Initializing || Action == AA_Assigning)
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002508 Diag(From->getSourceRange().getBegin(),
2509 diag::ext_typecheck_convert_incompatible_pointer)
2510 << ToType << From->getType() << Action
Anna Zaks67221552011-07-28 19:51:27 +00002511 << From->getSourceRange() << 0;
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002512 else
2513 Diag(From->getSourceRange().getBegin(),
2514 diag::ext_typecheck_convert_incompatible_pointer)
2515 << From->getType() << ToType << Action
Anna Zaks67221552011-07-28 19:51:27 +00002516 << From->getSourceRange() << 0;
John McCallf85e1932011-06-15 23:02:42 +00002517
Douglas Gregor926df6c2011-06-11 01:09:30 +00002518 if (From->getType()->isObjCObjectPointerType() &&
2519 ToType->isObjCObjectPointerType())
2520 EmitRelatedResultTypeNote(From);
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002521 }
2522 else if (getLangOptions().ObjCAutoRefCount &&
2523 !CheckObjCARCUnavailableWeakConversion(ToType,
2524 From->getType())) {
John McCall7f3a6d32011-09-09 06:12:06 +00002525 if (Action == AA_Initializing)
2526 Diag(From->getSourceRange().getBegin(),
2527 diag::err_arc_weak_unavailable_assign);
2528 else
2529 Diag(From->getSourceRange().getBegin(),
2530 diag::err_arc_convesion_of_weak_unavailable)
2531 << (Action == AA_Casting) << From->getType() << ToType
2532 << From->getSourceRange();
2533 }
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002534
John McCalldaa8e4e2010-11-15 09:13:47 +00002535 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002536 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002537 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002538 return ExprError();
John McCalldc05b112011-09-10 01:16:55 +00002539
2540 // Make sure we extend blocks if necessary.
2541 // FIXME: doing this here is really ugly.
2542 if (Kind == CK_BlockPointerToObjCPointerCast) {
2543 ExprResult E = From;
2544 (void) PrepareCastToObjCObjectPointer(E);
2545 From = E.take();
2546 }
2547
Richard Smithc8d7f582011-11-29 22:48:16 +00002548 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2549 .take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002550 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00002551 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002552
Anders Carlsson61faec12009-09-12 04:46:44 +00002553 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002554 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002555 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002556 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002557 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002558 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002559 return ExprError();
Richard Smithc8d7f582011-11-29 22:48:16 +00002560 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2561 .take();
Anders Carlsson61faec12009-09-12 04:46:44 +00002562 break;
2563 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002564
Abramo Bagnara737d5442011-04-07 09:26:19 +00002565 case ICK_Boolean_Conversion:
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00002566 // Perform half-to-boolean conversion via float.
2567 if (From->getType()->isHalfType()) {
2568 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take();
2569 FromType = Context.FloatTy;
2570 }
2571
Richard Smithc8d7f582011-11-29 22:48:16 +00002572 From = ImpCastExprToType(From, Context.BoolTy,
2573 ScalarTypeToBooleanCastKind(FromType),
2574 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002575 break;
2576
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002577 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002578 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002579 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002580 ToType.getNonReferenceType(),
2581 From->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002582 From->getSourceRange(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002583 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002584 CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002585 return ExprError();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002586
Richard Smithc8d7f582011-11-29 22:48:16 +00002587 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2588 CK_DerivedToBase, From->getValueKind(),
2589 &BasePath, CCK).take();
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002590 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002591 }
2592
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002593 case ICK_Vector_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002594 From = ImpCastExprToType(From, ToType, CK_BitCast,
2595 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002596 break;
2597
2598 case ICK_Vector_Splat:
Richard Smithc8d7f582011-11-29 22:48:16 +00002599 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2600 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002601 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002602
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002603 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002604 // Case 1. x -> _Complex y
2605 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2606 QualType ElType = ToComplex->getElementType();
2607 bool isFloatingComplex = ElType->isRealFloatingType();
2608
2609 // x -> y
2610 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2611 // do nothing
2612 } else if (From->getType()->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002613 From = ImpCastExprToType(From, ElType,
2614 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002615 } else {
2616 assert(From->getType()->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002617 From = ImpCastExprToType(From, ElType,
2618 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002619 }
2620 // y -> _Complex y
Richard Smithc8d7f582011-11-29 22:48:16 +00002621 From = ImpCastExprToType(From, ToType,
2622 isFloatingComplex ? CK_FloatingRealToComplex
2623 : CK_IntegralRealToComplex).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002624
2625 // Case 2. _Complex x -> y
2626 } else {
2627 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2628 assert(FromComplex);
2629
2630 QualType ElType = FromComplex->getElementType();
2631 bool isFloatingComplex = ElType->isRealFloatingType();
2632
2633 // _Complex x -> x
Richard Smithc8d7f582011-11-29 22:48:16 +00002634 From = ImpCastExprToType(From, ElType,
2635 isFloatingComplex ? CK_FloatingComplexToReal
2636 : CK_IntegralComplexToReal,
2637 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002638
2639 // x -> y
2640 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2641 // do nothing
2642 } else if (ToType->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002643 From = ImpCastExprToType(From, ToType,
2644 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2645 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002646 } else {
2647 assert(ToType->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002648 From = ImpCastExprToType(From, ToType,
2649 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2650 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002651 }
2652 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002653 break;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002654
2655 case ICK_Block_Pointer_Conversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002656 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2657 VK_RValue, /*BasePath=*/0, CCK).take();
John McCallf85e1932011-06-15 23:02:42 +00002658 break;
2659 }
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002660
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002661 case ICK_TransparentUnionConversion: {
John Wiegley429bb272011-04-08 18:41:53 +00002662 ExprResult FromRes = Owned(From);
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002663 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002664 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2665 if (FromRes.isInvalid())
2666 return ExprError();
2667 From = FromRes.take();
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002668 assert ((ConvTy == Sema::Compatible) &&
2669 "Improper transparent union conversion");
2670 (void)ConvTy;
2671 break;
2672 }
2673
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002674 case ICK_Lvalue_To_Rvalue:
2675 case ICK_Array_To_Pointer:
2676 case ICK_Function_To_Pointer:
2677 case ICK_Qualification:
2678 case ICK_Num_Conversion_Kinds:
David Blaikieb219cfc2011-09-23 05:06:16 +00002679 llvm_unreachable("Improper second standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002680 }
2681
2682 switch (SCS.Third) {
2683 case ICK_Identity:
2684 // Nothing to do.
2685 break;
2686
Sebastian Redl906082e2010-07-20 04:20:21 +00002687 case ICK_Qualification: {
2688 // The qualification keeps the category of the inner expression, unless the
2689 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002690 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002691 From->getValueKind() : VK_RValue;
Richard Smithc8d7f582011-11-29 22:48:16 +00002692 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2693 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
Douglas Gregora9bff302010-02-28 18:30:25 +00002694
Douglas Gregor069a6da2011-03-14 16:13:32 +00002695 if (SCS.DeprecatedStringLiteralToCharPtr &&
2696 !getLangOptions().WritableStrings)
Douglas Gregora9bff302010-02-28 18:30:25 +00002697 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2698 << ToType.getNonReferenceType();
2699
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002700 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002701 }
2702
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002703 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002704 llvm_unreachable("Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002705 }
2706
John Wiegley429bb272011-04-08 18:41:53 +00002707 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002708}
2709
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002710ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002711 SourceLocation KWLoc,
2712 ParsedType Ty,
2713 SourceLocation RParen) {
2714 TypeSourceInfo *TSInfo;
2715 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002716
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002717 if (!TSInfo)
2718 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002719 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002720}
2721
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002722/// \brief Check the completeness of a type in a unary type trait.
2723///
2724/// If the particular type trait requires a complete type, tries to complete
2725/// it. If completing the type fails, a diagnostic is emitted and false
2726/// returned. If completing the type succeeds or no completion was required,
2727/// returns true.
2728static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2729 UnaryTypeTrait UTT,
2730 SourceLocation Loc,
2731 QualType ArgTy) {
2732 // C++0x [meta.unary.prop]p3:
2733 // For all of the class templates X declared in this Clause, instantiating
2734 // that template with a template argument that is a class template
2735 // specialization may result in the implicit instantiation of the template
2736 // argument if and only if the semantics of X require that the argument
2737 // must be a complete type.
2738 // We apply this rule to all the type trait expressions used to implement
2739 // these class templates. We also try to follow any GCC documented behavior
2740 // in these expressions to ensure portability of standard libraries.
2741 switch (UTT) {
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002742 // is_complete_type somewhat obviously cannot require a complete type.
2743 case UTT_IsCompleteType:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002744 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002745
2746 // These traits are modeled on the type predicates in C++0x
2747 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2748 // requiring a complete type, as whether or not they return true cannot be
2749 // impacted by the completeness of the type.
2750 case UTT_IsVoid:
2751 case UTT_IsIntegral:
2752 case UTT_IsFloatingPoint:
2753 case UTT_IsArray:
2754 case UTT_IsPointer:
2755 case UTT_IsLvalueReference:
2756 case UTT_IsRvalueReference:
2757 case UTT_IsMemberFunctionPointer:
2758 case UTT_IsMemberObjectPointer:
2759 case UTT_IsEnum:
2760 case UTT_IsUnion:
2761 case UTT_IsClass:
2762 case UTT_IsFunction:
2763 case UTT_IsReference:
2764 case UTT_IsArithmetic:
2765 case UTT_IsFundamental:
2766 case UTT_IsObject:
2767 case UTT_IsScalar:
2768 case UTT_IsCompound:
2769 case UTT_IsMemberPointer:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002770 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002771
2772 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2773 // which requires some of its traits to have the complete type. However,
2774 // the completeness of the type cannot impact these traits' semantics, and
2775 // so they don't require it. This matches the comments on these traits in
2776 // Table 49.
2777 case UTT_IsConst:
2778 case UTT_IsVolatile:
2779 case UTT_IsSigned:
2780 case UTT_IsUnsigned:
2781 return true;
2782
2783 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002784 // applied to a complete type.
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002785 case UTT_IsTrivial:
Sean Huntfeb375d2011-05-13 00:31:07 +00002786 case UTT_IsTriviallyCopyable:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002787 case UTT_IsStandardLayout:
2788 case UTT_IsPOD:
2789 case UTT_IsLiteral:
2790 case UTT_IsEmpty:
2791 case UTT_IsPolymorphic:
2792 case UTT_IsAbstract:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002793 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002794
Douglas Gregor5e9392b2011-12-03 18:14:24 +00002795 // These traits require a complete type.
2796 case UTT_IsFinal:
2797
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002798 // These trait expressions are designed to help implement predicates in
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002799 // [meta.unary.prop] despite not being named the same. They are specified
2800 // by both GCC and the Embarcadero C++ compiler, and require the complete
2801 // type due to the overarching C++0x type predicates being implemented
2802 // requiring the complete type.
2803 case UTT_HasNothrowAssign:
2804 case UTT_HasNothrowConstructor:
2805 case UTT_HasNothrowCopy:
2806 case UTT_HasTrivialAssign:
Sean Hunt023df372011-05-09 18:22:59 +00002807 case UTT_HasTrivialDefaultConstructor:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002808 case UTT_HasTrivialCopy:
2809 case UTT_HasTrivialDestructor:
2810 case UTT_HasVirtualDestructor:
2811 // Arrays of unknown bound are expressly allowed.
2812 QualType ElTy = ArgTy;
2813 if (ArgTy->isIncompleteArrayType())
2814 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2815
2816 // The void type is expressly allowed.
2817 if (ElTy->isVoidType())
2818 return true;
2819
2820 return !S.RequireCompleteType(
2821 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleycf566412011-04-28 02:06:46 +00002822 }
Chandler Carruth73e0a912011-05-01 07:23:17 +00002823 llvm_unreachable("Type trait not handled by switch");
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002824}
2825
2826static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2827 SourceLocation KeyLoc, QualType T) {
Chandler Carruthd064c702011-05-01 08:41:10 +00002828 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleycf566412011-04-28 02:06:46 +00002829
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002830 ASTContext &C = Self.Context;
2831 switch(UTT) {
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002832 // Type trait expressions corresponding to the primary type category
2833 // predicates in C++0x [meta.unary.cat].
2834 case UTT_IsVoid:
2835 return T->isVoidType();
2836 case UTT_IsIntegral:
2837 return T->isIntegralType(C);
2838 case UTT_IsFloatingPoint:
2839 return T->isFloatingType();
2840 case UTT_IsArray:
2841 return T->isArrayType();
2842 case UTT_IsPointer:
2843 return T->isPointerType();
2844 case UTT_IsLvalueReference:
2845 return T->isLValueReferenceType();
2846 case UTT_IsRvalueReference:
2847 return T->isRValueReferenceType();
2848 case UTT_IsMemberFunctionPointer:
2849 return T->isMemberFunctionPointerType();
2850 case UTT_IsMemberObjectPointer:
2851 return T->isMemberDataPointerType();
2852 case UTT_IsEnum:
2853 return T->isEnumeralType();
Chandler Carruth28eeb382011-05-01 06:11:03 +00002854 case UTT_IsUnion:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002855 return T->isUnionType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002856 case UTT_IsClass:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002857 return T->isClassType() || T->isStructureType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002858 case UTT_IsFunction:
2859 return T->isFunctionType();
2860
2861 // Type trait expressions which correspond to the convenient composition
2862 // predicates in C++0x [meta.unary.comp].
2863 case UTT_IsReference:
2864 return T->isReferenceType();
2865 case UTT_IsArithmetic:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002866 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002867 case UTT_IsFundamental:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002868 return T->isFundamentalType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002869 case UTT_IsObject:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002870 return T->isObjectType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002871 case UTT_IsScalar:
John McCallf85e1932011-06-15 23:02:42 +00002872 // Note: semantic analysis depends on Objective-C lifetime types to be
2873 // considered scalar types. However, such types do not actually behave
2874 // like scalar types at run time (since they may require retain/release
2875 // operations), so we report them as non-scalar.
2876 if (T->isObjCLifetimeType()) {
2877 switch (T.getObjCLifetime()) {
2878 case Qualifiers::OCL_None:
2879 case Qualifiers::OCL_ExplicitNone:
2880 return true;
2881
2882 case Qualifiers::OCL_Strong:
2883 case Qualifiers::OCL_Weak:
2884 case Qualifiers::OCL_Autoreleasing:
2885 return false;
2886 }
2887 }
2888
Chandler Carruthcec0ced2011-05-01 09:29:55 +00002889 return T->isScalarType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002890 case UTT_IsCompound:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002891 return T->isCompoundType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002892 case UTT_IsMemberPointer:
2893 return T->isMemberPointerType();
2894
2895 // Type trait expressions which correspond to the type property predicates
2896 // in C++0x [meta.unary.prop].
2897 case UTT_IsConst:
2898 return T.isConstQualified();
2899 case UTT_IsVolatile:
2900 return T.isVolatileQualified();
2901 case UTT_IsTrivial:
John McCallf85e1932011-06-15 23:02:42 +00002902 return T.isTrivialType(Self.Context);
Sean Huntfeb375d2011-05-13 00:31:07 +00002903 case UTT_IsTriviallyCopyable:
John McCallf85e1932011-06-15 23:02:42 +00002904 return T.isTriviallyCopyableType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002905 case UTT_IsStandardLayout:
2906 return T->isStandardLayoutType();
2907 case UTT_IsPOD:
John McCallf85e1932011-06-15 23:02:42 +00002908 return T.isPODType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002909 case UTT_IsLiteral:
2910 return T->isLiteralType();
2911 case UTT_IsEmpty:
2912 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2913 return !RD->isUnion() && RD->isEmpty();
2914 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002915 case UTT_IsPolymorphic:
Chandler Carruth28eeb382011-05-01 06:11:03 +00002916 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2917 return RD->isPolymorphic();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002918 return false;
2919 case UTT_IsAbstract:
Chandler Carruth28eeb382011-05-01 06:11:03 +00002920 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2921 return RD->isAbstract();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002922 return false;
Douglas Gregor5e9392b2011-12-03 18:14:24 +00002923 case UTT_IsFinal:
2924 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2925 return RD->hasAttr<FinalAttr>();
2926 return false;
John Wiegley20c0da72011-04-27 23:09:49 +00002927 case UTT_IsSigned:
2928 return T->isSignedIntegerType();
John Wiegley20c0da72011-04-27 23:09:49 +00002929 case UTT_IsUnsigned:
2930 return T->isUnsignedIntegerType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002931
2932 // Type trait expressions which query classes regarding their construction,
2933 // destruction, and copying. Rather than being based directly on the
2934 // related type predicates in the standard, they are specified by both
2935 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
2936 // specifications.
2937 //
2938 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
2939 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Sean Hunt023df372011-05-09 18:22:59 +00002940 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002941 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2942 // If __is_pod (type) is true then the trait is true, else if type is
2943 // a cv class or union type (or array thereof) with a trivial default
2944 // constructor ([class.ctor]) then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002945 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002946 return true;
2947 if (const RecordType *RT =
2948 C.getBaseElementType(T)->getAs<RecordType>())
Sean Hunt023df372011-05-09 18:22:59 +00002949 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002950 return false;
2951 case UTT_HasTrivialCopy:
2952 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2953 // If __is_pod (type) is true or type is a reference type then
2954 // the trait is true, else if type is a cv class or union type
2955 // with a trivial copy constructor ([class.copy]) then the trait
2956 // is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00002957 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002958 return true;
2959 if (const RecordType *RT = T->getAs<RecordType>())
2960 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2961 return false;
2962 case UTT_HasTrivialAssign:
2963 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2964 // If type is const qualified or is a reference type then the
2965 // trait is false. Otherwise if __is_pod (type) is true then the
2966 // trait is true, else if type is a cv class or union type with
2967 // a trivial copy assignment ([class.copy]) then the trait is
2968 // true, else it is false.
2969 // Note: the const and reference restrictions are interesting,
2970 // given that const and reference members don't prevent a class
2971 // from having a trivial copy assignment operator (but do cause
2972 // errors if the copy assignment operator is actually used, q.v.
2973 // [class.copy]p12).
2974
2975 if (C.getBaseElementType(T).isConstQualified())
2976 return false;
John McCallf85e1932011-06-15 23:02:42 +00002977 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002978 return true;
2979 if (const RecordType *RT = T->getAs<RecordType>())
2980 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2981 return false;
2982 case UTT_HasTrivialDestructor:
2983 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2984 // If __is_pod (type) is true or type is a reference type
2985 // then the trait is true, else if type is a cv class or union
2986 // type (or array thereof) with a trivial destructor
2987 // ([class.dtor]) then the trait is true, else it is
2988 // false.
John McCallf85e1932011-06-15 23:02:42 +00002989 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002990 return true;
John McCallf85e1932011-06-15 23:02:42 +00002991
2992 // Objective-C++ ARC: autorelease types don't require destruction.
2993 if (T->isObjCLifetimeType() &&
2994 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
2995 return true;
2996
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002997 if (const RecordType *RT =
2998 C.getBaseElementType(T)->getAs<RecordType>())
2999 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
3000 return false;
3001 // TODO: Propagate nothrowness for implicitly declared special members.
3002 case UTT_HasNothrowAssign:
3003 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3004 // If type is const qualified or is a reference type then the
3005 // trait is false. Otherwise if __has_trivial_assign (type)
3006 // is true then the trait is true, else if type is a cv class
3007 // or union type with copy assignment operators that are known
3008 // not to throw an exception then the trait is true, else it is
3009 // false.
3010 if (C.getBaseElementType(T).isConstQualified())
3011 return false;
3012 if (T->isReferenceType())
3013 return false;
John McCallf85e1932011-06-15 23:02:42 +00003014 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
3015 return true;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003016 if (const RecordType *RT = T->getAs<RecordType>()) {
3017 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
3018 if (RD->hasTrivialCopyAssignment())
3019 return true;
3020
3021 bool FoundAssign = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003022 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00003023 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
3024 Sema::LookupOrdinaryName);
3025 if (Self.LookupQualifiedName(Res, RD)) {
Douglas Gregord41679d2011-10-12 15:40:49 +00003026 Res.suppressDiagnostics();
Sebastian Redlf8aca862010-09-14 23:40:14 +00003027 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
3028 Op != OpEnd; ++Op) {
Douglas Gregord41679d2011-10-12 15:40:49 +00003029 if (isa<FunctionTemplateDecl>(*Op))
3030 continue;
3031
Sebastian Redlf8aca862010-09-14 23:40:14 +00003032 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
3033 if (Operator->isCopyAssignmentOperator()) {
3034 FoundAssign = true;
3035 const FunctionProtoType *CPT
3036 = Operator->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00003037 if (CPT->getExceptionSpecType() == EST_Delayed)
3038 return false;
3039 if (!CPT->isNothrow(Self.Context))
3040 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003041 }
3042 }
3043 }
Douglas Gregord41679d2011-10-12 15:40:49 +00003044
Richard Smith7a614d82011-06-11 17:19:42 +00003045 return FoundAssign;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003046 }
3047 return false;
3048 case UTT_HasNothrowCopy:
3049 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3050 // If __has_trivial_copy (type) is true then the trait is true, else
3051 // if type is a cv class or union type with copy constructors that are
3052 // known not to throw an exception then the trait is true, else it is
3053 // false.
John McCallf85e1932011-06-15 23:02:42 +00003054 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003055 return true;
3056 if (const RecordType *RT = T->getAs<RecordType>()) {
3057 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3058 if (RD->hasTrivialCopyConstructor())
3059 return true;
3060
3061 bool FoundConstructor = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003062 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003063 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00003064 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003065 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00003066 // A template constructor is never a copy constructor.
3067 // FIXME: However, it may actually be selected at the actual overload
3068 // resolution point.
3069 if (isa<FunctionTemplateDecl>(*Con))
3070 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003071 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3072 if (Constructor->isCopyConstructor(FoundTQs)) {
3073 FoundConstructor = true;
3074 const FunctionProtoType *CPT
3075 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00003076 if (CPT->getExceptionSpecType() == EST_Delayed)
3077 return false;
Sebastian Redl60618fa2011-03-12 11:50:43 +00003078 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redl751025d2010-09-13 22:02:47 +00003079 // For now, we'll be conservative and assume that they can throw.
Richard Smith7a614d82011-06-11 17:19:42 +00003080 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
3081 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003082 }
3083 }
3084
Richard Smith7a614d82011-06-11 17:19:42 +00003085 return FoundConstructor;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003086 }
3087 return false;
3088 case UTT_HasNothrowConstructor:
3089 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3090 // If __has_trivial_constructor (type) is true then the trait is
3091 // true, else if type is a cv class or union type (or array
3092 // thereof) with a default constructor that is known not to
3093 // throw an exception then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00003094 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003095 return true;
3096 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
3097 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Hunt023df372011-05-09 18:22:59 +00003098 if (RD->hasTrivialDefaultConstructor())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003099 return true;
3100
Sebastian Redl751025d2010-09-13 22:02:47 +00003101 DeclContext::lookup_const_iterator Con, ConEnd;
3102 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
3103 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00003104 // FIXME: In C++0x, a constructor template can be a default constructor.
3105 if (isa<FunctionTemplateDecl>(*Con))
3106 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00003107 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3108 if (Constructor->isDefaultConstructor()) {
3109 const FunctionProtoType *CPT
3110 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smith7a614d82011-06-11 17:19:42 +00003111 if (CPT->getExceptionSpecType() == EST_Delayed)
3112 return false;
Sebastian Redl751025d2010-09-13 22:02:47 +00003113 // TODO: check whether evaluating default arguments can throw.
3114 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00003115 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
Sebastian Redl751025d2010-09-13 22:02:47 +00003116 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003117 }
3118 }
3119 return false;
3120 case UTT_HasVirtualDestructor:
3121 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3122 // If type is a class type with a virtual destructor ([class.dtor])
3123 // then the trait is true, else it is false.
3124 if (const RecordType *Record = T->getAs<RecordType>()) {
3125 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00003126 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003127 return Destructor->isVirtual();
3128 }
3129 return false;
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003130
3131 // These type trait expressions are modeled on the specifications for the
3132 // Embarcadero C++0x type trait functions:
3133 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3134 case UTT_IsCompleteType:
3135 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3136 // Returns True if and only if T is a complete type at the point of the
3137 // function call.
3138 return !T->isIncompleteType();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003139 }
Chandler Carruth83f563c2011-05-01 07:44:17 +00003140 llvm_unreachable("Type trait not covered by switch");
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003141}
3142
3143ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00003144 SourceLocation KWLoc,
3145 TypeSourceInfo *TSInfo,
3146 SourceLocation RParen) {
3147 QualType T = TSInfo->getType();
Chandler Carrutheb65a102011-04-30 10:07:32 +00003148 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
3149 return ExprError();
Sebastian Redl64b45f72009-01-05 20:52:13 +00003150
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003151 bool Value = false;
3152 if (!T->isDependentType())
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00003153 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003154
3155 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00003156 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00003157}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003158
Francois Pichet6ad6f282010-12-07 00:08:36 +00003159ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
3160 SourceLocation KWLoc,
3161 ParsedType LhsTy,
3162 ParsedType RhsTy,
3163 SourceLocation RParen) {
3164 TypeSourceInfo *LhsTSInfo;
3165 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3166 if (!LhsTSInfo)
3167 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3168
3169 TypeSourceInfo *RhsTSInfo;
3170 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3171 if (!RhsTSInfo)
3172 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3173
3174 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3175}
3176
3177static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3178 QualType LhsT, QualType RhsT,
3179 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003180 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3181 "Cannot evaluate traits of dependent types");
Francois Pichet6ad6f282010-12-07 00:08:36 +00003182
3183 switch(BTT) {
John McCalld89d30f2011-01-28 22:02:36 +00003184 case BTT_IsBaseOf: {
Francois Pichet6ad6f282010-12-07 00:08:36 +00003185 // C++0x [meta.rel]p2
John McCalld89d30f2011-01-28 22:02:36 +00003186 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet6ad6f282010-12-07 00:08:36 +00003187 // Base and Derived are not unions and name the same class type without
3188 // regard to cv-qualifiers.
Francois Pichet6ad6f282010-12-07 00:08:36 +00003189
John McCalld89d30f2011-01-28 22:02:36 +00003190 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3191 if (!lhsRecord) return false;
3192
3193 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3194 if (!rhsRecord) return false;
3195
3196 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3197 == (lhsRecord == rhsRecord));
3198
3199 if (lhsRecord == rhsRecord)
3200 return !lhsRecord->getDecl()->isUnion();
3201
3202 // C++0x [meta.rel]p2:
3203 // If Base and Derived are class types and are different types
3204 // (ignoring possible cv-qualifiers) then Derived shall be a
3205 // complete type.
3206 if (Self.RequireCompleteType(KeyLoc, RhsT,
3207 diag::err_incomplete_type_used_in_type_trait_expr))
3208 return false;
3209
3210 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3211 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3212 }
John Wiegley20c0da72011-04-27 23:09:49 +00003213 case BTT_IsSame:
3214 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichetf1872372010-12-08 22:35:30 +00003215 case BTT_TypeCompatible:
3216 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3217 RhsT.getUnqualifiedType());
John Wiegley20c0da72011-04-27 23:09:49 +00003218 case BTT_IsConvertible:
Douglas Gregor9f361132011-01-27 20:28:01 +00003219 case BTT_IsConvertibleTo: {
3220 // C++0x [meta.rel]p4:
3221 // Given the following function prototype:
3222 //
3223 // template <class T>
3224 // typename add_rvalue_reference<T>::type create();
3225 //
3226 // the predicate condition for a template specialization
3227 // is_convertible<From, To> shall be satisfied if and only if
3228 // the return expression in the following code would be
3229 // well-formed, including any implicit conversions to the return
3230 // type of the function:
3231 //
3232 // To test() {
3233 // return create<From>();
3234 // }
3235 //
3236 // Access checking is performed as if in a context unrelated to To and
3237 // From. Only the validity of the immediate context of the expression
3238 // of the return-statement (including conversions to the return type)
3239 // is considered.
3240 //
3241 // We model the initialization as a copy-initialization of a temporary
3242 // of the appropriate type, which for this expression is identical to the
3243 // return statement (since NRVO doesn't apply).
3244 if (LhsT->isObjectType() || LhsT->isFunctionType())
3245 LhsT = Self.Context.getRValueReferenceType(LhsT);
3246
3247 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorb608b982011-01-28 02:26:04 +00003248 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor9f361132011-01-27 20:28:01 +00003249 Expr::getValueKindForType(LhsT));
3250 Expr *FromPtr = &From;
3251 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3252 SourceLocation()));
3253
Eli Friedman3add9f02012-01-25 01:05:57 +00003254 // Perform the initialization in an unevaluated context within a SFINAE
3255 // trap at translation unit scope.
3256 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003257 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3258 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor9f361132011-01-27 20:28:01 +00003259 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003260 if (Init.Failed())
Douglas Gregor9f361132011-01-27 20:28:01 +00003261 return false;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003262
Douglas Gregor9f361132011-01-27 20:28:01 +00003263 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
3264 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3265 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003266 }
3267 llvm_unreachable("Unknown type trait or not implemented");
3268}
3269
3270ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3271 SourceLocation KWLoc,
3272 TypeSourceInfo *LhsTSInfo,
3273 TypeSourceInfo *RhsTSInfo,
3274 SourceLocation RParen) {
3275 QualType LhsT = LhsTSInfo->getType();
3276 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003277
John McCalld89d30f2011-01-28 22:02:36 +00003278 if (BTT == BTT_TypeCompatible) {
Francois Pichetf1872372010-12-08 22:35:30 +00003279 if (getLangOptions().CPlusPlus) {
3280 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3281 << SourceRange(KWLoc, RParen);
3282 return ExprError();
3283 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003284 }
3285
3286 bool Value = false;
3287 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3288 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3289
Francois Pichetf1872372010-12-08 22:35:30 +00003290 // Select trait result type.
3291 QualType ResultType;
3292 switch (BTT) {
Francois Pichetf1872372010-12-08 22:35:30 +00003293 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
John Wiegley20c0da72011-04-27 23:09:49 +00003294 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3295 case BTT_IsSame: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003296 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor9f361132011-01-27 20:28:01 +00003297 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003298 }
3299
Francois Pichet6ad6f282010-12-07 00:08:36 +00003300 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3301 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00003302 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00003303}
3304
John Wiegley21ff2e52011-04-28 00:16:57 +00003305ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3306 SourceLocation KWLoc,
3307 ParsedType Ty,
3308 Expr* DimExpr,
3309 SourceLocation RParen) {
3310 TypeSourceInfo *TSInfo;
3311 QualType T = GetTypeFromParser(Ty, &TSInfo);
3312 if (!TSInfo)
3313 TSInfo = Context.getTrivialTypeSourceInfo(T);
3314
3315 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3316}
3317
3318static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3319 QualType T, Expr *DimExpr,
3320 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003321 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley21ff2e52011-04-28 00:16:57 +00003322
3323 switch(ATT) {
3324 case ATT_ArrayRank:
3325 if (T->isArrayType()) {
3326 unsigned Dim = 0;
3327 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3328 ++Dim;
3329 T = AT->getElementType();
3330 }
3331 return Dim;
John Wiegley21ff2e52011-04-28 00:16:57 +00003332 }
John Wiegleycf566412011-04-28 02:06:46 +00003333 return 0;
3334
John Wiegley21ff2e52011-04-28 00:16:57 +00003335 case ATT_ArrayExtent: {
3336 llvm::APSInt Value;
3337 uint64_t Dim;
Richard Smith282e7e62012-02-04 09:53:13 +00003338 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
3339 Self.PDiag(diag::err_dimension_expr_not_constant_integer),
3340 false).isInvalid())
3341 return 0;
3342 if (Value.isSigned() && Value.isNegative()) {
3343 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer),
John Wiegleycf566412011-04-28 02:06:46 +00003344 DimExpr->getSourceRange();
Richard Smith282e7e62012-02-04 09:53:13 +00003345 return 0;
John Wiegleycf566412011-04-28 02:06:46 +00003346 }
Richard Smith282e7e62012-02-04 09:53:13 +00003347 Dim = Value.getLimitedValue();
John Wiegley21ff2e52011-04-28 00:16:57 +00003348
3349 if (T->isArrayType()) {
3350 unsigned D = 0;
3351 bool Matched = false;
3352 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3353 if (Dim == D) {
3354 Matched = true;
3355 break;
3356 }
3357 ++D;
3358 T = AT->getElementType();
3359 }
3360
John Wiegleycf566412011-04-28 02:06:46 +00003361 if (Matched && T->isArrayType()) {
3362 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3363 return CAT->getSize().getLimitedValue();
3364 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003365 }
John Wiegleycf566412011-04-28 02:06:46 +00003366 return 0;
John Wiegley21ff2e52011-04-28 00:16:57 +00003367 }
3368 }
3369 llvm_unreachable("Unknown type trait or not implemented");
3370}
3371
3372ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3373 SourceLocation KWLoc,
3374 TypeSourceInfo *TSInfo,
3375 Expr* DimExpr,
3376 SourceLocation RParen) {
3377 QualType T = TSInfo->getType();
John Wiegley21ff2e52011-04-28 00:16:57 +00003378
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003379 // FIXME: This should likely be tracked as an APInt to remove any host
3380 // assumptions about the width of size_t on the target.
Chandler Carruthd064c702011-05-01 08:41:10 +00003381 uint64_t Value = 0;
3382 if (!T->isDependentType())
3383 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3384
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003385 // While the specification for these traits from the Embarcadero C++
3386 // compiler's documentation says the return type is 'unsigned int', Clang
3387 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3388 // compiler, there is no difference. On several other platforms this is an
3389 // important distinction.
John Wiegley21ff2e52011-04-28 00:16:57 +00003390 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
Chandler Carruth06207f62011-05-01 07:49:26 +00003391 DimExpr, RParen,
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003392 Context.getSizeType()));
John Wiegley21ff2e52011-04-28 00:16:57 +00003393}
3394
John Wiegley55262202011-04-25 06:54:41 +00003395ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003396 SourceLocation KWLoc,
3397 Expr *Queried,
3398 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003399 // If error parsing the expression, ignore.
3400 if (!Queried)
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003401 return ExprError();
John Wiegley55262202011-04-25 06:54:41 +00003402
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003403 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegley55262202011-04-25 06:54:41 +00003404
3405 return move(Result);
3406}
3407
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003408static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3409 switch (ET) {
3410 case ET_IsLValueExpr: return E->isLValue();
3411 case ET_IsRValueExpr: return E->isRValue();
3412 }
3413 llvm_unreachable("Expression trait not covered by switch");
3414}
3415
John Wiegley55262202011-04-25 06:54:41 +00003416ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003417 SourceLocation KWLoc,
3418 Expr *Queried,
3419 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003420 if (Queried->isTypeDependent()) {
3421 // Delay type-checking for type-dependent expressions.
3422 } else if (Queried->getType()->isPlaceholderType()) {
3423 ExprResult PE = CheckPlaceholderExpr(Queried);
3424 if (PE.isInvalid()) return ExprError();
3425 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3426 }
3427
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003428 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf7ef0002011-05-01 08:48:19 +00003429
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003430 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3431 RParen, Context.BoolTy));
John Wiegley55262202011-04-25 06:54:41 +00003432}
3433
Richard Trieudd225092011-09-15 21:56:47 +00003434QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCallf89e55a2010-11-18 06:31:45 +00003435 ExprValueKind &VK,
3436 SourceLocation Loc,
3437 bool isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003438 assert(!LHS.get()->getType()->isPlaceholderType() &&
3439 !RHS.get()->getType()->isPlaceholderType() &&
John McCallea4aba02011-06-30 17:15:34 +00003440 "placeholders should have been weeded out by now");
3441
3442 // The LHS undergoes lvalue conversions if this is ->*.
3443 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003444 LHS = DefaultLvalueConversion(LHS.take());
3445 if (LHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003446 }
3447
3448 // The RHS always undergoes lvalue conversions.
Richard Trieudd225092011-09-15 21:56:47 +00003449 RHS = DefaultLvalueConversion(RHS.take());
3450 if (RHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003451
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003452 const char *OpSpelling = isIndirect ? "->*" : ".*";
3453 // C++ 5.5p2
3454 // The binary operator .* [p3: ->*] binds its second operand, which shall
3455 // be of type "pointer to member of T" (where T is a completely-defined
3456 // class type) [...]
Richard Trieudd225092011-09-15 21:56:47 +00003457 QualType RHSType = RHS.get()->getType();
3458 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00003459 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003460 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieudd225092011-09-15 21:56:47 +00003461 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003462 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00003463 }
Douglas Gregore7450f52009-03-24 19:52:54 +00003464
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003465 QualType Class(MemPtr->getClass(), 0);
3466
Douglas Gregor7d520ba2010-10-13 20:41:14 +00003467 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3468 // member pointer points must be completely-defined. However, there is no
3469 // reason for this semantic distinction, and the rule is not enforced by
3470 // other compilers. Therefore, we do not check this property, as it is
3471 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00003472
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003473 // C++ 5.5p2
3474 // [...] to its first operand, which shall be of class T or of a class of
3475 // which T is an unambiguous and accessible base class. [p3: a pointer to
3476 // such a class]
Richard Trieudd225092011-09-15 21:56:47 +00003477 QualType LHSType = LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003478 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003479 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
3480 LHSType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003481 else {
3482 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieudd225092011-09-15 21:56:47 +00003483 << OpSpelling << 1 << LHSType
Douglas Gregor849b2432010-03-31 17:46:05 +00003484 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003485 return QualType();
3486 }
3487 }
3488
Richard Trieudd225092011-09-15 21:56:47 +00003489 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00003490 // If we want to check the hierarchy, we need a complete type.
Richard Trieudd225092011-09-15 21:56:47 +00003491 if (RequireCompleteType(Loc, LHSType, PDiag(diag::err_bad_memptr_lhs)
Sebastian Redl17e1d352010-04-23 17:18:26 +00003492 << OpSpelling << (int)isIndirect)) {
3493 return QualType();
3494 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003495 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00003496 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00003497 // FIXME: Would it be useful to print full ambiguity paths, or is that
3498 // overkill?
Richard Trieudd225092011-09-15 21:56:47 +00003499 if (!IsDerivedFrom(LHSType, Class, Paths) ||
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003500 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3501 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieudd225092011-09-15 21:56:47 +00003502 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003503 return QualType();
3504 }
Eli Friedman3005efe2010-01-16 00:00:48 +00003505 // Cast LHS to type of use.
3506 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00003507 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00003508
John McCallf871d0c2010-08-07 06:22:56 +00003509 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003510 BuildBasePathArray(Paths, BasePath);
Richard Trieudd225092011-09-15 21:56:47 +00003511 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
3512 &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003513 }
3514
Richard Trieudd225092011-09-15 21:56:47 +00003515 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00003516 // Diagnose use of pointer-to-member type which when used as
3517 // the functional cast in a pointer-to-member expression.
3518 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3519 return QualType();
3520 }
John McCallf89e55a2010-11-18 06:31:45 +00003521
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003522 // C++ 5.5p2
3523 // The result is an object or a function of the type specified by the
3524 // second operand.
3525 // The cv qualifiers are the union of those in the pointer and the left side,
3526 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003527 QualType Result = MemPtr->getPointeeType();
Richard Trieudd225092011-09-15 21:56:47 +00003528 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00003529
Douglas Gregor6b4df912011-01-26 16:40:18 +00003530 // C++0x [expr.mptr.oper]p6:
3531 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003532 // ill-formed if the second operand is a pointer to member function with
3533 // ref-qualifier &. In a ->* expression or in a .* expression whose object
3534 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor6b4df912011-01-26 16:40:18 +00003535 // is a pointer to member function with ref-qualifier &&.
3536 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3537 switch (Proto->getRefQualifier()) {
3538 case RQ_None:
3539 // Do nothing
3540 break;
3541
3542 case RQ_LValue:
Richard Trieudd225092011-09-15 21:56:47 +00003543 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003544 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003545 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003546 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003547
Douglas Gregor6b4df912011-01-26 16:40:18 +00003548 case RQ_RValue:
Richard Trieudd225092011-09-15 21:56:47 +00003549 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003550 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003551 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003552 break;
3553 }
3554 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003555
John McCallf89e55a2010-11-18 06:31:45 +00003556 // C++ [expr.mptr.oper]p6:
3557 // The result of a .* expression whose second operand is a pointer
3558 // to a data member is of the same value category as its
3559 // first operand. The result of a .* expression whose second
3560 // operand is a pointer to a member function is a prvalue. The
3561 // result of an ->* expression is an lvalue if its second operand
3562 // is a pointer to data member and a prvalue otherwise.
John McCall864c0412011-04-26 20:42:42 +00003563 if (Result->isFunctionType()) {
John McCallf89e55a2010-11-18 06:31:45 +00003564 VK = VK_RValue;
John McCall864c0412011-04-26 20:42:42 +00003565 return Context.BoundMemberTy;
3566 } else if (isIndirect) {
John McCallf89e55a2010-11-18 06:31:45 +00003567 VK = VK_LValue;
John McCall864c0412011-04-26 20:42:42 +00003568 } else {
Richard Trieudd225092011-09-15 21:56:47 +00003569 VK = LHS.get()->getValueKind();
John McCall864c0412011-04-26 20:42:42 +00003570 }
John McCallf89e55a2010-11-18 06:31:45 +00003571
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003572 return Result;
3573}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003574
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003575/// \brief Try to convert a type to another according to C++0x 5.16p3.
3576///
3577/// This is part of the parameter validation for the ? operator. If either
3578/// value operand is a class type, the two operands are attempted to be
3579/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003580/// It returns true if the program is ill-formed and has already been diagnosed
3581/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003582static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3583 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00003584 bool &HaveConversion,
3585 QualType &ToType) {
3586 HaveConversion = false;
3587 ToType = To->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003588
3589 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003590 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003591 // C++0x 5.16p3
3592 // The process for determining whether an operand expression E1 of type T1
3593 // can be converted to match an operand expression E2 of type T2 is defined
3594 // as follows:
3595 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00003596 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003597 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003598 // E1 can be converted to match E2 if E1 can be implicitly converted to
3599 // type "lvalue reference to T2", subject to the constraint that in the
3600 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003601 QualType T = Self.Context.getLValueReferenceType(ToType);
3602 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003603
Douglas Gregorb70cf442010-03-26 20:14:36 +00003604 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3605 if (InitSeq.isDirectReferenceBinding()) {
3606 ToType = T;
3607 HaveConversion = true;
3608 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003609 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003610
Douglas Gregorb70cf442010-03-26 20:14:36 +00003611 if (InitSeq.isAmbiguous())
3612 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003613 }
John McCallb1bdc622010-02-25 01:37:24 +00003614
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003615 // -- If E2 is an rvalue, or if the conversion above cannot be done:
3616 // -- if E1 and E2 have class type, and the underlying class types are
3617 // the same or one is a base class of the other:
3618 QualType FTy = From->getType();
3619 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003620 const RecordType *FRec = FTy->getAs<RecordType>();
3621 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003622 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003623 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003624 if (FRec && TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003625 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003626 // E1 can be converted to match E2 if the class of T2 is the
3627 // same type as, or a base class of, the class of T1, and
3628 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00003629 if (FRec == TRec || FDerivedFromT) {
3630 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003631 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3632 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003633 if (InitSeq) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003634 HaveConversion = true;
3635 return false;
3636 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003637
Douglas Gregorb70cf442010-03-26 20:14:36 +00003638 if (InitSeq.isAmbiguous())
3639 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003640 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003641 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003642
Douglas Gregorb70cf442010-03-26 20:14:36 +00003643 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003644 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003645
Douglas Gregorb70cf442010-03-26 20:14:36 +00003646 // -- Otherwise: E1 can be converted to match E2 if E1 can be
3647 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003648 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003649 // an rvalue).
3650 //
3651 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3652 // to the array-to-pointer or function-to-pointer conversions.
3653 if (!TTy->getAs<TagType>())
3654 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003655
Douglas Gregorb70cf442010-03-26 20:14:36 +00003656 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3657 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003658 HaveConversion = !InitSeq.Failed();
Douglas Gregorb70cf442010-03-26 20:14:36 +00003659 ToType = TTy;
3660 if (InitSeq.isAmbiguous())
3661 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3662
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003663 return false;
3664}
3665
3666/// \brief Try to find a common type for two according to C++0x 5.16p5.
3667///
3668/// This is part of the parameter validation for the ? operator. If either
3669/// value operand is a class type, overload resolution is used to find a
3670/// conversion to a common type.
John Wiegley429bb272011-04-08 18:41:53 +00003671static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth82214a82011-02-18 23:54:50 +00003672 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00003673 Expr *Args[2] = { LHS.get(), RHS.get() };
Chandler Carruth82214a82011-02-18 23:54:50 +00003674 OverloadCandidateSet CandidateSet(QuestionLoc);
3675 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3676 CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003677
3678 OverloadCandidateSet::iterator Best;
Chandler Carruth82214a82011-02-18 23:54:50 +00003679 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley429bb272011-04-08 18:41:53 +00003680 case OR_Success: {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003681 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley429bb272011-04-08 18:41:53 +00003682 ExprResult LHSRes =
3683 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3684 Best->Conversions[0], Sema::AA_Converting);
3685 if (LHSRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003686 break;
John Wiegley429bb272011-04-08 18:41:53 +00003687 LHS = move(LHSRes);
3688
3689 ExprResult RHSRes =
3690 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3691 Best->Conversions[1], Sema::AA_Converting);
3692 if (RHSRes.isInvalid())
3693 break;
3694 RHS = move(RHSRes);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003695 if (Best->Function)
Eli Friedman5f2987c2012-02-02 03:46:19 +00003696 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003697 return false;
John Wiegley429bb272011-04-08 18:41:53 +00003698 }
3699
Douglas Gregor20093b42009-12-09 23:02:17 +00003700 case OR_No_Viable_Function:
Chandler Carruth82214a82011-02-18 23:54:50 +00003701
3702 // Emit a better diagnostic if one of the expressions is a null pointer
3703 // constant and the other is a pointer type. In this case, the user most
3704 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00003705 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00003706 return true;
3707
3708 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003709 << LHS.get()->getType() << RHS.get()->getType()
3710 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003711 return true;
3712
Douglas Gregor20093b42009-12-09 23:02:17 +00003713 case OR_Ambiguous:
Chandler Carruth82214a82011-02-18 23:54:50 +00003714 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley429bb272011-04-08 18:41:53 +00003715 << LHS.get()->getType() << RHS.get()->getType()
3716 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00003717 // FIXME: Print the possible common types by printing the return types of
3718 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003719 break;
3720
Douglas Gregor20093b42009-12-09 23:02:17 +00003721 case OR_Deleted:
David Blaikieb219cfc2011-09-23 05:06:16 +00003722 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003723 }
3724 return true;
3725}
3726
Sebastian Redl76458502009-04-17 16:30:52 +00003727/// \brief Perform an "extended" implicit conversion as returned by
3728/// TryClassUnification.
John Wiegley429bb272011-04-08 18:41:53 +00003729static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003730 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley429bb272011-04-08 18:41:53 +00003731 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003732 SourceLocation());
John Wiegley429bb272011-04-08 18:41:53 +00003733 Expr *Arg = E.take();
3734 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
3735 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00003736 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00003737 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003738
John Wiegley429bb272011-04-08 18:41:53 +00003739 E = Result;
Sebastian Redl76458502009-04-17 16:30:52 +00003740 return false;
3741}
3742
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003743/// \brief Check the operands of ?: under C++ semantics.
3744///
3745/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
3746/// extension. In this case, LHS == Cond. (But they're not aliases.)
John Wiegley429bb272011-04-08 18:41:53 +00003747QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCall56ca35d2011-02-17 10:25:35 +00003748 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003749 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00003750 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
3751 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003752
3753 // C++0x 5.16p1
3754 // The first expression is contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00003755 if (!Cond.get()->isTypeDependent()) {
3756 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
3757 if (CondRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003758 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003759 Cond = move(CondRes);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003760 }
3761
John McCallf89e55a2010-11-18 06:31:45 +00003762 // Assume r-value.
3763 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00003764 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00003765
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003766 // Either of the arguments dependent?
John Wiegley429bb272011-04-08 18:41:53 +00003767 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003768 return Context.DependentTy;
3769
3770 // C++0x 5.16p2
3771 // If either the second or the third operand has type (cv) void, ...
John Wiegley429bb272011-04-08 18:41:53 +00003772 QualType LTy = LHS.get()->getType();
3773 QualType RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003774 bool LVoid = LTy->isVoidType();
3775 bool RVoid = RTy->isVoidType();
3776 if (LVoid || RVoid) {
3777 // ... then the [l2r] conversions are performed on the second and third
3778 // operands ...
John Wiegley429bb272011-04-08 18:41:53 +00003779 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3780 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3781 if (LHS.isInvalid() || RHS.isInvalid())
3782 return QualType();
3783 LTy = LHS.get()->getType();
3784 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003785
3786 // ... and one of the following shall hold:
3787 // -- The second or the third operand (but not both) is a throw-
3788 // expression; the result is of the type of the other and is an rvalue.
John Wiegley429bb272011-04-08 18:41:53 +00003789 bool LThrow = isa<CXXThrowExpr>(LHS.get());
3790 bool RThrow = isa<CXXThrowExpr>(RHS.get());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003791 if (LThrow && !RThrow)
3792 return RTy;
3793 if (RThrow && !LThrow)
3794 return LTy;
3795
3796 // -- Both the second and third operands have type void; the result is of
3797 // type void and is an rvalue.
3798 if (LVoid && RVoid)
3799 return Context.VoidTy;
3800
3801 // Neither holds, error.
3802 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3803 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley429bb272011-04-08 18:41:53 +00003804 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003805 return QualType();
3806 }
3807
3808 // Neither is void.
3809
3810 // C++0x 5.16p3
3811 // Otherwise, if the second and third operand have different types, and
3812 // either has (cv) class type, and attempt is made to convert each of those
3813 // operands to the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003814 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003815 (LTy->isRecordType() || RTy->isRecordType())) {
3816 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3817 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003818 QualType L2RType, R2LType;
3819 bool HaveL2R, HaveR2L;
John Wiegley429bb272011-04-08 18:41:53 +00003820 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003821 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003822 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003823 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003824
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003825 // If both can be converted, [...] the program is ill-formed.
3826 if (HaveL2R && HaveR2L) {
3827 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley429bb272011-04-08 18:41:53 +00003828 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003829 return QualType();
3830 }
3831
3832 // If exactly one conversion is possible, that conversion is applied to
3833 // the chosen operand and the converted operands are used in place of the
3834 // original operands for the remainder of this section.
3835 if (HaveL2R) {
John Wiegley429bb272011-04-08 18:41:53 +00003836 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003837 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003838 LTy = LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003839 } else if (HaveR2L) {
John Wiegley429bb272011-04-08 18:41:53 +00003840 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003841 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003842 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003843 }
3844 }
3845
3846 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00003847 // If the second and third operands are glvalues of the same value
3848 // category and have the same type, the result is of that type and
3849 // value category and it is a bit-field if the second or the third
3850 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00003851 // We only extend this to bitfields, not to the crazy other kinds of
3852 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003853 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00003854 if (Same &&
John Wiegley429bb272011-04-08 18:41:53 +00003855 LHS.get()->isGLValue() &&
3856 LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
3857 LHS.get()->isOrdinaryOrBitFieldObject() &&
3858 RHS.get()->isOrdinaryOrBitFieldObject()) {
3859 VK = LHS.get()->getValueKind();
3860 if (LHS.get()->getObjectKind() == OK_BitField ||
3861 RHS.get()->getObjectKind() == OK_BitField)
John McCall09431682010-11-18 19:01:18 +00003862 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00003863 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00003864 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003865
3866 // C++0x 5.16p5
3867 // Otherwise, the result is an rvalue. If the second and third operands
3868 // do not have the same type, and either has (cv) class type, ...
3869 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3870 // ... overload resolution is used to determine the conversions (if any)
3871 // to be applied to the operands. If the overload resolution fails, the
3872 // program is ill-formed.
3873 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3874 return QualType();
3875 }
3876
3877 // C++0x 5.16p6
3878 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3879 // conversions are performed on the second and third operands.
John Wiegley429bb272011-04-08 18:41:53 +00003880 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3881 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3882 if (LHS.isInvalid() || RHS.isInvalid())
3883 return QualType();
3884 LTy = LHS.get()->getType();
3885 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003886
3887 // After those conversions, one of the following shall hold:
3888 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00003889 // is of that type. If the operands have class type, the result
3890 // is a prvalue temporary of the result type, which is
3891 // copy-initialized from either the second operand or the third
3892 // operand depending on the value of the first operand.
3893 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3894 if (LTy->isRecordType()) {
3895 // The operands have class type. Make a temporary copy.
3896 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003897 ExprResult LHSCopy = PerformCopyInitialization(Entity,
3898 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00003899 LHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00003900 if (LHSCopy.isInvalid())
3901 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003902
3903 ExprResult RHSCopy = PerformCopyInitialization(Entity,
3904 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00003905 RHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00003906 if (RHSCopy.isInvalid())
3907 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003908
John Wiegley429bb272011-04-08 18:41:53 +00003909 LHS = LHSCopy;
3910 RHS = RHSCopy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003911 }
3912
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003913 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00003914 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003915
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003916 // Extension: conditional operator involving vector types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003917 if (LTy->isVectorType() || RTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00003918 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00003919
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003920 // -- The second and third operands have arithmetic or enumeration type;
3921 // the usual arithmetic conversions are performed to bring them to a
3922 // common type, and the result is of that type.
3923 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3924 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00003925 if (LHS.isInvalid() || RHS.isInvalid())
3926 return QualType();
3927 return LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003928 }
3929
3930 // -- The second and third operands have pointer type, or one has pointer
3931 // type and the other is a null pointer constant; pointer conversions
3932 // and qualification conversions are performed to bring them to their
3933 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00003934 // -- The second and third operands have pointer to member type, or one has
3935 // pointer to member type and the other is a null pointer constant;
3936 // pointer to member conversions and qualification conversions are
3937 // performed to bring them to a common type, whose cv-qualification
3938 // shall match the cv-qualification of either the second or the third
3939 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003940 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003941 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003942 isSFINAEContext()? 0 : &NonStandardCompositeType);
3943 if (!Composite.isNull()) {
3944 if (NonStandardCompositeType)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003945 Diag(QuestionLoc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003946 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3947 << LTy << RTy << Composite
John Wiegley429bb272011-04-08 18:41:53 +00003948 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003949
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003950 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003951 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003952
Douglas Gregor1927b1f2010-04-01 22:47:07 +00003953 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00003954 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3955 if (!Composite.isNull())
3956 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003957
Chandler Carruth7ef93242011-02-19 00:13:59 +00003958 // Check if we are using a null with a non-pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00003959 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth7ef93242011-02-19 00:13:59 +00003960 return QualType();
3961
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003962 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003963 << LHS.get()->getType() << RHS.get()->getType()
3964 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003965 return QualType();
3966}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003967
3968/// \brief Find a merged pointer type and convert the two expressions to it.
3969///
Douglas Gregor20b3e992009-08-24 17:42:35 +00003970/// This finds the composite pointer type (or member pointer type) for @p E1
3971/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3972/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003973/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003974///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003975/// \param Loc The location of the operator requiring these two expressions to
3976/// be converted to the composite pointer type.
3977///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003978/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3979/// a non-standard (but still sane) composite type to which both expressions
3980/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3981/// will be set true.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003982QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00003983 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00003984 bool *NonStandardCompositeType) {
3985 if (NonStandardCompositeType)
3986 *NonStandardCompositeType = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003987
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003988 assert(getLangOptions().CPlusPlus && "This function assumes C++");
3989 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003990
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00003991 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3992 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00003993 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00003994
3995 // C++0x 5.9p2
3996 // Pointer conversions and qualification conversions are performed on
3997 // pointer operands to bring them to their composite pointer type. If
3998 // one operand is a null pointer constant, the composite pointer type is
3999 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00004000 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004001 if (T2->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00004002 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004003 else
John Wiegley429bb272011-04-08 18:41:53 +00004004 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004005 return T2;
4006 }
Douglas Gregorce940492009-09-25 04:25:58 +00004007 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004008 if (T1->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00004009 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004010 else
John Wiegley429bb272011-04-08 18:41:53 +00004011 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004012 return T1;
4013 }
Mike Stump1eb44332009-09-09 15:08:12 +00004014
Douglas Gregor20b3e992009-08-24 17:42:35 +00004015 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00004016 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
4017 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004018 return QualType();
4019
4020 // Otherwise, of one of the operands has type "pointer to cv1 void," then
4021 // the other has type "pointer to cv2 T" and the composite pointer type is
4022 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
4023 // Otherwise, the composite pointer type is a pointer type similar to the
4024 // type of one of the operands, with a cv-qualification signature that is
4025 // the union of the cv-qualification signatures of the operand types.
4026 // In practice, the first part here is redundant; it's subsumed by the second.
4027 // What we do here is, we build the two possible composite types, and try the
4028 // conversions in both directions. If only one works, or if the two composite
4029 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00004030 // FIXME: extended qualifiers?
Chris Lattner5f9e2722011-07-23 10:55:15 +00004031 typedef SmallVector<unsigned, 4> QualifierVector;
Sebastian Redla439e6f2009-11-16 21:03:45 +00004032 QualifierVector QualifierUnion;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004033 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
Sebastian Redla439e6f2009-11-16 21:03:45 +00004034 ContainingClassVector;
4035 ContainingClassVector MemberOfClass;
4036 QualType Composite1 = Context.getCanonicalType(T1),
4037 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004038 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00004039 do {
4040 const PointerType *Ptr1, *Ptr2;
4041 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
4042 (Ptr2 = Composite2->getAs<PointerType>())) {
4043 Composite1 = Ptr1->getPointeeType();
4044 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004045
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004046 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004047 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004048 if (NonStandardCompositeType &&
4049 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4050 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004051
Douglas Gregor20b3e992009-08-24 17:42:35 +00004052 QualifierUnion.push_back(
4053 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4054 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
4055 continue;
4056 }
Mike Stump1eb44332009-09-09 15:08:12 +00004057
Douglas Gregor20b3e992009-08-24 17:42:35 +00004058 const MemberPointerType *MemPtr1, *MemPtr2;
4059 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
4060 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
4061 Composite1 = MemPtr1->getPointeeType();
4062 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004063
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004064 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004065 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004066 if (NonStandardCompositeType &&
4067 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4068 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004069
Douglas Gregor20b3e992009-08-24 17:42:35 +00004070 QualifierUnion.push_back(
4071 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4072 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
4073 MemPtr2->getClass()));
4074 continue;
4075 }
Mike Stump1eb44332009-09-09 15:08:12 +00004076
Douglas Gregor20b3e992009-08-24 17:42:35 +00004077 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00004078
Douglas Gregor20b3e992009-08-24 17:42:35 +00004079 // Cannot unwrap any more types.
4080 break;
4081 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00004082
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004083 if (NeedConstBefore && NonStandardCompositeType) {
4084 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004085 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004086 // requirements of C++ [conv.qual]p4 bullet 3.
4087 for (unsigned I = 0; I != NeedConstBefore; ++I) {
4088 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
4089 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
4090 *NonStandardCompositeType = true;
4091 }
4092 }
4093 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004094
Douglas Gregor20b3e992009-08-24 17:42:35 +00004095 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00004096 ContainingClassVector::reverse_iterator MOC
4097 = MemberOfClass.rbegin();
4098 for (QualifierVector::reverse_iterator
4099 I = QualifierUnion.rbegin(),
4100 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00004101 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00004102 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004103 if (MOC->first && MOC->second) {
4104 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00004105 Composite1 = Context.getMemberPointerType(
4106 Context.getQualifiedType(Composite1, Quals),
4107 MOC->first);
4108 Composite2 = Context.getMemberPointerType(
4109 Context.getQualifiedType(Composite2, Quals),
4110 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004111 } else {
4112 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00004113 Composite1
4114 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
4115 Composite2
4116 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00004117 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004118 }
4119
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004120 // Try to convert to the first composite pointer type.
4121 InitializedEntity Entity1
4122 = InitializedEntity::InitializeTemporary(Composite1);
4123 InitializationKind Kind
4124 = InitializationKind::CreateCopy(Loc, SourceLocation());
4125 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
4126 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00004127
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004128 if (E1ToC1 && E2ToC1) {
4129 // Conversion to Composite1 is viable.
4130 if (!Context.hasSameType(Composite1, Composite2)) {
4131 // Composite2 is a different type from Composite1. Check whether
4132 // Composite2 is also viable.
4133 InitializedEntity Entity2
4134 = InitializedEntity::InitializeTemporary(Composite2);
4135 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4136 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4137 if (E1ToC2 && E2ToC2) {
4138 // Both Composite1 and Composite2 are viable and are different;
4139 // this is an ambiguity.
4140 return QualType();
4141 }
4142 }
4143
4144 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004145 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004146 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004147 if (E1Result.isInvalid())
4148 return QualType();
4149 E1 = E1Result.takeAs<Expr>();
4150
4151 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004152 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004153 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004154 if (E2Result.isInvalid())
4155 return QualType();
4156 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004157
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004158 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004159 }
4160
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004161 // Check whether Composite2 is viable.
4162 InitializedEntity Entity2
4163 = InitializedEntity::InitializeTemporary(Composite2);
4164 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4165 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4166 if (!E1ToC2 || !E2ToC2)
4167 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004168
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004169 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004170 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004171 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004172 if (E1Result.isInvalid())
4173 return QualType();
4174 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004175
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004176 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004177 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004178 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004179 if (E2Result.isInvalid())
4180 return QualType();
4181 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004182
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004183 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004184}
Anders Carlsson165a0a02009-05-17 18:41:29 +00004185
John McCall60d7b3a2010-08-24 06:29:42 +00004186ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00004187 if (!E)
4188 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004189
John McCallf85e1932011-06-15 23:02:42 +00004190 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4191
4192 // If the result is a glvalue, we shouldn't bind it.
4193 if (!E->isRValue())
Anders Carlsson089c2602009-08-15 23:41:35 +00004194 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004195
John McCallf85e1932011-06-15 23:02:42 +00004196 // In ARC, calls that return a retainable type can return retained,
4197 // in which case we have to insert a consuming cast.
4198 if (getLangOptions().ObjCAutoRefCount &&
4199 E->getType()->isObjCRetainableType()) {
4200
4201 bool ReturnsRetained;
4202
4203 // For actual calls, we compute this by examining the type of the
4204 // called value.
4205 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4206 Expr *Callee = Call->getCallee()->IgnoreParens();
4207 QualType T = Callee->getType();
4208
4209 if (T == Context.BoundMemberTy) {
4210 // Handle pointer-to-members.
4211 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4212 T = BinOp->getRHS()->getType();
4213 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4214 T = Mem->getMemberDecl()->getType();
4215 }
4216
4217 if (const PointerType *Ptr = T->getAs<PointerType>())
4218 T = Ptr->getPointeeType();
4219 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4220 T = Ptr->getPointeeType();
4221 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4222 T = MemPtr->getPointeeType();
4223
4224 const FunctionType *FTy = T->getAs<FunctionType>();
4225 assert(FTy && "call to value not of function type?");
4226 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4227
4228 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4229 // type always produce a +1 object.
4230 } else if (isa<StmtExpr>(E)) {
4231 ReturnsRetained = true;
4232
4233 // For message sends and property references, we try to find an
4234 // actual method. FIXME: we should infer retention by selector in
4235 // cases where we don't have an actual method.
4236 } else {
John McCallfc4b1912011-08-03 07:02:44 +00004237 ObjCMethodDecl *D = 0;
John McCallf85e1932011-06-15 23:02:42 +00004238 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4239 D = Send->getMethodDecl();
John McCallf85e1932011-06-15 23:02:42 +00004240 }
4241
4242 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCallfc4b1912011-08-03 07:02:44 +00004243
4244 // Don't do reclaims on performSelector calls; despite their
4245 // return type, the invoked method doesn't necessarily actually
4246 // return an object.
4247 if (!ReturnsRetained &&
4248 D && D->getMethodFamily() == OMF_performSelector)
4249 return Owned(E);
John McCallf85e1932011-06-15 23:02:42 +00004250 }
4251
John McCall567c5862011-11-14 19:53:16 +00004252 // Don't reclaim an object of Class type.
4253 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4254 return Owned(E);
4255
John McCall7e5e5f42011-07-07 06:58:02 +00004256 ExprNeedsCleanups = true;
4257
John McCall33e56f32011-09-10 06:18:15 +00004258 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4259 : CK_ARCReclaimReturnedObject);
John McCall7e5e5f42011-07-07 06:58:02 +00004260 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4261 VK_RValue));
John McCallf85e1932011-06-15 23:02:42 +00004262 }
4263
4264 if (!getLangOptions().CPlusPlus)
4265 return Owned(E);
Douglas Gregor51326552009-12-24 18:51:59 +00004266
Peter Collingbourneb4ab8432012-01-26 03:33:51 +00004267 // Search for the base element type (cf. ASTContext::getBaseElementType) with
4268 // a fast path for the common case that the type is directly a RecordType.
4269 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
4270 const RecordType *RT = 0;
4271 while (!RT) {
4272 switch (T->getTypeClass()) {
4273 case Type::Record:
4274 RT = cast<RecordType>(T);
4275 break;
4276 case Type::ConstantArray:
4277 case Type::IncompleteArray:
4278 case Type::VariableArray:
4279 case Type::DependentSizedArray:
4280 T = cast<ArrayType>(T)->getElementType().getTypePtr();
4281 break;
4282 default:
4283 return Owned(E);
4284 }
4285 }
Mike Stump1eb44332009-09-09 15:08:12 +00004286
John McCall86ff3082010-02-04 22:26:26 +00004287 // That should be enough to guarantee that this type is complete.
4288 // If it has a trivial destructor, we can avoid the extra copy.
Jeffrey Yasskinb7ee2e52011-01-27 19:17:54 +00004289 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall507384f2010-08-12 02:40:37 +00004290 if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
John McCall86ff3082010-02-04 22:26:26 +00004291 return Owned(E);
4292
John McCallf85e1932011-06-15 23:02:42 +00004293 CXXDestructorDecl *Destructor = LookupDestructor(RD);
4294
4295 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
4296 if (Destructor) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00004297 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00004298 CheckDestructorAccess(E->getExprLoc(), Destructor,
4299 PDiag(diag::err_access_dtor_temp)
4300 << E->getType());
John McCallf85e1932011-06-15 23:02:42 +00004301
John McCall80ee6e82011-11-10 05:35:25 +00004302 // We need a cleanup, but we don't need to remember the temporary.
John McCallf85e1932011-06-15 23:02:42 +00004303 ExprNeedsCleanups = true;
John McCallc91cc662010-04-07 00:41:46 +00004304 }
Anders Carlssondef11992009-05-30 20:36:53 +00004305 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
4306}
4307
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004308ExprResult
John McCall4765fa02010-12-06 08:20:24 +00004309Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004310 if (SubExpr.isInvalid())
4311 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004312
John McCall4765fa02010-12-06 08:20:24 +00004313 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00004314}
4315
John McCall80ee6e82011-11-10 05:35:25 +00004316Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
4317 assert(SubExpr && "sub expression can't be null!");
4318
Eli Friedmand2cce132012-02-02 23:15:15 +00004319 CleanupVarDeclMarking();
4320
John McCall80ee6e82011-11-10 05:35:25 +00004321 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
4322 assert(ExprCleanupObjects.size() >= FirstCleanup);
4323 assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
4324 if (!ExprNeedsCleanups)
4325 return SubExpr;
4326
4327 ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
4328 = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
4329 ExprCleanupObjects.size() - FirstCleanup);
4330
4331 Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
4332 DiscardCleanupsInEvaluationContext();
4333
4334 return E;
4335}
4336
John McCall4765fa02010-12-06 08:20:24 +00004337Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004338 assert(SubStmt && "sub statement can't be null!");
4339
Eli Friedmand2cce132012-02-02 23:15:15 +00004340 CleanupVarDeclMarking();
4341
John McCallf85e1932011-06-15 23:02:42 +00004342 if (!ExprNeedsCleanups)
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004343 return SubStmt;
4344
4345 // FIXME: In order to attach the temporaries, wrap the statement into
4346 // a StmtExpr; currently this is only used for asm statements.
4347 // This is hacky, either create a new CXXStmtWithTemporaries statement or
4348 // a new AsmStmtWithTemporaries.
4349 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
4350 SourceLocation(),
4351 SourceLocation());
4352 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
4353 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00004354 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004355}
4356
John McCall60d7b3a2010-08-24 06:29:42 +00004357ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004358Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00004359 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00004360 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004361 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004362 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004363 if (Result.isInvalid()) return ExprError();
4364 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004365
John McCall3c3b7f92011-10-25 17:37:35 +00004366 Result = CheckPlaceholderExpr(Base);
4367 if (Result.isInvalid()) return ExprError();
4368 Base = Result.take();
4369
John McCall9ae2f072010-08-23 23:25:46 +00004370 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004371 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004372 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00004373 // If we have a pointer to a dependent type and are using the -> operator,
4374 // the object type is the type that the pointer points to. We might still
4375 // have enough information about that type to do something useful.
4376 if (OpKind == tok::arrow)
4377 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4378 BaseType = Ptr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004379
John McCallb3d87482010-08-24 05:47:05 +00004380 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00004381 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004382 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004383 }
Mike Stump1eb44332009-09-09 15:08:12 +00004384
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004385 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00004386 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004387 // returned, with the original second operand.
4388 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00004389 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00004390 llvm::SmallPtrSet<CanQualType,8> CTypes;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004391 SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00004392 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004393
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004394 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00004395 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
4396 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004397 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00004398 Base = Result.get();
4399 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00004400 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00004401 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00004402 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00004403 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004404 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00004405 for (unsigned i = 0; i < Locations.size(); i++)
4406 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004407 return ExprError();
4408 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004409 }
Mike Stump1eb44332009-09-09 15:08:12 +00004410
Douglas Gregor1d7049a2012-01-12 16:11:24 +00004411 if (BaseType->isPointerType() || BaseType->isObjCObjectPointerType())
Douglas Gregor31658df2009-11-20 19:58:21 +00004412 BaseType = BaseType->getPointeeType();
4413 }
Mike Stump1eb44332009-09-09 15:08:12 +00004414
Douglas Gregor1d7049a2012-01-12 16:11:24 +00004415 // Objective-C properties allow "." access on Objective-C pointer types,
4416 // so adjust the base type to the object type itself.
4417 if (BaseType->isObjCObjectPointerType())
4418 BaseType = BaseType->getPointeeType();
4419
4420 // C++ [basic.lookup.classref]p2:
4421 // [...] If the type of the object expression is of pointer to scalar
4422 // type, the unqualified-id is looked up in the context of the complete
4423 // postfix-expression.
4424 //
4425 // This also indicates that we could be parsing a pseudo-destructor-name.
4426 // Note that Objective-C class and object types can be pseudo-destructor
4427 // expressions or normal member (ivar or property) access expressions.
4428 if (BaseType->isObjCObjectOrInterfaceType()) {
4429 MayBePseudoDestructor = true;
4430 } else if (!BaseType->isRecordType()) {
John McCallb3d87482010-08-24 05:47:05 +00004431 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004432 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004433 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00004434 }
Mike Stump1eb44332009-09-09 15:08:12 +00004435
Douglas Gregor03c57052009-11-17 05:17:33 +00004436 // The object type must be complete (or dependent).
4437 if (!BaseType->isDependentType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004438 RequireCompleteType(OpLoc, BaseType,
Douglas Gregor03c57052009-11-17 05:17:33 +00004439 PDiag(diag::err_incomplete_member_access)))
4440 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004441
Douglas Gregorc68afe22009-09-03 21:38:09 +00004442 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004443 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00004444 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00004445 // type C (or of pointer to a class type C), the unqualified-id is looked
4446 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00004447 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00004448 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004449}
4450
John McCall60d7b3a2010-08-24 06:29:42 +00004451ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00004452 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00004453 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00004454 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
4455 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00004456 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004457
Douglas Gregor77549082010-02-24 21:29:12 +00004458 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00004459 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00004460 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00004461 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00004462 /*RPLoc*/ ExpectedLParenLoc);
4463}
Douglas Gregord4dca082010-02-24 18:44:31 +00004464
Eli Friedmane0dbedf2012-01-25 04:29:24 +00004465static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie91ec7892011-12-16 16:03:09 +00004466 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedmane0dbedf2012-01-25 04:29:24 +00004467 if (Base->hasPlaceholderType()) {
4468 ExprResult result = S.CheckPlaceholderExpr(Base);
4469 if (result.isInvalid()) return true;
4470 Base = result.take();
4471 }
4472 ObjectType = Base->getType();
4473
David Blaikie91ec7892011-12-16 16:03:09 +00004474 // C++ [expr.pseudo]p2:
4475 // The left-hand side of the dot operator shall be of scalar type. The
4476 // left-hand side of the arrow operator shall be of pointer to scalar type.
4477 // This scalar type is the object type.
Eli Friedmane0dbedf2012-01-25 04:29:24 +00004478 // Note that this is rather different from the normal handling for the
4479 // arrow operator.
David Blaikie91ec7892011-12-16 16:03:09 +00004480 if (OpKind == tok::arrow) {
4481 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4482 ObjectType = Ptr->getPointeeType();
4483 } else if (!Base->isTypeDependent()) {
4484 // The user wrote "p->" when she probably meant "p."; fix it.
4485 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4486 << ObjectType << true
4487 << FixItHint::CreateReplacement(OpLoc, ".");
4488 if (S.isSFINAEContext())
4489 return true;
4490
4491 OpKind = tok::period;
4492 }
4493 }
4494
4495 return false;
4496}
4497
John McCall60d7b3a2010-08-24 06:29:42 +00004498ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004499 SourceLocation OpLoc,
4500 tok::TokenKind OpKind,
4501 const CXXScopeSpec &SS,
4502 TypeSourceInfo *ScopeTypeInfo,
4503 SourceLocation CCLoc,
4504 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004505 PseudoDestructorTypeStorage Destructed,
John McCall2d9f5fa2011-02-25 05:21:17 +00004506 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004507 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004508
Eli Friedman8c9fe202012-01-25 04:35:06 +00004509 QualType ObjectType;
David Blaikie91ec7892011-12-16 16:03:09 +00004510 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4511 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004512
Douglas Gregorb57fb492010-02-24 22:38:50 +00004513 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
Nico Weberdf1be862012-01-23 05:50:57 +00004514 if (getLangOptions().MicrosoftMode && ObjectType->isVoidType())
Nico Weber2d757ec2012-01-23 06:08:16 +00004515 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Nico Weberdf1be862012-01-23 05:50:57 +00004516 else
4517 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
4518 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00004519 return ExprError();
4520 }
4521
4522 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004523 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb57fb492010-02-24 22:38:50 +00004524 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004525 if (DestructedTypeInfo) {
4526 QualType DestructedType = DestructedTypeInfo->getType();
4527 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004528 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCallf85e1932011-06-15 23:02:42 +00004529 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
4530 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
4531 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
4532 << ObjectType << DestructedType << Base->getSourceRange()
4533 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004534
John McCallf85e1932011-06-15 23:02:42 +00004535 // Recover by setting the destructed type to the object type.
4536 DestructedType = ObjectType;
4537 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004538 DestructedTypeStart);
John McCallf85e1932011-06-15 23:02:42 +00004539 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4540 } else if (DestructedType.getObjCLifetime() !=
4541 ObjectType.getObjCLifetime()) {
4542
4543 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
4544 // Okay: just pretend that the user provided the correctly-qualified
4545 // type.
4546 } else {
4547 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
4548 << ObjectType << DestructedType << Base->getSourceRange()
4549 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4550 }
4551
4552 // Recover by setting the destructed type to the object type.
4553 DestructedType = ObjectType;
4554 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4555 DestructedTypeStart);
4556 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4557 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004558 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00004559 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004560
Douglas Gregorb57fb492010-02-24 22:38:50 +00004561 // C++ [expr.pseudo]p2:
4562 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4563 // form
4564 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004565 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb57fb492010-02-24 22:38:50 +00004566 //
4567 // shall designate the same scalar type.
4568 if (ScopeTypeInfo) {
4569 QualType ScopeType = ScopeTypeInfo->getType();
4570 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00004571 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004572
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004573 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00004574 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00004575 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004576 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004577
Douglas Gregorb57fb492010-02-24 22:38:50 +00004578 ScopeType = QualType();
4579 ScopeTypeInfo = 0;
4580 }
4581 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004582
John McCall9ae2f072010-08-23 23:25:46 +00004583 Expr *Result
4584 = new (Context) CXXPseudoDestructorExpr(Context, Base,
4585 OpKind == tok::arrow, OpLoc,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004586 SS.getWithLocInContext(Context),
John McCall9ae2f072010-08-23 23:25:46 +00004587 ScopeTypeInfo,
4588 CCLoc,
4589 TildeLoc,
4590 Destructed);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004591
Douglas Gregorb57fb492010-02-24 22:38:50 +00004592 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00004593 return Owned(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004594
John McCall9ae2f072010-08-23 23:25:46 +00004595 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00004596}
4597
John McCall60d7b3a2010-08-24 06:29:42 +00004598ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004599 SourceLocation OpLoc,
4600 tok::TokenKind OpKind,
4601 CXXScopeSpec &SS,
4602 UnqualifiedId &FirstTypeName,
4603 SourceLocation CCLoc,
4604 SourceLocation TildeLoc,
4605 UnqualifiedId &SecondTypeName,
4606 bool HasTrailingLParen) {
Douglas Gregor77549082010-02-24 21:29:12 +00004607 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4608 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4609 "Invalid first type name in pseudo-destructor");
4610 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4611 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4612 "Invalid second type name in pseudo-destructor");
4613
Eli Friedman8c9fe202012-01-25 04:35:06 +00004614 QualType ObjectType;
David Blaikie91ec7892011-12-16 16:03:09 +00004615 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4616 return ExprError();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004617
4618 // Compute the object type that we should use for name lookup purposes. Only
4619 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00004620 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004621 if (!SS.isSet()) {
John McCall2d9f5fa2011-02-25 05:21:17 +00004622 if (ObjectType->isRecordType())
4623 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallb3d87482010-08-24 05:47:05 +00004624 else if (ObjectType->isDependentType())
4625 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004626 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004627
4628 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb57fb492010-02-24 22:38:50 +00004629 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00004630 QualType DestructedType;
4631 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004632 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00004633 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004634 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00004635 SecondTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00004636 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004637 if (!T &&
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004638 ((SS.isSet() && !computeDeclContext(SS, false)) ||
4639 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004640 // The name of the type being destroyed is a dependent name, and we
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004641 // couldn't find anything useful in scope. Just store the identifier and
4642 // it's location, and we'll perform (qualified) name lookup again at
4643 // template instantiation time.
4644 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
4645 SecondTypeName.StartLocation);
4646 } else if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004647 Diag(SecondTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00004648 diag::err_pseudo_dtor_destructor_non_type)
4649 << SecondTypeName.Identifier << ObjectType;
4650 if (isSFINAEContext())
4651 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004652
Douglas Gregor77549082010-02-24 21:29:12 +00004653 // Recover by assuming we had the right type all along.
4654 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004655 } else
Douglas Gregor77549082010-02-24 21:29:12 +00004656 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004657 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004658 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00004659 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004660 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4661 TemplateId->getTemplateArgs(),
4662 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00004663 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara55d23c92012-02-06 14:41:24 +00004664 TemplateId->TemplateKWLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +00004665 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004666 TemplateId->TemplateNameLoc,
4667 TemplateId->LAngleLoc,
4668 TemplateArgsPtr,
4669 TemplateId->RAngleLoc);
4670 if (T.isInvalid() || !T.get()) {
4671 // Recover by assuming we had the right type all along.
4672 DestructedType = ObjectType;
4673 } else
4674 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004675 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004676
4677 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb57fb492010-02-24 22:38:50 +00004678 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004679 if (!DestructedType.isNull()) {
4680 if (!DestructedTypeInfo)
4681 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004682 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004683 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4684 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004685
Douglas Gregorb57fb492010-02-24 22:38:50 +00004686 // Convert the name of the scope type (the type prior to '::') into a type.
4687 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00004688 QualType ScopeType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004689 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor77549082010-02-24 21:29:12 +00004690 FirstTypeName.Identifier) {
4691 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004692 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00004693 FirstTypeName.StartLocation,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004694 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00004695 if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004696 Diag(FirstTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00004697 diag::err_pseudo_dtor_destructor_non_type)
4698 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004699
Douglas Gregorb57fb492010-02-24 22:38:50 +00004700 if (isSFINAEContext())
4701 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004702
Douglas Gregorb57fb492010-02-24 22:38:50 +00004703 // Just drop this type. It's unnecessary anyway.
4704 ScopeType = QualType();
4705 } else
4706 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004707 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00004708 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00004709 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00004710 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4711 TemplateId->getTemplateArgs(),
4712 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00004713 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara55d23c92012-02-06 14:41:24 +00004714 TemplateId->TemplateKWLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +00004715 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00004716 TemplateId->TemplateNameLoc,
4717 TemplateId->LAngleLoc,
4718 TemplateArgsPtr,
4719 TemplateId->RAngleLoc);
4720 if (T.isInvalid() || !T.get()) {
4721 // Recover by dropping this type.
4722 ScopeType = QualType();
4723 } else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004724 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00004725 }
4726 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004727
Douglas Gregorb4a418f2010-02-24 23:02:30 +00004728 if (!ScopeType.isNull() && !ScopeTypeInfo)
4729 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
4730 FirstTypeName.StartLocation);
4731
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004732
John McCall9ae2f072010-08-23 23:25:46 +00004733 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00004734 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004735 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00004736}
4737
David Blaikie91ec7892011-12-16 16:03:09 +00004738ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4739 SourceLocation OpLoc,
4740 tok::TokenKind OpKind,
4741 SourceLocation TildeLoc,
4742 const DeclSpec& DS,
4743 bool HasTrailingLParen) {
Eli Friedman8c9fe202012-01-25 04:35:06 +00004744 QualType ObjectType;
David Blaikie91ec7892011-12-16 16:03:09 +00004745 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4746 return ExprError();
4747
4748 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4749
4750 TypeLocBuilder TLB;
4751 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
4752 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
4753 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
4754 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
4755
4756 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
4757 0, SourceLocation(), TildeLoc,
4758 Destructed, HasTrailingLParen);
4759}
4760
John Wiegley429bb272011-04-08 18:41:53 +00004761ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004762 CXXMethodDecl *Method,
4763 bool HadMultipleCandidates) {
John Wiegley429bb272011-04-08 18:41:53 +00004764 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
4765 FoundDecl, Method);
4766 if (Exp.isInvalid())
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004767 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00004768
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004769 MemberExpr *ME =
John Wiegley429bb272011-04-08 18:41:53 +00004770 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
Abramo Bagnara960809e2011-11-16 22:46:05 +00004771 SourceLocation(), Context.BoundMemberTy,
John McCallf89e55a2010-11-18 06:31:45 +00004772 VK_RValue, OK_Ordinary);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004773 if (HadMultipleCandidates)
4774 ME->setHadMultipleCandidates(true);
4775
John McCallf89e55a2010-11-18 06:31:45 +00004776 QualType ResultType = Method->getResultType();
4777 ExprValueKind VK = Expr::getValueKindForType(ResultType);
4778 ResultType = ResultType.getNonLValueExprType(Context);
4779
Eli Friedman5f2987c2012-02-02 03:46:19 +00004780 MarkFunctionReferenced(Exp.get()->getLocStart(), Method);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004781 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00004782 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
John Wiegley429bb272011-04-08 18:41:53 +00004783 Exp.get()->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00004784 return CE;
4785}
4786
Sebastian Redl2e156222010-09-10 20:55:43 +00004787ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4788 SourceLocation RParen) {
Sebastian Redl2e156222010-09-10 20:55:43 +00004789 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
4790 Operand->CanThrow(Context),
4791 KeyLoc, RParen));
4792}
4793
4794ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
4795 Expr *Operand, SourceLocation RParen) {
4796 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00004797}
4798
John McCallf6a16482010-12-04 03:47:34 +00004799/// Perform the conversions required for an expression used in a
4800/// context that ignores the result.
John Wiegley429bb272011-04-08 18:41:53 +00004801ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall3c3b7f92011-10-25 17:37:35 +00004802 if (E->hasPlaceholderType()) {
4803 ExprResult result = CheckPlaceholderExpr(E);
4804 if (result.isInvalid()) return Owned(E);
4805 E = result.take();
4806 }
4807
John McCalla878cda2010-12-02 02:07:15 +00004808 // C99 6.3.2.1:
4809 // [Except in specific positions,] an lvalue that does not have
4810 // array type is converted to the value stored in the
4811 // designated object (and is no longer an lvalue).
John McCalle6d134b2011-06-27 21:24:11 +00004812 if (E->isRValue()) {
4813 // In C, function designators (i.e. expressions of function type)
4814 // are r-values, but we still want to do function-to-pointer decay
4815 // on them. This is both technically correct and convenient for
4816 // some clients.
4817 if (!getLangOptions().CPlusPlus && E->getType()->isFunctionType())
4818 return DefaultFunctionArrayConversion(E);
4819
4820 return Owned(E);
4821 }
John McCalla878cda2010-12-02 02:07:15 +00004822
John McCallf6a16482010-12-04 03:47:34 +00004823 // Otherwise, this rule does not apply in C++, at least not for the moment.
John Wiegley429bb272011-04-08 18:41:53 +00004824 if (getLangOptions().CPlusPlus) return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004825
4826 // GCC seems to also exclude expressions of incomplete enum type.
4827 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
4828 if (!T->getDecl()->isComplete()) {
4829 // FIXME: stupid workaround for a codegen bug!
John Wiegley429bb272011-04-08 18:41:53 +00004830 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
4831 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004832 }
4833 }
4834
John Wiegley429bb272011-04-08 18:41:53 +00004835 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
4836 if (Res.isInvalid())
4837 return Owned(E);
4838 E = Res.take();
4839
John McCall85515d62010-12-04 12:29:11 +00004840 if (!E->getType()->isVoidType())
4841 RequireCompleteType(E->getExprLoc(), E->getType(),
4842 diag::err_incomplete_type);
John Wiegley429bb272011-04-08 18:41:53 +00004843 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00004844}
4845
John Wiegley429bb272011-04-08 18:41:53 +00004846ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
4847 ExprResult FullExpr = Owned(FE);
4848
4849 if (!FullExpr.get())
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00004850 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00004851
John Wiegley429bb272011-04-08 18:41:53 +00004852 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregord0937222010-12-13 22:49:22 +00004853 return ExprError();
4854
Douglas Gregor5e3a8be2011-12-15 00:53:32 +00004855 // Top-level message sends default to 'id' when we're in a debugger.
Sean Callanan50a9a122012-02-04 01:29:37 +00004856 if (getLangOptions().DebuggerCastResultToId &&
Douglas Gregor5e3a8be2011-12-15 00:53:32 +00004857 FullExpr.get()->getType() == Context.UnknownAnyTy &&
4858 isa<ObjCMessageExpr>(FullExpr.get())) {
4859 FullExpr = forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdType());
4860 if (FullExpr.isInvalid())
4861 return ExprError();
4862 }
4863
John McCallfb8721c2011-04-10 19:13:55 +00004864 FullExpr = CheckPlaceholderExpr(FullExpr.take());
4865 if (FullExpr.isInvalid())
4866 return ExprError();
Douglas Gregor353ee242011-03-07 02:05:23 +00004867
John Wiegley429bb272011-04-08 18:41:53 +00004868 FullExpr = IgnoredValueConversions(FullExpr.take());
4869 if (FullExpr.isInvalid())
4870 return ExprError();
4871
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004872 CheckImplicitConversions(FullExpr.get(), FullExpr.get()->getExprLoc());
John McCall4765fa02010-12-06 08:20:24 +00004873 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00004874}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004875
4876StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
4877 if (!FullStmt) return StmtError();
4878
John McCall4765fa02010-12-06 08:20:24 +00004879 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004880}
Francois Pichet1e862692011-05-06 20:48:22 +00004881
Douglas Gregorba0513d2011-10-25 01:33:02 +00004882Sema::IfExistsResult
4883Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
4884 CXXScopeSpec &SS,
4885 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet1e862692011-05-06 20:48:22 +00004886 DeclarationName TargetName = TargetNameInfo.getName();
4887 if (!TargetName)
Douglas Gregor3896fc52011-10-24 22:31:10 +00004888 return IER_DoesNotExist;
Douglas Gregorba0513d2011-10-25 01:33:02 +00004889
Douglas Gregor3896fc52011-10-24 22:31:10 +00004890 // If the name itself is dependent, then the result is dependent.
4891 if (TargetName.isDependentName())
4892 return IER_Dependent;
Douglas Gregorba0513d2011-10-25 01:33:02 +00004893
Francois Pichet1e862692011-05-06 20:48:22 +00004894 // Do the redeclaration lookup in the current scope.
4895 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
4896 Sema::NotForRedeclaration);
Douglas Gregor3896fc52011-10-24 22:31:10 +00004897 LookupParsedName(R, S, &SS);
Francois Pichet1e862692011-05-06 20:48:22 +00004898 R.suppressDiagnostics();
Douglas Gregor3896fc52011-10-24 22:31:10 +00004899
4900 switch (R.getResultKind()) {
4901 case LookupResult::Found:
4902 case LookupResult::FoundOverloaded:
4903 case LookupResult::FoundUnresolvedValue:
4904 case LookupResult::Ambiguous:
4905 return IER_Exists;
4906
4907 case LookupResult::NotFound:
4908 return IER_DoesNotExist;
4909
4910 case LookupResult::NotFoundInCurrentInstantiation:
4911 return IER_Dependent;
4912 }
David Blaikie7530c032012-01-17 06:56:22 +00004913
4914 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet1e862692011-05-06 20:48:22 +00004915}
Douglas Gregorba0513d2011-10-25 01:33:02 +00004916
Douglas Gregor65019ac2011-10-25 03:44:56 +00004917Sema::IfExistsResult
4918Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4919 bool IsIfExists, CXXScopeSpec &SS,
4920 UnqualifiedId &Name) {
Douglas Gregorba0513d2011-10-25 01:33:02 +00004921 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Douglas Gregor65019ac2011-10-25 03:44:56 +00004922
4923 // Check for unexpanded parameter packs.
4924 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
4925 collectUnexpandedParameterPacks(SS, Unexpanded);
4926 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
4927 if (!Unexpanded.empty()) {
4928 DiagnoseUnexpandedParameterPacks(KeywordLoc,
4929 IsIfExists? UPPC_IfExists
4930 : UPPC_IfNotExists,
4931 Unexpanded);
4932 return IER_Error;
4933 }
4934
Douglas Gregorba0513d2011-10-25 01:33:02 +00004935 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
4936}