blob: a053c2aed60c0e96e54862d43b6497a53300f096 [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner29375652006-12-04 18:06:35 +00007//
8//===----------------------------------------------------------------------===//
James Dennettf14a6e52012-06-15 22:23:43 +00009
10// \file
11// \brief Implements semantic analysis for C++ expressions.
Chris Lattner29375652006-12-04 18:06:35 +000012
John McCall83024632010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
John McCall19c1bfd2010-08-25 05:32:35 +000014#include "clang/Sema/DeclSpec.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
John McCall19c1bfd2010-08-25 05:32:35 +000017#include "clang/Sema/ParsedTemplate.h"
John McCallc63de662011-02-02 13:00:07 +000018#include "clang/Sema/ScopeInfo.h"
Richard Smith938f40b2011-06-11 17:19:42 +000019#include "clang/Sema/Scope.h"
John McCall19c1bfd2010-08-25 05:32:35 +000020#include "clang/Sema/TemplateDeduction.h"
Steve Naroffaac94152007-08-25 14:02:58 +000021#include "clang/AST/ASTContext.h"
Nick Lewycky411fc652012-01-24 21:15:41 +000022#include "clang/AST/CharUnits.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000025#include "clang/AST/ExprCXX.h"
Fariborz Jahanian1d446082010-06-16 18:56:04 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000027#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000029#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000030#include "clang/Lex/Preprocessor.h"
David Blaikie1d578782011-12-16 16:03:09 +000031#include "TypeLocBuilder.h"
Sebastian Redlb8fc4772012-02-16 12:59:47 +000032#include "llvm/ADT/APInt.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000033#include "llvm/ADT/STLExtras.h"
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +000034#include "llvm/Support/ErrorHandling.h"
Chris Lattner29375652006-12-04 18:06:35 +000035using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000036using namespace sema;
Chris Lattner29375652006-12-04 18:06:35 +000037
John McCallba7bf592010-08-24 05:47:05 +000038ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000039 IdentifierInfo &II,
John McCallba7bf592010-08-24 05:47:05 +000040 SourceLocation NameLoc,
41 Scope *S, CXXScopeSpec &SS,
42 ParsedType ObjectTypePtr,
43 bool EnteringContext) {
Douglas Gregorfe17d252010-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 Gregor46841e12010-02-23 00:15:22 +000063 // See also PR6358 and PR6359.
Sebastian Redla771d222010-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 Gregorfe17d252010-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 Gregor46841e12010-02-23 00:15:22 +000078 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000079
Douglas Gregor46841e12010-02-23 00:15:22 +000080 bool AlreadySearched = false;
81 bool LookAtPrefix = true;
Sebastian Redla771d222010-07-07 23:17:38 +000082 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000083 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redla771d222010-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 Takumi7c288862011-01-27 07:09:49 +000086 //
87 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redla771d222010-07-07 23:17:38 +000088 //
89 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth8f254812010-02-21 10:19:54 +000090 // a qualified-id of the form:
Douglas Gregorfe17d252010-02-16 19:09:40 +000091 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +000092 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregorfe17d252010-02-16 19:09:40 +000093 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000094 // the class-names are looked up as types in the scope designated by
Sebastian Redla771d222010-07-07 23:17:38 +000095 // the nested-name-specifier.
Douglas Gregorfe17d252010-02-16 19:09:40 +000096 //
Sebastian Redla771d222010-07-07 23:17:38 +000097 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000098 // code below is permitted to look at the prefix of the
Sebastian Redla771d222010-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 Takumif9cbcc42011-01-27 07:10:08 +0000107
Sebastian Redla771d222010-07-07 23:17:38 +0000108 // The second case from the C++03 rules quoted further above.
Douglas Gregor46841e12010-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 Gregor10176412011-02-25 16:07:42 +0000114 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor46841e12010-02-23 00:15:22 +0000115 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
116 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor46841e12010-02-23 00:15:22 +0000117 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000118 LookupCtx = computeDeclContext(SearchType);
119 isDependent = SearchType->isDependentType();
120 } else {
121 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000122 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000123 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000124
Douglas Gregorcd3f49f2010-02-25 04:46:04 +0000125 LookInScope = false;
Douglas Gregorfe17d252010-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 Takumif9cbcc42011-01-27 07:10:08 +0000136 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregorfe17d252010-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 Gregor4cf85a72011-03-04 22:32:08 +0000145 TypeDecl *NonMatchingTypeDecl = 0;
Douglas Gregorfe17d252010-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 Gregor4cf85a72011-03-04 22:32:08 +0000149 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregorfe17d252010-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 Gregor678f90d2010-02-25 01:56:36 +0000154 else if (Step == 1 && LookInScope && S)
Douglas Gregorfe17d252010-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 McCallba7bf592010-08-24 05:47:05 +0000161 return ParsedType();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000162
163 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
164 QualType T = Context.getTypeDeclType(Type);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000165
166 if (SearchType.isNull() || SearchType->isDependentType() ||
167 Context.hasSameUnqualifiedType(T, SearchType)) {
168 // We found our type!
169
John McCallba7bf592010-08-24 05:47:05 +0000170 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000171 }
John Wiegleyb4a9e512011-03-08 08:13:22 +0000172
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000173 if (!SearchType.isNull())
174 NonMatchingTypeDecl = Type;
Douglas Gregorfe17d252010-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 Takumif9cbcc42011-01-27 07:10:08 +0000182 // issue 399, for which there isn't even an obvious direction.
Douglas Gregorfe17d252010-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 McCalle78aac42010-03-10 03:28:59 +0000188 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
189 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000190 }
191 }
192 if (MemberOfType.isNull())
193 MemberOfType = SearchType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000194
Douglas Gregorfe17d252010-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 McCallba7bf592010-08-24 05:47:05 +0000206 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000207 }
208
209 continue;
210 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000211
Douglas Gregorfe17d252010-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 McCallba7bf592010-08-24 05:47:05 +0000225 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-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 Takumif9cbcc42011-01-27 07:10:08 +0000232 if (DependentTemplateName *DepTemplate
Douglas Gregorfe17d252010-02-16 19:09:40 +0000233 = SpecName.getAsDependentTemplateName()) {
234 if (DepTemplate->isIdentifier() &&
235 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallba7bf592010-08-24 05:47:05 +0000236 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-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 Gregor9cbc22b2011-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 McCallba7bf592010-08-24 05:47:05 +0000252 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000253 }
254
Douglas Gregor4cf85a72011-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 Takumif9cbcc42011-01-27 07:10:08 +0000263 << &II;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000264 else
265 Diag(NameLoc, diag::err_destructor_class_name);
266
John McCallba7bf592010-08-24 05:47:05 +0000267 return ParsedType();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000268}
269
David Blaikieecd8a942011-12-08 16:13:53 +0000270ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
David Blaikie08608f62011-12-12 04:13:55 +0000271 if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
David Blaikieecd8a942011-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 Gregor9da64192010-04-26 22:37:10 +0000286/// \brief Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000287ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000288 SourceLocation TypeidLoc,
289 TypeSourceInfo *Operand,
290 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000291 // C++ [expr.typeid]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000292 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor9da64192010-04-26 22:37:10 +0000293 // that is the operand of typeid are always ignored.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000294 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor9da64192010-04-26 22:37:10 +0000295 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000296 Qualifiers Quals;
297 QualType T
298 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
299 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000300 if (T->getAs<RecordType>() &&
301 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
302 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000303
Douglas Gregor9da64192010-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 McCalldadc5752010-08-24 06:29:42 +0000310ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000311 SourceLocation TypeidLoc,
312 Expr *E,
313 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000314 if (E && !E->isTypeDependent()) {
John McCall50a2c2c2011-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 Gregor9da64192010-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 Takumif9cbcc42011-01-27 07:10:08 +0000329
Douglas Gregor9da64192010-04-26 22:37:10 +0000330 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000331 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000332 // polymorphic class type [...] [the] expression is an unevaluated
333 // operand. [...]
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000334 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Eli Friedman456f0182012-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 Gregor88d292c2010-05-13 16:44:06 +0000340
341 // We require a vtable to query the type at run time.
342 MarkVTableUsed(TypeidLoc, RecordD);
343 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000344 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000345
Douglas Gregor9da64192010-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 Takumif9cbcc42011-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 Gregor9da64192010-04-26 22:37:10 +0000350 // type.
Douglas Gregor876cec22010-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 Friedmanbe4b3632011-09-27 21:58:52 +0000355 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take();
Douglas Gregor9da64192010-04-26 22:37:10 +0000356 }
357 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000358
Douglas Gregor9da64192010-04-26 22:37:10 +0000359 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCallb268a282010-08-23 23:25:46 +0000360 E,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000361 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor9da64192010-04-26 22:37:10 +0000362}
363
364/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000365ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000366Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
367 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000368 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000369 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000370 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000371
Douglas Gregor4c7c1092010-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>();
Nico Weber5f968832012-06-19 23:58:27 +0000377 // Microsoft's typeinfo doesn't have type_info in std but in the global
378 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
379 if (!CXXTypeInfoDecl && LangOpts.MicrosoftMode) {
380 LookupQualifiedName(R, Context.getTranslationUnitDecl());
381 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
382 }
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000383 if (!CXXTypeInfoDecl)
384 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
385 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000386
Nico Weber1b7f39d2012-05-20 01:27:21 +0000387 if (!getLangOpts().RTTI) {
388 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
389 }
390
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000391 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000392
Douglas Gregor9da64192010-04-26 22:37:10 +0000393 if (isType) {
394 // The operand is a type; handle it as such.
395 TypeSourceInfo *TInfo = 0;
John McCallba7bf592010-08-24 05:47:05 +0000396 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
397 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000398 if (T.isNull())
399 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000400
Douglas Gregor9da64192010-04-26 22:37:10 +0000401 if (!TInfo)
402 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000403
Douglas Gregor9da64192010-04-26 22:37:10 +0000404 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000405 }
Mike Stump11289f42009-09-09 15:08:12 +0000406
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000407 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000408 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000409}
410
Francois Pichetb7577652010-12-27 01:32:00 +0000411/// Retrieve the UuidAttr associated with QT.
412static UuidAttr *GetUuidAttrOfType(QualType QT) {
413 // Optionally remove one level of pointer, reference or array indirection.
John McCall424cec92011-01-19 06:33:43 +0000414 const Type *Ty = QT.getTypePtr();;
Francois Pichet9dddd402010-12-20 03:51:03 +0000415 if (QT->isPointerType() || QT->isReferenceType())
416 Ty = QT->getPointeeType().getTypePtr();
417 else if (QT->isArrayType())
418 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
419
Francois Pichet59d2b012011-05-08 10:02:20 +0000420 // Loop all record redeclaration looking for an uuid attribute.
Francois Pichetb7577652010-12-27 01:32:00 +0000421 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Francois Pichet59d2b012011-05-08 10:02:20 +0000422 for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(),
423 E = RD->redecls_end(); I != E; ++I) {
424 if (UuidAttr *Uuid = I->getAttr<UuidAttr>())
Francois Pichetb7577652010-12-27 01:32:00 +0000425 return Uuid;
Francois Pichetb7577652010-12-27 01:32:00 +0000426 }
Francois Pichet59d2b012011-05-08 10:02:20 +0000427
Francois Pichetb7577652010-12-27 01:32:00 +0000428 return 0;
Francois Pichet9dddd402010-12-20 03:51:03 +0000429}
430
Francois Pichet9f4f2072010-09-08 12:20:18 +0000431/// \brief Build a Microsoft __uuidof expression with a type operand.
432ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
433 SourceLocation TypeidLoc,
434 TypeSourceInfo *Operand,
435 SourceLocation RParenLoc) {
Francois Pichetb7577652010-12-27 01:32:00 +0000436 if (!Operand->getType()->isDependentType()) {
437 if (!GetUuidAttrOfType(Operand->getType()))
438 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
439 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000440
Francois Pichet9f4f2072010-09-08 12:20:18 +0000441 // FIXME: add __uuidof semantic analysis for type operand.
442 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
443 Operand,
444 SourceRange(TypeidLoc, RParenLoc)));
445}
446
447/// \brief Build a Microsoft __uuidof expression with an expression operand.
448ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
449 SourceLocation TypeidLoc,
450 Expr *E,
451 SourceLocation RParenLoc) {
Francois Pichetb7577652010-12-27 01:32:00 +0000452 if (!E->getType()->isDependentType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000453 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichetb7577652010-12-27 01:32:00 +0000454 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
455 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
456 }
457 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000458 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
459 E,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000460 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000461}
462
463/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
464ExprResult
465Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
466 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000467 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000468 if (!MSVCGuidDecl) {
469 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
470 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
471 LookupQualifiedName(R, Context.getTranslationUnitDecl());
472 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
473 if (!MSVCGuidDecl)
474 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000475 }
476
Francois Pichet9f4f2072010-09-08 12:20:18 +0000477 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000478
Francois Pichet9f4f2072010-09-08 12:20:18 +0000479 if (isType) {
480 // The operand is a type; handle it as such.
481 TypeSourceInfo *TInfo = 0;
482 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
483 &TInfo);
484 if (T.isNull())
485 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000486
Francois Pichet9f4f2072010-09-08 12:20:18 +0000487 if (!TInfo)
488 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
489
490 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
491 }
492
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000493 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000494 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
495}
496
Steve Naroff66356bd2007-09-16 14:56:35 +0000497/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000498ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000499Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000500 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000501 "Unknown C++ Boolean value!");
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000502 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
503 Context.BoolTy, OpLoc));
Bill Wendling4073ed52007-02-13 01:51:42 +0000504}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000505
Sebastian Redl576fd422009-05-10 18:38:11 +0000506/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000507ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000508Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
509 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
510}
511
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000512/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000513ExprResult
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000514Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
515 bool IsThrownVarInScope = false;
516 if (Ex) {
517 // C++0x [class.copymove]p31:
518 // When certain criteria are met, an implementation is allowed to omit the
519 // copy/move construction of a class object [...]
520 //
521 // - in a throw-expression, when the operand is the name of a
522 // non-volatile automatic object (other than a function or catch-
523 // clause parameter) whose scope does not extend beyond the end of the
524 // innermost enclosing try-block (if there is one), the copy/move
525 // operation from the operand to the exception object (15.1) can be
526 // omitted by constructing the automatic object directly into the
527 // exception object
528 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
529 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
530 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
531 for( ; S; S = S->getParent()) {
532 if (S->isDeclScope(Var)) {
533 IsThrownVarInScope = true;
534 break;
535 }
536
537 if (S->getFlags() &
538 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
539 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
540 Scope::TryScope))
541 break;
542 }
543 }
544 }
545 }
546
547 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
548}
549
550ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
551 bool IsThrownVarInScope) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000552 // Don't report an error if 'throw' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000553 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000554 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb94ad3e2011-02-19 21:53:09 +0000555 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000556
John Wiegley01296292011-04-08 18:41:53 +0000557 if (Ex && !Ex->isTypeDependent()) {
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000558 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
John Wiegley01296292011-04-08 18:41:53 +0000559 if (ExRes.isInvalid())
560 return ExprError();
561 Ex = ExRes.take();
562 }
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000563
564 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
565 IsThrownVarInScope));
Sebastian Redl4de47b42009-04-27 20:27:31 +0000566}
567
568/// CheckCXXThrowOperand - Validate the operand of a throw.
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000569ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
570 bool IsThrownVarInScope) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000571 // C++ [except.throw]p3:
Douglas Gregor247894b2009-12-23 22:04:40 +0000572 // A throw-expression initializes a temporary object, called the exception
573 // object, the type of which is determined by removing any top-level
574 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000575 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor247894b2009-12-23 22:04:40 +0000576 // or "pointer to function returning T", [...]
577 if (E->getType().hasQualifiers())
John Wiegley01296292011-04-08 18:41:53 +0000578 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Eli Friedmanbe4b3632011-09-27 21:58:52 +0000579 E->getValueKind()).take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000580
John Wiegley01296292011-04-08 18:41:53 +0000581 ExprResult Res = DefaultFunctionArrayConversion(E);
582 if (Res.isInvalid())
583 return ExprError();
584 E = Res.take();
Sebastian Redl4de47b42009-04-27 20:27:31 +0000585
586 // If the type of the exception would be an incomplete type or a pointer
587 // to an incomplete type other than (cv) void the program is ill-formed.
588 QualType Ty = E->getType();
John McCall2e6567a2010-04-22 01:10:34 +0000589 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000590 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000591 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000592 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000593 }
594 if (!isPointer || !Ty->isVoidType()) {
595 if (RequireCompleteType(ThrowLoc, Ty,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000596 isPointer? diag::err_throw_incomplete_ptr
597 : diag::err_throw_incomplete,
598 E->getSourceRange()))
John Wiegley01296292011-04-08 18:41:53 +0000599 return ExprError();
Rafael Espindola70e040d2010-03-02 21:28:26 +0000600
Douglas Gregore8154332010-04-15 18:05:39 +0000601 if (RequireNonAbstractType(ThrowLoc, E->getType(),
Douglas Gregorae298422012-05-04 17:09:59 +0000602 diag::err_throw_abstract_type, E))
John Wiegley01296292011-04-08 18:41:53 +0000603 return ExprError();
Sebastian Redl4de47b42009-04-27 20:27:31 +0000604 }
605
John McCall2e6567a2010-04-22 01:10:34 +0000606 // Initialize the exception result. This implicitly weeds out
607 // abstract types or types with inaccessible copy constructors.
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000608
609 // C++0x [class.copymove]p31:
610 // When certain criteria are met, an implementation is allowed to omit the
611 // copy/move construction of a class object [...]
612 //
613 // - in a throw-expression, when the operand is the name of a
614 // non-volatile automatic object (other than a function or catch-clause
615 // parameter) whose scope does not extend beyond the end of the
616 // innermost enclosing try-block (if there is one), the copy/move
617 // operation from the operand to the exception object (15.1) can be
618 // omitted by constructing the automatic object directly into the
619 // exception object
620 const VarDecl *NRVOVariable = 0;
621 if (IsThrownVarInScope)
622 NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
623
John McCall2e6567a2010-04-22 01:10:34 +0000624 InitializedEntity Entity =
Douglas Gregorc74edc22011-01-21 22:46:35 +0000625 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000626 /*NRVO=*/NRVOVariable != 0);
John Wiegley01296292011-04-08 18:41:53 +0000627 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000628 QualType(), E,
629 IsThrownVarInScope);
John McCall2e6567a2010-04-22 01:10:34 +0000630 if (Res.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000631 return ExprError();
632 E = Res.take();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000633
Eli Friedman91a3d272010-06-03 20:39:03 +0000634 // If the exception has class type, we need additional handling.
635 const RecordType *RecordTy = Ty->getAs<RecordType>();
636 if (!RecordTy)
John Wiegley01296292011-04-08 18:41:53 +0000637 return Owned(E);
Eli Friedman91a3d272010-06-03 20:39:03 +0000638 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
639
Douglas Gregor88d292c2010-05-13 16:44:06 +0000640 // If we are throwing a polymorphic class type or pointer thereof,
641 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000642 MarkVTableUsed(ThrowLoc, RD);
643
Eli Friedman36ebbec2010-10-12 20:32:36 +0000644 // If a pointer is thrown, the referenced object will not be destroyed.
645 if (isPointer)
John Wiegley01296292011-04-08 18:41:53 +0000646 return Owned(E);
Eli Friedman36ebbec2010-10-12 20:32:36 +0000647
Richard Smitheec915d62012-02-18 04:13:32 +0000648 // If the class has a destructor, we must be able to call it.
649 if (RD->hasIrrelevantDestructor())
John Wiegley01296292011-04-08 18:41:53 +0000650 return Owned(E);
Eli Friedman91a3d272010-06-03 20:39:03 +0000651
Sebastian Redl249dee52012-03-05 19:35:43 +0000652 CXXDestructorDecl *Destructor = LookupDestructor(RD);
Eli Friedman91a3d272010-06-03 20:39:03 +0000653 if (!Destructor)
John Wiegley01296292011-04-08 18:41:53 +0000654 return Owned(E);
Eli Friedman91a3d272010-06-03 20:39:03 +0000655
Eli Friedmanfa0df832012-02-02 03:46:19 +0000656 MarkFunctionReferenced(E->getExprLoc(), Destructor);
Eli Friedman91a3d272010-06-03 20:39:03 +0000657 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregor747eb782010-07-08 06:14:04 +0000658 PDiag(diag::err_access_dtor_exception) << Ty);
Richard Smitheec915d62012-02-18 04:13:32 +0000659 DiagnoseUseOfDecl(Destructor, E->getExprLoc());
John Wiegley01296292011-04-08 18:41:53 +0000660 return Owned(E);
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000661}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000662
Eli Friedman73a04092012-01-07 04:59:52 +0000663QualType Sema::getCurrentThisType() {
664 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +0000665 QualType ThisTy = CXXThisTypeOverride;
Richard Smith938f40b2011-06-11 17:19:42 +0000666 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
667 if (method && method->isInstance())
668 ThisTy = method->getThisType(Context);
Richard Smith938f40b2011-06-11 17:19:42 +0000669 }
Douglas Gregor3024f072012-04-16 07:05:22 +0000670
Richard Smith938f40b2011-06-11 17:19:42 +0000671 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +0000672}
673
Douglas Gregor3024f072012-04-16 07:05:22 +0000674Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
675 Decl *ContextDecl,
676 unsigned CXXThisTypeQuals,
677 bool Enabled)
678 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
679{
680 if (!Enabled || !ContextDecl)
681 return;
682
683 CXXRecordDecl *Record = 0;
684 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
685 Record = Template->getTemplatedDecl();
686 else
687 Record = cast<CXXRecordDecl>(ContextDecl);
688
689 S.CXXThisTypeOverride
690 = S.Context.getPointerType(
691 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
692
693 this->Enabled = true;
694}
695
696
697Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
698 if (Enabled) {
699 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
700 }
701}
702
Douglas Gregorcdd11d42012-02-01 17:04:21 +0000703void Sema::CheckCXXThisCapture(SourceLocation Loc, bool Explicit) {
Eli Friedman73a04092012-01-07 04:59:52 +0000704 // We don't need to capture this in an unevaluated context.
Douglas Gregorcdd11d42012-02-01 17:04:21 +0000705 if (ExprEvalContexts.back().Context == Unevaluated && !Explicit)
Eli Friedman73a04092012-01-07 04:59:52 +0000706 return;
707
708 // Otherwise, check that we can capture 'this'.
709 unsigned NumClosures = 0;
710 for (unsigned idx = FunctionScopes.size() - 1; idx != 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +0000711 if (CapturingScopeInfo *CSI =
712 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
713 if (CSI->CXXThisCaptureIndex != 0) {
714 // 'this' is already being captured; there isn't anything more to do.
Eli Friedman73a04092012-01-07 04:59:52 +0000715 break;
716 }
Douglas Gregorcdd11d42012-02-01 17:04:21 +0000717
Eli Friedman20139d32012-01-11 02:36:31 +0000718 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +0000719 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +0000720 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
721 Explicit) {
722 // This closure can capture 'this'; continue looking upwards.
Eli Friedman73a04092012-01-07 04:59:52 +0000723 NumClosures++;
Douglas Gregorcdd11d42012-02-01 17:04:21 +0000724 Explicit = false;
Eli Friedman73a04092012-01-07 04:59:52 +0000725 continue;
726 }
Eli Friedman20139d32012-01-11 02:36:31 +0000727 // This context can't implicitly capture 'this'; fail out.
Douglas Gregorcdd11d42012-02-01 17:04:21 +0000728 Diag(Loc, diag::err_this_capture) << Explicit;
Eli Friedman73a04092012-01-07 04:59:52 +0000729 return;
730 }
Eli Friedman73a04092012-01-07 04:59:52 +0000731 break;
732 }
733
734 // Mark that we're implicitly capturing 'this' in all the scopes we skipped.
735 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
736 // contexts.
737 for (unsigned idx = FunctionScopes.size() - 1;
738 NumClosures; --idx, --NumClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +0000739 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Eli Friedmanc9751062012-02-11 02:51:16 +0000740 Expr *ThisExpr = 0;
Douglas Gregorfdf598e2012-02-18 09:37:24 +0000741 QualType ThisTy = getCurrentThisType();
Eli Friedmanc9751062012-02-11 02:51:16 +0000742 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
743 // For lambda expressions, build a field and an initializing expression.
Eli Friedmanc9751062012-02-11 02:51:16 +0000744 CXXRecordDecl *Lambda = LSI->Lambda;
745 FieldDecl *Field
746 = FieldDecl::Create(Context, Lambda, Loc, Loc, 0, ThisTy,
747 Context.getTrivialTypeSourceInfo(ThisTy, Loc),
Richard Smith2b013182012-06-10 03:12:00 +0000748 0, false, ICIS_NoInit);
Eli Friedmanc9751062012-02-11 02:51:16 +0000749 Field->setImplicit(true);
750 Field->setAccess(AS_private);
751 Lambda->addDecl(Field);
752 ThisExpr = new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/true);
753 }
Eli Friedman20139d32012-01-11 02:36:31 +0000754 bool isNested = NumClosures > 1;
Douglas Gregorfdf598e2012-02-18 09:37:24 +0000755 CSI->addThisCapture(isNested, Loc, ThisTy, ThisExpr);
Eli Friedman73a04092012-01-07 04:59:52 +0000756 }
757}
758
Richard Smith938f40b2011-06-11 17:19:42 +0000759ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +0000760 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
761 /// is a non-lvalue expression whose value is the address of the object for
762 /// which the function is called.
763
Douglas Gregor09deffa2011-10-18 16:47:30 +0000764 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +0000765 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +0000766
Eli Friedman73a04092012-01-07 04:59:52 +0000767 CheckCXXThisCapture(Loc);
Richard Smith938f40b2011-06-11 17:19:42 +0000768 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000769}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000770
Douglas Gregor3024f072012-04-16 07:05:22 +0000771bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
772 // If we're outside the body of a member function, then we'll have a specified
773 // type for 'this'.
774 if (CXXThisTypeOverride.isNull())
775 return false;
776
777 // Determine whether we're looking into a class that's currently being
778 // defined.
779 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
780 return Class && Class->isBeingDefined();
781}
782
John McCalldadc5752010-08-24 06:29:42 +0000783ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +0000784Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000785 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000786 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000787 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +0000788 if (!TypeRep)
789 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000790
John McCall97513962010-01-15 18:39:57 +0000791 TypeSourceInfo *TInfo;
792 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
793 if (!TInfo)
794 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +0000795
796 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
797}
798
799/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
800/// Can be interpreted either as function-style casting ("int(x)")
801/// or class type construction ("ClassType(x,y,z)")
802/// or creation of a value-initialized type ("int()").
803ExprResult
804Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
805 SourceLocation LParenLoc,
806 MultiExprArg exprs,
807 SourceLocation RParenLoc) {
808 QualType Ty = TInfo->getType();
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000809 unsigned NumExprs = exprs.size();
810 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregor2b88c112010-09-08 00:15:04 +0000811 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000812
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000813 if (Ty->isDependentType() ||
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +0000814 CallExpr::hasAnyTypeDependentArguments(
815 llvm::makeArrayRef(Exprs, NumExprs))) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000816 exprs.release();
Mike Stump11289f42009-09-09 15:08:12 +0000817
Douglas Gregor2b88c112010-09-08 00:15:04 +0000818 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregorce934142009-05-20 18:46:25 +0000819 LParenLoc,
820 Exprs, NumExprs,
821 RParenLoc));
Douglas Gregor0950e412009-03-13 21:01:28 +0000822 }
823
Sebastian Redld74dd492012-02-12 18:41:05 +0000824 bool ListInitialization = LParenLoc.isInvalid();
825 assert((!ListInitialization || (NumExprs == 1 && isa<InitListExpr>(Exprs[0])))
826 && "List initialization must have initializer list as expression.");
827 SourceRange FullRange = SourceRange(TyBeginLoc,
828 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
829
Douglas Gregordd04d332009-01-16 18:33:17 +0000830 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000831 // If the expression list is a single expression, the type conversion
832 // expression is equivalent (in definedness, and if defined in meaning) to the
833 // corresponding cast expression.
Sebastian Redl2b80af42012-02-13 19:55:43 +0000834 if (NumExprs == 1 && !ListInitialization) {
John McCallb50451a2011-10-05 07:41:44 +0000835 Expr *Arg = Exprs[0];
Anders Carlssone9766d52009-09-09 21:33:21 +0000836 exprs.release();
John McCallb50451a2011-10-05 07:41:44 +0000837 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000838 }
839
Eli Friedman576cbd02012-02-29 00:00:28 +0000840 QualType ElemTy = Ty;
841 if (Ty->isArrayType()) {
842 if (!ListInitialization)
843 return ExprError(Diag(TyBeginLoc,
844 diag::err_value_init_for_array_type) << FullRange);
845 ElemTy = Context.getBaseElementType(Ty);
846 }
847
848 if (!Ty->isVoidType() &&
849 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000850 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +0000851 return ExprError();
852
853 if (RequireNonAbstractType(TyBeginLoc, Ty,
854 diag::err_allocation_of_abstract_type))
855 return ExprError();
856
Douglas Gregor8ec51732010-09-08 21:40:08 +0000857 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
858 InitializationKind Kind
Sebastian Redl2b80af42012-02-13 19:55:43 +0000859 = NumExprs ? ListInitialization
860 ? InitializationKind::CreateDirectList(TyBeginLoc)
861 : InitializationKind::CreateDirect(TyBeginLoc,
862 LParenLoc, RParenLoc)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000863 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor8ec51732010-09-08 21:40:08 +0000864 LParenLoc, RParenLoc);
865 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
866 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000867
Sebastian Redl2b80af42012-02-13 19:55:43 +0000868 if (!Result.isInvalid() && ListInitialization &&
869 isa<InitListExpr>(Result.get())) {
870 // If the list-initialization doesn't involve a constructor call, we'll get
871 // the initializer-list (with corrected type) back, but that's not what we
872 // want, since it will be treated as an initializer list in further
873 // processing. Explicitly insert a cast here.
874 InitListExpr *List = cast<InitListExpr>(Result.take());
875 Result = Owned(CXXFunctionalCastExpr::Create(Context, List->getType(),
876 Expr::getValueKindForType(TInfo->getType()),
877 TInfo, TyBeginLoc, CK_NoOp,
878 List, /*Path=*/0, RParenLoc));
879 }
880
Douglas Gregor8ec51732010-09-08 21:40:08 +0000881 // FIXME: Improve AST representation?
882 return move(Result);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000883}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000884
John McCall284c48f2011-01-27 09:37:56 +0000885/// doesUsualArrayDeleteWantSize - Answers whether the usual
886/// operator delete[] for the given type has a size_t parameter.
887static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
888 QualType allocType) {
889 const RecordType *record =
890 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
891 if (!record) return false;
892
893 // Try to find an operator delete[] in class scope.
894
895 DeclarationName deleteName =
896 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
897 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
898 S.LookupQualifiedName(ops, record->getDecl());
899
900 // We're just doing this for information.
901 ops.suppressDiagnostics();
902
903 // Very likely: there's no operator delete[].
904 if (ops.empty()) return false;
905
906 // If it's ambiguous, it should be illegal to call operator delete[]
907 // on this thing, so it doesn't matter if we allocate extra space or not.
908 if (ops.isAmbiguous()) return false;
909
910 LookupResult::Filter filter = ops.makeFilter();
911 while (filter.hasNext()) {
912 NamedDecl *del = filter.next()->getUnderlyingDecl();
913
914 // C++0x [basic.stc.dynamic.deallocation]p2:
915 // A template instance is never a usual deallocation function,
916 // regardless of its signature.
917 if (isa<FunctionTemplateDecl>(del)) {
918 filter.erase();
919 continue;
920 }
921
922 // C++0x [basic.stc.dynamic.deallocation]p2:
923 // If class T does not declare [an operator delete[] with one
924 // parameter] but does declare a member deallocation function
925 // named operator delete[] with exactly two parameters, the
926 // second of which has type std::size_t, then this function
927 // is a usual deallocation function.
928 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
929 filter.erase();
930 continue;
931 }
932 }
933 filter.done();
934
935 if (!ops.isSingleResult()) return false;
936
937 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
938 return (del->getNumParams() == 2);
939}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000940
Sebastian Redld74dd492012-02-12 18:41:05 +0000941/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +0000942///
Sebastian Redld74dd492012-02-12 18:41:05 +0000943/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +0000944/// @code new (memory) int[size][4] @endcode
945/// or
946/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +0000947///
948/// \param StartLoc The first location of the expression.
949/// \param UseGlobal True if 'new' was prefixed with '::'.
950/// \param PlacementLParen Opening paren of the placement arguments.
951/// \param PlacementArgs Placement new arguments.
952/// \param PlacementRParen Closing paren of the placement arguments.
953/// \param TypeIdParens If the type is in parens, the source range.
954/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +0000955/// \param Initializer The initializing expression or initializer-list, or null
956/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +0000957ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000958Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000959 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000960 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +0000961 Declarator &D, Expr *Initializer) {
Richard Smith30482bc2011-02-20 03:19:35 +0000962 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
963
Sebastian Redl351bb782008-12-02 14:43:59 +0000964 Expr *ArraySize = 0;
Sebastian Redl351bb782008-12-02 14:43:59 +0000965 // If the specified type is an array, unwrap it and save the expression.
966 if (D.getNumTypeObjects() > 0 &&
967 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
James Dennettf14a6e52012-06-15 22:23:43 +0000968 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith30482bc2011-02-20 03:19:35 +0000969 if (TypeContainsAuto)
970 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
971 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000972 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000973 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
974 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000975 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000976 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
977 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000978
Sebastian Redl351bb782008-12-02 14:43:59 +0000979 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000980 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +0000981 }
982
Douglas Gregor73341c42009-09-11 00:18:58 +0000983 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000984 if (ArraySize) {
985 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +0000986 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
987 break;
988
989 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
990 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +0000991 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +0000992 Array.NumElts
993 = VerifyIntegerConstantExpression(NumElts, 0,
994 diag::err_new_array_nonconst)
995 .take();
Richard Smithf4c51d92012-02-04 09:53:13 +0000996 if (!Array.NumElts)
997 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +0000998 }
999 }
1000 }
1001 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001002
Argyrios Kyrtzidis3ff13572011-06-28 03:01:23 +00001003 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
John McCall8cb7bdf2010-06-04 23:28:52 +00001004 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001005 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001006 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001007
Sebastian Redl6047f072012-02-16 12:22:20 +00001008 SourceRange DirectInitRange;
1009 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1010 DirectInitRange = List->getSourceRange();
1011
Mike Stump11289f42009-09-09 15:08:12 +00001012 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001013 PlacementLParen,
Mike Stump11289f42009-09-09 15:08:12 +00001014 move(PlacementArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +00001015 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001016 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +00001017 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001018 TInfo,
John McCallb268a282010-08-23 23:25:46 +00001019 ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001020 DirectInitRange,
1021 Initializer,
Richard Smith30482bc2011-02-20 03:19:35 +00001022 TypeContainsAuto);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001023}
1024
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001025static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1026 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001027 if (!Init)
1028 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001029 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1030 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001031 if (isa<ImplicitValueInitExpr>(Init))
1032 return true;
1033 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1034 return !CCE->isListInitialization() &&
1035 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001036 else if (Style == CXXNewExpr::ListInit) {
1037 assert(isa<InitListExpr>(Init) &&
1038 "Shouldn't create list CXXConstructExprs for arrays.");
1039 return true;
1040 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001041 return false;
1042}
1043
John McCalldadc5752010-08-24 06:29:42 +00001044ExprResult
Douglas Gregord0fefba2009-05-21 00:00:09 +00001045Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
1046 SourceLocation PlacementLParen,
1047 MultiExprArg PlacementArgs,
1048 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001049 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001050 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001051 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +00001052 Expr *ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001053 SourceRange DirectInitRange,
1054 Expr *Initializer,
Richard Smith30482bc2011-02-20 03:19:35 +00001055 bool TypeMayContainAuto) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001056 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redl351bb782008-12-02 14:43:59 +00001057
Sebastian Redl6047f072012-02-16 12:22:20 +00001058 CXXNewExpr::InitializationStyle initStyle;
1059 if (DirectInitRange.isValid()) {
1060 assert(Initializer && "Have parens but no initializer.");
1061 initStyle = CXXNewExpr::CallInit;
1062 } else if (Initializer && isa<InitListExpr>(Initializer))
1063 initStyle = CXXNewExpr::ListInit;
1064 else {
Sebastian Redle7c31a92012-02-22 09:07:21 +00001065 // In template instantiation, the initializer could be a CXXDefaultArgExpr
1066 // unwrapped from a CXXConstructExpr that was implicitly built. There is no
1067 // particularly sane way we can handle this (especially since it can even
1068 // occur for array new), so we throw the initializer away and have it be
1069 // rebuilt.
1070 if (Initializer && isa<CXXDefaultArgExpr>(Initializer))
1071 Initializer = 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001072 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1073 isa<CXXConstructExpr>(Initializer)) &&
1074 "Initializer expression that cannot have been implicitly created.");
1075 initStyle = CXXNewExpr::NoInit;
1076 }
1077
1078 Expr **Inits = &Initializer;
1079 unsigned NumInits = Initializer ? 1 : 0;
1080 if (initStyle == CXXNewExpr::CallInit) {
1081 if (ParenListExpr *List = dyn_cast<ParenListExpr>(Initializer)) {
1082 Inits = List->getExprs();
1083 NumInits = List->getNumExprs();
1084 } else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Initializer)){
1085 if (!isa<CXXTemporaryObjectExpr>(CCE)) {
1086 // Can happen in template instantiation. Since this is just an implicit
1087 // construction, we just take it apart and rebuild it.
1088 Inits = CCE->getArgs();
1089 NumInits = CCE->getNumArgs();
1090 }
1091 }
1092 }
1093
Richard Smith30482bc2011-02-20 03:19:35 +00001094 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1095 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001096 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001097 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1098 << AllocType << TypeRange);
Sebastian Redl6047f072012-02-16 12:22:20 +00001099 if (initStyle == CXXNewExpr::ListInit)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001100 return ExprError(Diag(Inits[0]->getLocStart(),
Sebastian Redl6047f072012-02-16 12:22:20 +00001101 diag::err_auto_new_requires_parens)
1102 << AllocType << TypeRange);
1103 if (NumInits > 1) {
1104 Expr *FirstBad = Inits[1];
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001105 return ExprError(Diag(FirstBad->getLocStart(),
Richard Smith30482bc2011-02-20 03:19:35 +00001106 diag::err_auto_new_ctor_multiple_expressions)
1107 << AllocType << TypeRange);
1108 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001109 Expr *Deduce = Inits[0];
Richard Smith9647d3c2011-03-17 16:11:59 +00001110 TypeSourceInfo *DeducedType = 0;
Sebastian Redld74dd492012-02-12 18:41:05 +00001111 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00001112 DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001113 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redld74dd492012-02-12 18:41:05 +00001114 << AllocType << Deduce->getType()
1115 << TypeRange << Deduce->getSourceRange());
Richard Smith9647d3c2011-03-17 16:11:59 +00001116 if (!DeducedType)
1117 return ExprError();
Richard Smith30482bc2011-02-20 03:19:35 +00001118
Richard Smith9647d3c2011-03-17 16:11:59 +00001119 AllocTypeInfo = DeducedType;
1120 AllocType = AllocTypeInfo->getType();
Richard Smith30482bc2011-02-20 03:19:35 +00001121 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001122
Douglas Gregorcda95f42010-05-16 16:01:03 +00001123 // Per C++0x [expr.new]p5, the type being constructed may be a
1124 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001125 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001126 if (const ConstantArrayType *Array
1127 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001128 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1129 Context.getSizeType(),
1130 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001131 AllocType = Array->getElementType();
1132 }
1133 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001134
Douglas Gregor3999e152010-10-06 16:00:31 +00001135 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1136 return ExprError();
1137
Sebastian Redl6047f072012-02-16 12:22:20 +00001138 if (initStyle == CXXNewExpr::ListInit && isStdInitializerList(AllocType, 0)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001139 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1140 diag::warn_dangling_std_initializer_list)
Sebastian Redl73cfbeb2012-02-19 16:31:05 +00001141 << /*at end of FE*/0 << Inits[0]->getSourceRange();
Sebastian Redld74dd492012-02-12 18:41:05 +00001142 }
1143
John McCall31168b02011-06-15 23:02:42 +00001144 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001145 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001146 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1147 AllocType->isObjCLifetimeType()) {
1148 AllocType = Context.getLifetimeQualifiedType(AllocType,
1149 AllocType->getObjCARCImplicitLifetime());
1150 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001151
John McCall31168b02011-06-15 23:02:42 +00001152 QualType ResultType = Context.getPointerType(AllocType);
1153
Richard Smith8dd34252012-02-04 07:07:42 +00001154 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1155 // integral or enumeration type with a non-negative value."
1156 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1157 // enumeration type, or a class type for which a single non-explicit
1158 // conversion function to integral or unscoped enumeration type exists.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001159 if (ArraySize && !ArraySize->isTypeDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00001160 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1161 Expr *ArraySize;
1162
1163 public:
1164 SizeConvertDiagnoser(Expr *ArraySize)
1165 : ICEConvertDiagnoser(false, false), ArraySize(ArraySize) { }
1166
1167 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1168 QualType T) {
1169 return S.Diag(Loc, diag::err_array_size_not_integral)
1170 << S.getLangOpts().CPlusPlus0x << T;
1171 }
1172
1173 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
1174 QualType T) {
1175 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1176 << T << ArraySize->getSourceRange();
1177 }
1178
1179 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
1180 SourceLocation Loc,
1181 QualType T,
1182 QualType ConvTy) {
1183 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1184 }
1185
1186 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
1187 CXXConversionDecl *Conv,
1188 QualType ConvTy) {
1189 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1190 << ConvTy->isEnumeralType() << ConvTy;
1191 }
1192
1193 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
1194 QualType T) {
1195 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1196 }
1197
1198 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
1199 QualType ConvTy) {
1200 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1201 << ConvTy->isEnumeralType() << ConvTy;
1202 }
1203
1204 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1205 QualType T,
1206 QualType ConvTy) {
1207 return S.Diag(Loc,
1208 S.getLangOpts().CPlusPlus0x
1209 ? diag::warn_cxx98_compat_array_size_conversion
1210 : diag::ext_array_size_conversion)
1211 << T << ConvTy->isEnumeralType() << ConvTy;
1212 }
1213 } SizeDiagnoser(ArraySize);
1214
1215 ExprResult ConvertedSize
1216 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize, SizeDiagnoser,
1217 /*AllowScopedEnumerations*/ false);
Douglas Gregor4799d032010-06-30 00:20:43 +00001218 if (ConvertedSize.isInvalid())
1219 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001220
John McCallb268a282010-08-23 23:25:46 +00001221 ArraySize = ConvertedSize.take();
John McCall9b80c212012-01-11 00:14:46 +00001222 QualType SizeType = ArraySize->getType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00001223 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001224 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001225
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001226 // C++98 [expr.new]p7:
1227 // The expression in a direct-new-declarator shall have integral type
1228 // with a non-negative value.
1229 //
1230 // Let's see if this is a constant < 0. If so, we reject it out of
1231 // hand. Otherwise, if it's not a constant, we must have an unparenthesized
1232 // array type.
1233 //
1234 // Note: such a construct has well-defined semantics in C++11: it throws
1235 // std::bad_array_new_length.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001236 if (!ArraySize->isValueDependent()) {
1237 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00001238 // We've already performed any required implicit conversion to integer or
1239 // unscoped enumeration type.
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001240 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001241 if (Value < llvm::APSInt(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001242 llvm::APInt::getNullValue(Value.getBitWidth()),
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001243 Value.isUnsigned())) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001244 if (getLangOpts().CPlusPlus0x)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001245 Diag(ArraySize->getLocStart(),
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001246 diag::warn_typecheck_negative_array_new_size)
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001247 << ArraySize->getSourceRange();
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001248 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001249 return ExprError(Diag(ArraySize->getLocStart(),
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001250 diag::err_typecheck_negative_array_size)
1251 << ArraySize->getSourceRange());
1252 } else if (!AllocType->isDependentType()) {
1253 unsigned ActiveSizeBits =
1254 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1255 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001256 if (getLangOpts().CPlusPlus0x)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001257 Diag(ArraySize->getLocStart(),
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001258 diag::warn_array_new_too_large)
1259 << Value.toString(10)
1260 << ArraySize->getSourceRange();
1261 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001262 return ExprError(Diag(ArraySize->getLocStart(),
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001263 diag::err_array_too_large)
1264 << Value.toString(10)
1265 << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001266 }
1267 }
Douglas Gregorf2753b32010-07-13 15:54:32 +00001268 } else if (TypeIdParens.isValid()) {
1269 // Can't have dynamic array size when the type-id is in parentheses.
1270 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1271 << ArraySize->getSourceRange()
1272 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1273 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001274
Douglas Gregorf2753b32010-07-13 15:54:32 +00001275 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001276 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001277 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001278
John McCall31168b02011-06-15 23:02:42 +00001279 // ARC: warn about ABI issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001280 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001281 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1282 if (BaseAllocType.hasStrongOrWeakObjCLifetime())
1283 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1284 << 0 << BaseAllocType;
1285 }
1286
John McCall036f2f62011-05-15 07:14:44 +00001287 // Note that we do *not* convert the argument in any way. It can
1288 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00001289 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001290
Sebastian Redlbd150f42008-11-21 19:14:01 +00001291 FunctionDecl *OperatorNew = 0;
1292 FunctionDecl *OperatorDelete = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001293 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
1294 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001295
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001296 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001297 !Expr::hasAnyTypeDependentArguments(
1298 llvm::makeArrayRef(PlaceArgs, NumPlaceArgs)) &&
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001299 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001300 SourceRange(PlacementLParen, PlacementRParen),
1301 UseGlobal, AllocType, ArraySize, PlaceArgs,
1302 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001303 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00001304
1305 // If this is an array allocation, compute whether the usual array
1306 // deallocation function for the type has a size_t parameter.
1307 bool UsualArrayDeleteWantsSize = false;
1308 if (ArraySize && !AllocType->isDependentType())
1309 UsualArrayDeleteWantsSize
1310 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1311
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001312 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001313 if (OperatorNew) {
1314 // Add default arguments, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001315 const FunctionProtoType *Proto =
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001316 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001317 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00001318 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001319
Anders Carlssonc144bc22010-05-03 02:07:56 +00001320 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001321 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlssonc144bc22010-05-03 02:07:56 +00001322 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001323 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001324
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001325 NumPlaceArgs = AllPlaceArgs.size();
1326 if (NumPlaceArgs > 0)
1327 PlaceArgs = &AllPlaceArgs[0];
Eli Friedmanff4b4072012-02-18 04:48:30 +00001328
1329 DiagnoseSentinelCalls(OperatorNew, PlacementLParen,
1330 PlaceArgs, NumPlaceArgs);
1331
1332 // FIXME: Missing call to CheckFunctionCall or equivalent
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001333 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001334
Nick Lewycky411fc652012-01-24 21:15:41 +00001335 // Warn if the type is over-aligned and is being allocated by global operator
1336 // new.
Nick Lewycky96ed7b62012-02-04 03:30:14 +00001337 if (NumPlaceArgs == 0 && OperatorNew &&
Nick Lewycky411fc652012-01-24 21:15:41 +00001338 (OperatorNew->isImplicit() ||
1339 getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) {
1340 if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
1341 unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
1342 if (Align > SuitableAlign)
1343 Diag(StartLoc, diag::warn_overaligned_type)
1344 << AllocType
1345 << unsigned(Align / Context.getCharWidth())
1346 << unsigned(SuitableAlign / Context.getCharWidth());
1347 }
1348 }
1349
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001350 QualType InitType = AllocType;
Sebastian Redl6047f072012-02-16 12:22:20 +00001351 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001352 // Initializer lists are also allowed, in C++11. Rely on the parser for the
1353 // dialect distinction.
1354 if (ResultType->isArrayType() || ArraySize) {
1355 if (!isLegalArrayNewInitializer(initStyle, Initializer)) {
1356 SourceRange InitRange(Inits[0]->getLocStart(),
1357 Inits[NumInits - 1]->getLocEnd());
1358 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1359 return ExprError();
1360 }
1361 if (InitListExpr *ILE = dyn_cast_or_null<InitListExpr>(Initializer)) {
1362 // We do the initialization typechecking against the array type
1363 // corresponding to the number of initializers + 1 (to also check
1364 // default-initialization).
1365 unsigned NumElements = ILE->getNumInits() + 1;
1366 InitType = Context.getConstantArrayType(AllocType,
1367 llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumElements),
1368 ArrayType::Normal, 0);
1369 }
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001370 }
1371
Douglas Gregor85dabae2009-12-16 01:38:02 +00001372 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001373 !Expr::hasAnyTypeDependentArguments(
1374 llvm::makeArrayRef(Inits, NumInits))) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001375 // C++11 [expr.new]p15:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001376 // A new-expression that creates an object of type T initializes that
1377 // object as follows:
1378 InitializationKind Kind
1379 // - If the new-initializer is omitted, the object is default-
1380 // initialized (8.5); if no initialization is performed,
1381 // the object has indeterminate value
Sebastian Redl6047f072012-02-16 12:22:20 +00001382 = initStyle == CXXNewExpr::NoInit
1383 ? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001384 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor85dabae2009-12-16 01:38:02 +00001385 // initialization rules of 8.5 for direct-initialization.
Sebastian Redl6047f072012-02-16 12:22:20 +00001386 : initStyle == CXXNewExpr::ListInit
1387 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1388 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1389 DirectInitRange.getBegin(),
1390 DirectInitRange.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001391
Douglas Gregor85dabae2009-12-16 01:38:02 +00001392 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001393 = InitializedEntity::InitializeNew(StartLoc, InitType);
Sebastian Redl6047f072012-02-16 12:22:20 +00001394 InitializationSequence InitSeq(*this, Entity, Kind, Inits, NumInits);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001395 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00001396 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00001397 if (FullInit.isInvalid())
1398 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001399
Sebastian Redl6047f072012-02-16 12:22:20 +00001400 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1401 // we don't want the initialized object to be destructed.
1402 if (CXXBindTemporaryExpr *Binder =
1403 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
1404 FullInit = Owned(Binder->getSubExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001405
Sebastian Redl6047f072012-02-16 12:22:20 +00001406 Initializer = FullInit.take();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001407 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001408
Douglas Gregor6642ca22010-02-26 05:06:18 +00001409 // Mark the new and delete operators as referenced.
1410 if (OperatorNew)
Eli Friedmanfa0df832012-02-02 03:46:19 +00001411 MarkFunctionReferenced(StartLoc, OperatorNew);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001412 if (OperatorDelete)
Eli Friedmanfa0df832012-02-02 03:46:19 +00001413 MarkFunctionReferenced(StartLoc, OperatorDelete);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001414
John McCall928a2572011-07-13 20:12:57 +00001415 // C++0x [expr.new]p17:
1416 // If the new expression creates an array of objects of class type,
1417 // access and ambiguity control are done for the destructor.
David Blaikie631a4862012-03-10 23:40:02 +00001418 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1419 if (ArraySize && !BaseAllocType->isDependentType()) {
1420 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
1421 if (CXXDestructorDecl *dtor = LookupDestructor(
1422 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
1423 MarkFunctionReferenced(StartLoc, dtor);
1424 CheckDestructorAccess(StartLoc, dtor,
1425 PDiag(diag::err_access_dtor)
1426 << BaseAllocType);
1427 DiagnoseUseOfDecl(dtor, StartLoc);
1428 }
John McCall928a2572011-07-13 20:12:57 +00001429 }
1430 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001431
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001432 PlacementArgs.release();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001433
Ted Kremenek9d6eb402010-02-11 22:51:03 +00001434 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00001435 OperatorDelete,
John McCall284c48f2011-01-27 09:37:56 +00001436 UsualArrayDeleteWantsSize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001437 PlaceArgs, NumPlaceArgs, TypeIdParens,
1438 ArraySize, initStyle, Initializer,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001439 ResultType, AllocTypeInfo,
Sebastian Redl6047f072012-02-16 12:22:20 +00001440 StartLoc, DirectInitRange));
Sebastian Redlbd150f42008-11-21 19:14:01 +00001441}
1442
Sebastian Redl6047f072012-02-16 12:22:20 +00001443/// \brief Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00001444/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00001445bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00001446 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00001447 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1448 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00001449 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00001450 return Diag(Loc, diag::err_bad_new_type)
1451 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00001452 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00001453 return Diag(Loc, diag::err_bad_new_type)
1454 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00001455 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001456 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00001457 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00001458 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00001459 diag::err_allocation_of_abstract_type))
1460 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00001461 else if (AllocType->isVariablyModifiedType())
1462 return Diag(Loc, diag::err_variably_modified_new_type)
1463 << AllocType;
Douglas Gregor39d1a092011-04-15 19:46:20 +00001464 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1465 return Diag(Loc, diag::err_address_space_qualified_new)
1466 << AllocType.getUnqualifiedType() << AddressSpace;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001467 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001468 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1469 QualType BaseAllocType = Context.getBaseElementType(AT);
1470 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1471 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001472 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00001473 << BaseAllocType;
1474 }
1475 }
Douglas Gregor39d1a092011-04-15 19:46:20 +00001476
Sebastian Redlbd150f42008-11-21 19:14:01 +00001477 return false;
1478}
1479
Douglas Gregor6642ca22010-02-26 05:06:18 +00001480/// \brief Determine whether the given function is a non-placement
1481/// deallocation function.
1482static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1483 if (FD->isInvalidDecl())
1484 return false;
1485
1486 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1487 return Method->isUsualDeallocationFunction();
1488
1489 return ((FD->getOverloadedOperator() == OO_Delete ||
1490 FD->getOverloadedOperator() == OO_Array_Delete) &&
1491 FD->getNumParams() == 1);
1492}
1493
Sebastian Redlfaf68082008-12-03 20:26:15 +00001494/// FindAllocationFunctions - Finds the overloads of operator new and delete
1495/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001496bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1497 bool UseGlobal, QualType AllocType,
1498 bool IsArray, Expr **PlaceArgs,
1499 unsigned NumPlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00001500 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +00001501 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001502 // --- Choosing an allocation function ---
1503 // C++ 5.3.4p8 - 14 & 18
1504 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1505 // in the scope of the allocated class.
1506 // 2) If an array size is given, look for operator new[], else look for
1507 // operator new.
1508 // 3) The first argument is always size_t. Append the arguments from the
1509 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00001510
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001511 SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001512 // We don't care about the actual value of this argument.
1513 // FIXME: Should the Sema create the expression and embed it in the syntax
1514 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001515 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00001516 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00001517 Context.getSizeType(),
1518 SourceLocation());
1519 AllocArgs[0] = &Size;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001520 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1521
Douglas Gregor6642ca22010-02-26 05:06:18 +00001522 // C++ [expr.new]p8:
1523 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001524 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00001525 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001526 // type, the allocation function's name is operator new[] and the
1527 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00001528 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1529 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001530 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1531 IsArray ? OO_Array_Delete : OO_Delete);
1532
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001533 QualType AllocElemType = Context.getBaseElementType(AllocType);
1534
1535 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +00001536 CXXRecordDecl *Record
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001537 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001538 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +00001539 AllocArgs.size(), Record, /*AllowMissing=*/true,
1540 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00001541 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001542 }
1543 if (!OperatorNew) {
1544 // Didn't find a member overload. Look for a global one.
1545 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +00001546 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001547 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +00001548 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1549 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00001550 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001551 }
1552
John McCall0f55a032010-04-20 02:18:25 +00001553 // We don't need an operator delete if we're running under
1554 // -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001555 if (!getLangOpts().Exceptions) {
John McCall0f55a032010-04-20 02:18:25 +00001556 OperatorDelete = 0;
1557 return false;
1558 }
1559
Anders Carlsson6f9dabf2009-05-31 20:26:12 +00001560 // FindAllocationOverload can change the passed in arguments, so we need to
1561 // copy them back.
1562 if (NumPlaceArgs > 0)
1563 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001564
Douglas Gregor6642ca22010-02-26 05:06:18 +00001565 // C++ [expr.new]p19:
1566 //
1567 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001568 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00001569 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001570 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00001571 // the scope of T. If this lookup fails to find the name, or if
1572 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001573 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00001574 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001575 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001576 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001577 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00001578 LookupQualifiedName(FoundDelete, RD);
1579 }
John McCallfb6f5262010-03-18 08:19:33 +00001580 if (FoundDelete.isAmbiguous())
1581 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00001582
1583 if (FoundDelete.empty()) {
1584 DeclareGlobalNewDelete();
1585 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1586 }
1587
1588 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00001589
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001590 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00001591
John McCalld3be2c82010-09-14 21:34:24 +00001592 // Whether we're looking for a placement operator delete is dictated
1593 // by whether we selected a placement operator new, not by whether
1594 // we had explicit placement arguments. This matters for things like
1595 // struct A { void *operator new(size_t, int = 0); ... };
1596 // A *a = new A()
1597 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1598
1599 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001600 // C++ [expr.new]p20:
1601 // A declaration of a placement deallocation function matches the
1602 // declaration of a placement allocation function if it has the
1603 // same number of parameters and, after parameter transformations
1604 // (8.3.5), all parameter types except the first are
1605 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001606 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00001607 // To perform this comparison, we compute the function type that
1608 // the deallocation function should have, and use that type both
1609 // for template argument deduction and for comparison purposes.
John McCalldb40c7f2010-12-14 08:05:40 +00001610 //
1611 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6642ca22010-02-26 05:06:18 +00001612 QualType ExpectedFunctionType;
1613 {
1614 const FunctionProtoType *Proto
1615 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00001616
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001617 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001618 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001619 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1620 ArgTypes.push_back(Proto->getArgType(I));
1621
John McCalldb40c7f2010-12-14 08:05:40 +00001622 FunctionProtoType::ExtProtoInfo EPI;
1623 EPI.Variadic = Proto->isVariadic();
1624
Douglas Gregor6642ca22010-02-26 05:06:18 +00001625 ExpectedFunctionType
1626 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalldb40c7f2010-12-14 08:05:40 +00001627 ArgTypes.size(), EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001628 }
1629
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001630 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001631 DEnd = FoundDelete.end();
1632 D != DEnd; ++D) {
1633 FunctionDecl *Fn = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001634 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6642ca22010-02-26 05:06:18 +00001635 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1636 // Perform template argument deduction to try to match the
1637 // expected function type.
1638 TemplateDeductionInfo Info(Context, StartLoc);
1639 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1640 continue;
1641 } else
1642 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1643
1644 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00001645 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001646 }
1647 } else {
1648 // C++ [expr.new]p20:
1649 // [...] Any non-placement deallocation function matches a
1650 // non-placement allocation function. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001651 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001652 DEnd = FoundDelete.end();
1653 D != DEnd; ++D) {
1654 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1655 if (isNonPlacementDeallocationFunction(Fn))
John McCalla0296f72010-03-19 07:35:19 +00001656 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001657 }
1658 }
1659
1660 // C++ [expr.new]p20:
1661 // [...] If the lookup finds a single matching deallocation
1662 // function, that function will be called; otherwise, no
1663 // deallocation function will be called.
1664 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00001665 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00001666
1667 // C++0x [expr.new]p20:
1668 // If the lookup finds the two-parameter form of a usual
1669 // deallocation function (3.7.4.2) and that function, considered
1670 // as a placement deallocation function, would have been
1671 // selected as a match for the allocation function, the program
1672 // is ill-formed.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001673 if (NumPlaceArgs && getLangOpts().CPlusPlus0x &&
Douglas Gregor6642ca22010-02-26 05:06:18 +00001674 isNonPlacementDeallocationFunction(OperatorDelete)) {
1675 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001676 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001677 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1678 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1679 << DeleteName;
John McCallfb6f5262010-03-18 08:19:33 +00001680 } else {
1681 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCalla0296f72010-03-19 07:35:19 +00001682 Matches[0].first);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001683 }
1684 }
1685
Sebastian Redlfaf68082008-12-03 20:26:15 +00001686 return false;
1687}
1688
Sebastian Redl33a31012008-12-04 22:20:51 +00001689/// FindAllocationOverload - Find an fitting overload for the allocation
1690/// function in the specified scope.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001691bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1692 DeclarationName Name, Expr** Args,
1693 unsigned NumArgs, DeclContext *Ctx,
Alexis Hunt1f69a022011-05-12 22:46:29 +00001694 bool AllowMissing, FunctionDecl *&Operator,
1695 bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00001696 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1697 LookupQualifiedName(R, Ctx);
John McCall9f3059a2009-10-09 21:13:30 +00001698 if (R.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001699 if (AllowMissing || !Diagnose)
Sebastian Redl33a31012008-12-04 22:20:51 +00001700 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +00001701 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001702 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +00001703 }
1704
John McCallfb6f5262010-03-18 08:19:33 +00001705 if (R.isAmbiguous())
1706 return true;
1707
1708 R.suppressDiagnostics();
John McCall9f3059a2009-10-09 21:13:30 +00001709
John McCallbc077cf2010-02-08 23:07:23 +00001710 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001711 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor80a6cc52009-09-30 00:03:47 +00001712 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor55297ac2008-12-23 00:26:44 +00001713 // Even member operator new/delete are implicitly treated as
1714 // static, so don't use AddMemberCandidate.
John McCalla0296f72010-03-19 07:35:19 +00001715 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth93538422010-02-03 11:02:14 +00001716
John McCalla0296f72010-03-19 07:35:19 +00001717 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1718 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001719 /*ExplicitTemplateArgs=*/0,
1720 llvm::makeArrayRef(Args, NumArgs),
Chandler Carruth93538422010-02-03 11:02:14 +00001721 Candidates,
1722 /*SuppressUserConversions=*/false);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001723 continue;
Chandler Carruth93538422010-02-03 11:02:14 +00001724 }
1725
John McCalla0296f72010-03-19 07:35:19 +00001726 FunctionDecl *Fn = cast<FunctionDecl>(D);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001727 AddOverloadCandidate(Fn, Alloc.getPair(),
1728 llvm::makeArrayRef(Args, NumArgs), Candidates,
Chandler Carruth93538422010-02-03 11:02:14 +00001729 /*SuppressUserConversions=*/false);
Sebastian Redl33a31012008-12-04 22:20:51 +00001730 }
1731
1732 // Do the resolution.
1733 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00001734 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001735 case OR_Success: {
1736 // Got one!
1737 FunctionDecl *FnDecl = Best->Function;
Eli Friedmanfa0df832012-02-02 03:46:19 +00001738 MarkFunctionReferenced(StartLoc, FnDecl);
Sebastian Redl33a31012008-12-04 22:20:51 +00001739 // The first argument is size_t, and the first parameter must be size_t,
1740 // too. This is checked on declaration and can be assumed. (It can't be
1741 // asserted on, though, since invalid decls are left in there.)
John McCallfb6f5262010-03-18 08:19:33 +00001742 // Watch out for variadic allocator function.
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001743 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1744 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001745 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1746 FnDecl->getParamDecl(i));
1747
1748 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1749 return true;
1750
John McCalldadc5752010-08-24 06:29:42 +00001751 ExprResult Result
Alexis Hunt1f69a022011-05-12 22:46:29 +00001752 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
Douglas Gregor34147272010-03-26 20:35:59 +00001753 if (Result.isInvalid())
Sebastian Redl33a31012008-12-04 22:20:51 +00001754 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001755
Douglas Gregor34147272010-03-26 20:35:59 +00001756 Args[i] = Result.takeAs<Expr>();
Sebastian Redl33a31012008-12-04 22:20:51 +00001757 }
Richard Smith921bd202012-02-26 09:11:52 +00001758
Sebastian Redl33a31012008-12-04 22:20:51 +00001759 Operator = FnDecl;
Richard Smith921bd202012-02-26 09:11:52 +00001760
1761 if (CheckAllocationAccess(StartLoc, Range, R.getNamingClass(),
1762 Best->FoundDecl, Diagnose) == AR_inaccessible)
1763 return true;
1764
Sebastian Redl33a31012008-12-04 22:20:51 +00001765 return false;
1766 }
1767
1768 case OR_No_Viable_Function:
Chandler Carruthe6c88182011-06-08 10:26:03 +00001769 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001770 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1771 << Name << Range;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001772 Candidates.NoteCandidates(*this, OCD_AllCandidates,
1773 llvm::makeArrayRef(Args, NumArgs));
Chandler Carruthe6c88182011-06-08 10:26:03 +00001774 }
Sebastian Redl33a31012008-12-04 22:20:51 +00001775 return true;
1776
1777 case OR_Ambiguous:
Chandler Carruthe6c88182011-06-08 10:26:03 +00001778 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001779 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1780 << Name << Range;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001781 Candidates.NoteCandidates(*this, OCD_ViableCandidates,
1782 llvm::makeArrayRef(Args, NumArgs));
Chandler Carruthe6c88182011-06-08 10:26:03 +00001783 }
Sebastian Redl33a31012008-12-04 22:20:51 +00001784 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001785
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001786 case OR_Deleted: {
Chandler Carruthe6c88182011-06-08 10:26:03 +00001787 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001788 Diag(StartLoc, diag::err_ovl_deleted_call)
1789 << Best->Function->isDeleted()
1790 << Name
1791 << getDeletedOrUnavailableSuffix(Best->Function)
1792 << Range;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001793 Candidates.NoteCandidates(*this, OCD_AllCandidates,
1794 llvm::makeArrayRef(Args, NumArgs));
Chandler Carruthe6c88182011-06-08 10:26:03 +00001795 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00001796 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +00001797 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001798 }
David Blaikie83d382b2011-09-23 05:06:16 +00001799 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Sebastian Redl33a31012008-12-04 22:20:51 +00001800}
1801
1802
Sebastian Redlfaf68082008-12-03 20:26:15 +00001803/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1804/// delete. These are:
1805/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00001806/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00001807/// void* operator new(std::size_t) throw(std::bad_alloc);
1808/// void* operator new[](std::size_t) throw(std::bad_alloc);
1809/// void operator delete(void *) throw();
1810/// void operator delete[](void *) throw();
Sebastian Redl37588092011-03-14 18:08:30 +00001811/// // C++0x:
1812/// void* operator new(std::size_t);
1813/// void* operator new[](std::size_t);
1814/// void operator delete(void *);
1815/// void operator delete[](void *);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001816/// @endcode
Sebastian Redl37588092011-03-14 18:08:30 +00001817/// C++0x operator delete is implicitly noexcept.
Sebastian Redlfaf68082008-12-03 20:26:15 +00001818/// Note that the placement and nothrow forms of new are *not* implicitly
1819/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00001820void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001821 if (GlobalNewDeleteDeclared)
1822 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001823
Douglas Gregor87f54062009-09-15 22:30:29 +00001824 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001825 // [...] The following allocation and deallocation functions (18.4) are
1826 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00001827 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001828 //
Sebastian Redl37588092011-03-14 18:08:30 +00001829 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00001830 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001831 // void* operator new[](std::size_t) throw(std::bad_alloc);
1832 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00001833 // void operator delete[](void*) throw();
Sebastian Redl37588092011-03-14 18:08:30 +00001834 // C++0x:
1835 // void* operator new(std::size_t);
1836 // void* operator new[](std::size_t);
1837 // void operator delete(void*);
1838 // void operator delete[](void*);
Douglas Gregor87f54062009-09-15 22:30:29 +00001839 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001840 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00001841 // new, operator new[], operator delete, operator delete[].
1842 //
1843 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1844 // "std" or "bad_alloc" as necessary to form the exception specification.
1845 // However, we do not make these implicit declarations visible to name
1846 // lookup.
Sebastian Redl37588092011-03-14 18:08:30 +00001847 // Note that the C++0x versions of operator delete are deallocation functions,
1848 // and thus are implicitly noexcept.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001849 if (!StdBadAlloc && !getLangOpts().CPlusPlus0x) {
Douglas Gregor87f54062009-09-15 22:30:29 +00001850 // The "std::bad_alloc" class has not yet been declared, so build it
1851 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001852 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1853 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001854 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001855 &PP.getIdentifierTable().get("bad_alloc"),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001856 0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001857 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00001858 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001859
Sebastian Redlfaf68082008-12-03 20:26:15 +00001860 GlobalNewDeleteDeclared = true;
1861
1862 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1863 QualType SizeT = Context.getSizeType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001864 bool AssumeSaneOperatorNew = getLangOpts().AssumeSaneOperatorNew;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001865
Sebastian Redlfaf68082008-12-03 20:26:15 +00001866 DeclareGlobalAllocationFunction(
1867 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001868 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001869 DeclareGlobalAllocationFunction(
1870 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001871 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001872 DeclareGlobalAllocationFunction(
1873 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1874 Context.VoidTy, VoidPtr);
1875 DeclareGlobalAllocationFunction(
1876 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1877 Context.VoidTy, VoidPtr);
1878}
1879
1880/// DeclareGlobalAllocationFunction - Declares a single implicit global
1881/// allocation function if it doesn't already exist.
1882void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopes13c88c72009-12-16 16:59:22 +00001883 QualType Return, QualType Argument,
1884 bool AddMallocAttr) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001885 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1886
1887 // Check if this function is already declared.
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001888 {
Douglas Gregor17eb26b2008-12-23 22:05:29 +00001889 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001890 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001891 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth93538422010-02-03 11:02:14 +00001892 // Only look at non-template functions, as it is the predefined,
1893 // non-templated allocation function we are trying to declare here.
1894 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1895 QualType InitialParamType =
Douglas Gregor684d7bd2009-12-22 23:42:49 +00001896 Context.getCanonicalType(
Chandler Carruth93538422010-02-03 11:02:14 +00001897 Func->getParamDecl(0)->getType().getUnqualifiedType());
1898 // FIXME: Do we need to check for default arguments here?
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00001899 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1900 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001901 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth93538422010-02-03 11:02:14 +00001902 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00001903 }
Chandler Carruth93538422010-02-03 11:02:14 +00001904 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00001905 }
1906 }
1907
Douglas Gregor87f54062009-09-15 22:30:29 +00001908 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001909 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00001910 = (Name.getCXXOverloadedOperator() == OO_New ||
1911 Name.getCXXOverloadedOperator() == OO_Array_New);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001912 if (HasBadAllocExceptionSpec && !getLangOpts().CPlusPlus0x) {
Douglas Gregor87f54062009-09-15 22:30:29 +00001913 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001914 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +00001915 }
John McCalldb40c7f2010-12-14 08:05:40 +00001916
1917 FunctionProtoType::ExtProtoInfo EPI;
John McCalldb40c7f2010-12-14 08:05:40 +00001918 if (HasBadAllocExceptionSpec) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001919 if (!getLangOpts().CPlusPlus0x) {
Sebastian Redl37588092011-03-14 18:08:30 +00001920 EPI.ExceptionSpecType = EST_Dynamic;
1921 EPI.NumExceptions = 1;
1922 EPI.Exceptions = &BadAllocType;
1923 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001924 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001925 EPI.ExceptionSpecType = getLangOpts().CPlusPlus0x ?
Sebastian Redl37588092011-03-14 18:08:30 +00001926 EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00001927 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001928
John McCalldb40c7f2010-12-14 08:05:40 +00001929 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001930 FunctionDecl *Alloc =
Abramo Bagnaradff19302011-03-08 08:55:46 +00001931 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1932 SourceLocation(), Name,
John McCall8e7d6562010-08-26 03:08:43 +00001933 FnType, /*TInfo=*/0, SC_None,
1934 SC_None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001935 Alloc->setImplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001936
Nuno Lopes13c88c72009-12-16 16:59:22 +00001937 if (AddMallocAttr)
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001938 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001939
Sebastian Redlfaf68082008-12-03 20:26:15 +00001940 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001941 SourceLocation(), 0,
1942 Argument, /*TInfo=*/0,
1943 SC_None, SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00001944 Alloc->setParams(Param);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001945
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001946 // FIXME: Also add this declaration to the IdentifierResolver, but
1947 // make sure it is at the end of the chain to coincide with the
1948 // global scope.
John McCallcc14d1f2010-08-24 08:50:51 +00001949 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001950}
1951
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001952bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1953 DeclarationName Name,
Alexis Hunt1f69a022011-05-12 22:46:29 +00001954 FunctionDecl* &Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00001955 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001956 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00001957 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001958
John McCall27b18f82009-11-17 02:14:36 +00001959 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001960 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001961
Chandler Carruthb6f99172010-06-28 00:30:51 +00001962 Found.suppressDiagnostics();
1963
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001964 SmallVector<DeclAccessPair,4> Matches;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001965 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1966 F != FEnd; ++F) {
Chandler Carruth9b418232010-08-08 07:04:00 +00001967 NamedDecl *ND = (*F)->getUnderlyingDecl();
1968
1969 // Ignore template operator delete members from the check for a usual
1970 // deallocation function.
1971 if (isa<FunctionTemplateDecl>(ND))
1972 continue;
1973
1974 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall66a87592010-08-04 00:31:26 +00001975 Matches.push_back(F.getPair());
1976 }
1977
1978 // There's exactly one suitable operator; pick it.
1979 if (Matches.size() == 1) {
1980 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
Alexis Hunt1f69a022011-05-12 22:46:29 +00001981
1982 if (Operator->isDeleted()) {
1983 if (Diagnose) {
1984 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00001985 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00001986 }
1987 return true;
1988 }
1989
Richard Smith921bd202012-02-26 09:11:52 +00001990 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1991 Matches[0], Diagnose) == AR_inaccessible)
1992 return true;
1993
John McCall66a87592010-08-04 00:31:26 +00001994 return false;
1995
1996 // We found multiple suitable operators; complain about the ambiguity.
1997 } else if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001998 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00001999 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2000 << Name << RD;
John McCall66a87592010-08-04 00:31:26 +00002001
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002002 for (SmallVectorImpl<DeclAccessPair>::iterator
Alexis Huntf91729462011-05-12 22:46:25 +00002003 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
2004 Diag((*F)->getUnderlyingDecl()->getLocation(),
2005 diag::note_member_declared_here) << Name;
2006 }
John McCall66a87592010-08-04 00:31:26 +00002007 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002008 }
2009
2010 // We did find operator delete/operator delete[] declarations, but
2011 // none of them were suitable.
2012 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002013 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002014 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2015 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002016
Alexis Huntf91729462011-05-12 22:46:25 +00002017 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
2018 F != FEnd; ++F)
2019 Diag((*F)->getUnderlyingDecl()->getLocation(),
2020 diag::note_member_declared_here) << Name;
2021 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002022 return true;
2023 }
2024
2025 // Look for a global declaration.
2026 DeclareGlobalNewDelete();
2027 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002028
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002029 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
2030 Expr* DeallocArgs[1];
2031 DeallocArgs[0] = &Null;
2032 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
Alexis Hunt1f69a022011-05-12 22:46:29 +00002033 DeallocArgs, 1, TUDecl, !Diagnose,
2034 Operator, Diagnose))
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002035 return true;
2036
2037 assert(Operator && "Did not find a deallocation function!");
2038 return false;
2039}
2040
Sebastian Redlbd150f42008-11-21 19:14:01 +00002041/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
2042/// @code ::delete ptr; @endcode
2043/// or
2044/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00002045ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00002046Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00002047 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002048 // C++ [expr.delete]p1:
2049 // The operand shall have a pointer type, or a class type having a single
2050 // conversion function to a pointer type. The result has type void.
2051 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00002052 // DR599 amends "pointer type" to "pointer to object type" in both cases.
2053
John Wiegley01296292011-04-08 18:41:53 +00002054 ExprResult Ex = Owned(ExE);
Anders Carlssona471db02009-08-16 20:29:29 +00002055 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00002056 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00002057 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00002058
John Wiegley01296292011-04-08 18:41:53 +00002059 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00002060 // Perform lvalue-to-rvalue cast, if needed.
2061 Ex = DefaultLvalueConversion(Ex.take());
2062
John Wiegley01296292011-04-08 18:41:53 +00002063 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002064
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002065 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002066 if (RequireCompleteType(StartLoc, Type,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002067 diag::err_delete_incomplete_class_type))
Douglas Gregorf65f4902010-07-29 14:44:35 +00002068 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002069
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002070 SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
John McCallda4458e2010-03-31 01:36:47 +00002071
Fariborz Jahanianb54ccb22009-09-11 21:44:33 +00002072 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002073 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002074 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002075 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00002076 NamedDecl *D = I.getDecl();
2077 if (isa<UsingShadowDecl>(D))
2078 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2079
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002080 // Skip over templated conversion functions; they aren't considered.
John McCallda4458e2010-03-31 01:36:47 +00002081 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002082 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002083
John McCallda4458e2010-03-31 01:36:47 +00002084 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002085
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002086 QualType ConvType = Conv->getConversionType().getNonReferenceType();
2087 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00002088 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanianadcea102009-09-15 22:15:23 +00002089 ObjectPtrConversions.push_back(Conv);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002090 }
Fariborz Jahanianadcea102009-09-15 22:15:23 +00002091 if (ObjectPtrConversions.size() == 1) {
2092 // We have a single conversion to a pointer-to-object type. Perform
2093 // that conversion.
John McCallda4458e2010-03-31 01:36:47 +00002094 // TODO: don't redo the conversion calculation.
John Wiegley01296292011-04-08 18:41:53 +00002095 ExprResult Res =
2096 PerformImplicitConversion(Ex.get(),
John McCallda4458e2010-03-31 01:36:47 +00002097 ObjectPtrConversions.front()->getConversionType(),
John Wiegley01296292011-04-08 18:41:53 +00002098 AA_Converting);
2099 if (Res.isUsable()) {
2100 Ex = move(Res);
2101 Type = Ex.get()->getType();
Fariborz Jahanianadcea102009-09-15 22:15:23 +00002102 }
2103 }
2104 else if (ObjectPtrConversions.size() > 1) {
2105 Diag(StartLoc, diag::err_ambiguous_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00002106 << Type << Ex.get()->getSourceRange();
John McCallda4458e2010-03-31 01:36:47 +00002107 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
2108 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanianadcea102009-09-15 22:15:23 +00002109 return ExprError();
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002110 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002111 }
2112
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002113 if (!Type->isPointerType())
2114 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00002115 << Type << Ex.get()->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002116
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002117 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00002118 QualType PointeeElem = Context.getBaseElementType(Pointee);
2119
2120 if (unsigned AddressSpace = Pointee.getAddressSpace())
2121 return Diag(Ex.get()->getLocStart(),
2122 diag::err_address_space_qualified_delete)
2123 << Pointee.getUnqualifiedType() << AddressSpace;
2124
2125 CXXRecordDecl *PointeeRD = 0;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00002126 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002127 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00002128 // effectively bans deletion of "void*". However, most compilers support
2129 // this, so we treat it as a warning unless we're in a SFINAE context.
2130 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00002131 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00002132 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002133 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00002134 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00002135 } else if (!Pointee->isDependentType()) {
2136 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002137 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00002138 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
2139 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
2140 }
2141 }
2142
Douglas Gregor98496dc2009-09-29 21:38:53 +00002143 // C++ [expr.delete]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002144 // [Note: a pointer to a const type can be the operand of a
2145 // delete-expression; it is not necessary to cast away the constness
2146 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor98496dc2009-09-29 21:38:53 +00002147 // of the delete-expression. ]
John McCall31168b02011-06-15 23:02:42 +00002148 if (!Context.hasSameType(Ex.get()->getType(), Context.VoidPtrTy))
Abramo Bagnarad4756b92011-11-16 15:42:13 +00002149 Ex = Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy,
2150 CK_BitCast, Ex.take(), 0, VK_RValue));
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00002151
2152 if (Pointee->isArrayType() && !ArrayForm) {
2153 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00002154 << Type << Ex.get()->getSourceRange()
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00002155 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
2156 ArrayForm = true;
2157 }
2158
Anders Carlssona471db02009-08-16 20:29:29 +00002159 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2160 ArrayForm ? OO_Array_Delete : OO_Delete);
2161
Eli Friedmanae4280f2011-07-26 22:25:31 +00002162 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002163 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00002164 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
2165 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00002166 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002167
John McCall284c48f2011-01-27 09:37:56 +00002168 // If we're allocating an array of records, check whether the
2169 // usual operator delete[] has a size_t parameter.
2170 if (ArrayForm) {
2171 // If the user specifically asked to use the global allocator,
2172 // we'll need to do the lookup into the class.
2173 if (UseGlobal)
2174 UsualArrayDeleteWantsSize =
2175 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
2176
2177 // Otherwise, the usual operator delete[] should be the
2178 // function we just found.
2179 else if (isa<CXXMethodDecl>(OperatorDelete))
2180 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
2181 }
2182
Richard Smitheec915d62012-02-18 04:13:32 +00002183 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00002184 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00002185 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002186 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002187 DiagnoseUseOfDecl(Dtor, StartLoc);
2188 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00002189
2190 // C++ [expr.delete]p3:
2191 // In the first alternative (delete object), if the static type of the
2192 // object to be deleted is different from its dynamic type, the static
2193 // type shall be a base class of the dynamic type of the object to be
2194 // deleted and the static type shall have a virtual destructor or the
2195 // behavior is undefined.
2196 //
2197 // Note: a final class cannot be derived from, no issue there
Eli Friedman1b71a222011-07-26 23:27:24 +00002198 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00002199 CXXDestructorDecl *dtor = PointeeRD->getDestructor();
Eli Friedman1b71a222011-07-26 23:27:24 +00002200 if (dtor && !dtor->isVirtual()) {
2201 if (PointeeRD->isAbstract()) {
2202 // If the class is abstract, we warn by default, because we're
2203 // sure the code has undefined behavior.
2204 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
2205 << PointeeElem;
2206 } else if (!ArrayForm) {
2207 // Otherwise, if this is not an array delete, it's a bit suspect,
2208 // but not necessarily wrong.
2209 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
2210 }
2211 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00002212 }
John McCall31168b02011-06-15 23:02:42 +00002213
David Blaikiebbafb8a2012-03-11 07:00:24 +00002214 } else if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002215 PointeeElem->isObjCLifetimeType() &&
2216 (PointeeElem.getObjCLifetime() == Qualifiers::OCL_Strong ||
2217 PointeeElem.getObjCLifetime() == Qualifiers::OCL_Weak) &&
2218 ArrayForm) {
2219 Diag(StartLoc, diag::warn_err_new_delete_object_array)
2220 << 1 << PointeeElem;
Anders Carlssona471db02009-08-16 20:29:29 +00002221 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002222
Anders Carlssona471db02009-08-16 20:29:29 +00002223 if (!OperatorDelete) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002224 // Look for a global declaration.
Anders Carlssona471db02009-08-16 20:29:29 +00002225 DeclareGlobalNewDelete();
2226 DeclContext *TUDecl = Context.getTranslationUnitDecl();
John Wiegley01296292011-04-08 18:41:53 +00002227 Expr *Arg = Ex.get();
Mike Stump11289f42009-09-09 15:08:12 +00002228 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
John Wiegley01296292011-04-08 18:41:53 +00002229 &Arg, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssona471db02009-08-16 20:29:29 +00002230 OperatorDelete))
2231 return ExprError();
2232 }
Mike Stump11289f42009-09-09 15:08:12 +00002233
Eli Friedmanfa0df832012-02-02 03:46:19 +00002234 MarkFunctionReferenced(StartLoc, OperatorDelete);
John McCall284c48f2011-01-27 09:37:56 +00002235
Douglas Gregorfa778132011-02-01 15:50:11 +00002236 // Check access and ambiguity of operator delete and destructor.
Eli Friedmanae4280f2011-07-26 22:25:31 +00002237 if (PointeeRD) {
2238 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
John Wiegley01296292011-04-08 18:41:53 +00002239 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregorfa778132011-02-01 15:50:11 +00002240 PDiag(diag::err_access_dtor) << PointeeElem);
2241 }
2242 }
2243
Sebastian Redlbd150f42008-11-21 19:14:01 +00002244 }
2245
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002246 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall284c48f2011-01-27 09:37:56 +00002247 ArrayFormAsWritten,
2248 UsualArrayDeleteWantsSize,
John Wiegley01296292011-04-08 18:41:53 +00002249 OperatorDelete, Ex.take(), StartLoc));
Sebastian Redlbd150f42008-11-21 19:14:01 +00002250}
2251
Douglas Gregor633caca2009-11-23 23:44:04 +00002252/// \brief Check the use of the given variable as a C++ condition in an if,
2253/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00002254ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00002255 SourceLocation StmtLoc,
2256 bool ConvertToBoolean) {
Douglas Gregor633caca2009-11-23 23:44:04 +00002257 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002258
Douglas Gregor633caca2009-11-23 23:44:04 +00002259 // C++ [stmt.select]p2:
2260 // The declarator shall not specify a function or an array.
2261 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002262 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00002263 diag::err_invalid_use_of_function_type)
2264 << ConditionVar->getSourceRange());
2265 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002266 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00002267 diag::err_invalid_use_of_array_type)
2268 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00002269
John Wiegley01296292011-04-08 18:41:53 +00002270 ExprResult Condition =
Abramo Bagnara7945c982012-01-27 09:46:47 +00002271 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2272 SourceLocation(),
2273 ConditionVar,
John McCall113bee02012-03-10 09:33:50 +00002274 /*enclosing*/ false,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002275 ConditionVar->getLocation(),
2276 ConditionVar->getType().getNonReferenceType(),
John Wiegley01296292011-04-08 18:41:53 +00002277 VK_LValue));
Eli Friedman2dfa7932012-01-16 21:00:51 +00002278
Eli Friedmanfa0df832012-02-02 03:46:19 +00002279 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedman2dfa7932012-01-16 21:00:51 +00002280
John Wiegley01296292011-04-08 18:41:53 +00002281 if (ConvertToBoolean) {
2282 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
2283 if (Condition.isInvalid())
2284 return ExprError();
2285 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002286
John Wiegley01296292011-04-08 18:41:53 +00002287 return move(Condition);
Douglas Gregor633caca2009-11-23 23:44:04 +00002288}
2289
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00002290/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley01296292011-04-08 18:41:53 +00002291ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00002292 // C++ 6.4p4:
2293 // The value of a condition that is an initialized declaration in a statement
2294 // other than a switch statement is the value of the declared variable
2295 // implicitly converted to type bool. If that conversion is ill-formed, the
2296 // program is ill-formed.
2297 // The value of a condition that is an expression is the value of the
2298 // expression, implicitly converted to bool.
2299 //
Douglas Gregor5fb53972009-01-14 15:45:31 +00002300 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00002301}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002302
2303/// Helper function to determine whether this is the (deprecated) C++
2304/// conversion from a string literal to a pointer to non-const char or
2305/// non-const wchar_t (for narrow and wide string literals,
2306/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00002307bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002308Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2309 // Look inside the implicit cast, if it exists.
2310 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2311 From = Cast->getSubExpr();
2312
2313 // A string literal (2.13.4) that is not a wide string literal can
2314 // be converted to an rvalue of type "pointer to char"; a wide
2315 // string literal can be converted to an rvalue of type "pointer
2316 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00002317 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002318 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00002319 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00002320 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002321 // This conversion is considered only when there is an
2322 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00002323 if (!ToPtrType->getPointeeType().hasQualifiers()) {
2324 switch (StrLit->getKind()) {
2325 case StringLiteral::UTF8:
2326 case StringLiteral::UTF16:
2327 case StringLiteral::UTF32:
2328 // We don't allow UTF literals to be implicitly converted
2329 break;
2330 case StringLiteral::Ascii:
2331 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2332 ToPointeeType->getKind() == BuiltinType::Char_S);
2333 case StringLiteral::Wide:
2334 return ToPointeeType->isWideCharType();
2335 }
2336 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002337 }
2338
2339 return false;
2340}
Douglas Gregor39c16d42008-10-24 04:54:22 +00002341
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002342static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00002343 SourceLocation CastLoc,
2344 QualType Ty,
2345 CastKind Kind,
2346 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00002347 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002348 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00002349 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00002350 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002351 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00002352 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00002353 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
John McCall37ad5512010-08-23 06:44:23 +00002354 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002355
Douglas Gregorc7a31072011-10-10 22:41:00 +00002356 if (S.CompleteConstructorCall(Constructor,
John McCallfaf5fb42010-08-26 23:41:50 +00002357 MultiExprArg(&From, 1),
Douglas Gregora4253922010-04-16 22:17:36 +00002358 CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00002359 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002360
John McCall5dadb652012-04-07 03:04:20 +00002361 S.CheckConstructorAccess(CastLoc, Constructor,
2362 InitializedEntity::InitializeTemporary(Ty),
2363 Constructor->getAccess());
Douglas Gregorc7a31072011-10-10 22:41:00 +00002364
2365 ExprResult Result
2366 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2367 move_arg(ConstructorArgs),
2368 HadMultipleCandidates, /*ZeroInit*/ false,
2369 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00002370 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00002371 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002372
Douglas Gregora4253922010-04-16 22:17:36 +00002373 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2374 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002375
John McCalle3027922010-08-25 11:45:40 +00002376 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00002377 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002378
Douglas Gregora4253922010-04-16 22:17:36 +00002379 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00002380 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
2381 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002382 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00002383 if (Result.isInvalid())
2384 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00002385 // Record usage of conversion in an implicit cast.
2386 Result = S.Owned(ImplicitCastExpr::Create(S.Context,
2387 Result.get()->getType(),
2388 CK_UserDefinedConversion,
2389 Result.get(), 0,
2390 Result.get()->getValueKind()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002391
John McCall30909032011-09-21 08:36:56 +00002392 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2393
Douglas Gregor668443e2011-01-20 00:18:04 +00002394 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00002395 }
2396 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002397}
Douglas Gregora4253922010-04-16 22:17:36 +00002398
Douglas Gregor5fb53972009-01-14 15:45:31 +00002399/// PerformImplicitConversion - Perform an implicit conversion of the
2400/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00002401/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002402/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002403/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00002404ExprResult
2405Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002406 const ImplicitConversionSequence &ICS,
John McCall31168b02011-06-15 23:02:42 +00002407 AssignmentAction Action,
2408 CheckedConversionKind CCK) {
John McCall0d1da222010-01-12 00:44:57 +00002409 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00002410 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00002411 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2412 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00002413 if (Res.isInvalid())
2414 return ExprError();
2415 From = Res.take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002416 break;
John Wiegley01296292011-04-08 18:41:53 +00002417 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002418
Anders Carlsson110b07b2009-09-15 06:28:28 +00002419 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002420
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00002421 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00002422 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00002423 QualType BeforeToType;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002424 assert(FD && "FIXME: aggregate initialization from init list");
Anders Carlsson110b07b2009-09-15 06:28:28 +00002425 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00002426 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002427
Anders Carlsson110b07b2009-09-15 06:28:28 +00002428 // If the user-defined conversion is specified by a conversion function,
2429 // the initial standard conversion sequence converts the source type to
2430 // the implicit object parameter of the conversion function.
2431 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00002432 } else {
2433 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00002434 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002435 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00002436 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002437 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian55824512009-11-06 00:23:08 +00002438 // initial standard conversion sequence converts the source type to the
2439 // type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00002440 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2441 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002442 }
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00002443 // Watch out for elipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00002444 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00002445 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00002446 PerformImplicitConversion(From, BeforeToType,
2447 ICS.UserDefined.Before, AA_Converting,
2448 CCK);
John Wiegley01296292011-04-08 18:41:53 +00002449 if (Res.isInvalid())
2450 return ExprError();
2451 From = Res.take();
Fariborz Jahanian55824512009-11-06 00:23:08 +00002452 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002453
2454 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00002455 = BuildCXXCastArgument(*this,
2456 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00002457 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002458 CastKind, cast<CXXMethodDecl>(FD),
2459 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002460 ICS.UserDefined.HadMultipleCandidates,
John McCallb268a282010-08-23 23:25:46 +00002461 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00002462
2463 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00002464 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00002465
John Wiegley01296292011-04-08 18:41:53 +00002466 From = CastArg.take();
Eli Friedmane96f1d32009-11-27 04:41:50 +00002467
Richard Smith507840d2011-11-29 22:48:16 +00002468 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2469 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00002470 }
John McCall0d1da222010-01-12 00:44:57 +00002471
2472 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00002473 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00002474 PDiag(diag::err_typecheck_ambiguous_condition)
2475 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00002476 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002477
Douglas Gregor39c16d42008-10-24 04:54:22 +00002478 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00002479 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002480
2481 case ImplicitConversionSequence::BadConversion:
John Wiegley01296292011-04-08 18:41:53 +00002482 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002483 }
2484
2485 // Everything went well.
John Wiegley01296292011-04-08 18:41:53 +00002486 return Owned(From);
Douglas Gregor39c16d42008-10-24 04:54:22 +00002487}
2488
Richard Smith507840d2011-11-29 22:48:16 +00002489/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00002490/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00002491/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00002492/// expression. Flavor is the context in which we're performing this
2493/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00002494ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00002495Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002496 const StandardConversionSequence& SCS,
John McCall31168b02011-06-15 23:02:42 +00002497 AssignmentAction Action,
2498 CheckedConversionKind CCK) {
2499 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2500
Mike Stump87c57ac2009-05-16 07:39:55 +00002501 // Overall FIXME: we are recomputing too many types here and doing far too
2502 // much extra work. What this means is that we need to keep track of more
2503 // information that is computed when we try the implicit conversion initially,
2504 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00002505 QualType FromType = From->getType();
John McCall31168b02011-06-15 23:02:42 +00002506
Douglas Gregor2fe98832008-11-03 19:09:14 +00002507 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00002508 // FIXME: When can ToType be a reference type?
2509 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002510 if (SCS.Second == ICK_Derived_To_Base) {
John McCall37ad5512010-08-23 06:44:23 +00002511 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002512 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCall37ad5512010-08-23 06:44:23 +00002513 MultiExprArg(*this, &From, 1),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002514 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002515 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00002516 return ExprError();
2517 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2518 ToType, SCS.CopyConstructor,
2519 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002520 /*HadMultipleCandidates*/ false,
John Wiegley01296292011-04-08 18:41:53 +00002521 /*ZeroInit*/ false,
2522 CXXConstructExpr::CK_Complete,
2523 SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002524 }
John Wiegley01296292011-04-08 18:41:53 +00002525 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2526 ToType, SCS.CopyConstructor,
2527 MultiExprArg(*this, &From, 1),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002528 /*HadMultipleCandidates*/ false,
John Wiegley01296292011-04-08 18:41:53 +00002529 /*ZeroInit*/ false,
2530 CXXConstructExpr::CK_Complete,
2531 SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00002532 }
2533
Douglas Gregor980fb162010-04-29 18:24:40 +00002534 // Resolve overloaded function references.
2535 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2536 DeclAccessPair Found;
2537 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2538 true, Found);
2539 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00002540 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00002541
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002542 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00002543 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002544
Douglas Gregor980fb162010-04-29 18:24:40 +00002545 From = FixOverloadedFunctionReference(From, Found, Fn);
2546 FromType = From->getType();
2547 }
2548
Richard Smith507840d2011-11-29 22:48:16 +00002549 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00002550 switch (SCS.First) {
2551 case ICK_Identity:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002552 // Nothing to do.
2553 break;
2554
Eli Friedman946b7b52012-01-24 22:51:26 +00002555 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00002556 assert(From->getObjectKind() != OK_ObjCProperty);
John McCall34376a62010-12-04 03:47:34 +00002557 FromType = FromType.getUnqualifiedType();
Eli Friedman946b7b52012-01-24 22:51:26 +00002558 ExprResult FromRes = DefaultLvalueConversion(From);
2559 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
2560 From = FromRes.take();
John McCall34376a62010-12-04 03:47:34 +00002561 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00002562 }
John McCall34376a62010-12-04 03:47:34 +00002563
Douglas Gregor39c16d42008-10-24 04:54:22 +00002564 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00002565 FromType = Context.getArrayDecayedType(FromType);
Richard Smith507840d2011-11-29 22:48:16 +00002566 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2567 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor171c45a2009-02-18 21:56:37 +00002568 break;
2569
2570 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002571 FromType = Context.getPointerType(FromType);
Richard Smith507840d2011-11-29 22:48:16 +00002572 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2573 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002574 break;
2575
2576 default:
David Blaikie83d382b2011-09-23 05:06:16 +00002577 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002578 }
2579
Richard Smith507840d2011-11-29 22:48:16 +00002580 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00002581 switch (SCS.Second) {
2582 case ICK_Identity:
Sebastian Redl5d431642009-10-10 12:04:10 +00002583 // If both sides are functions (or pointers/references to them), there could
2584 // be incompatible exception declarations.
2585 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00002586 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00002587 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00002588 break;
2589
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00002590 case ICK_NoReturn_Adjustment:
2591 // If both sides are functions (or pointers/references to them), there could
2592 // be incompatible exception declarations.
2593 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00002594 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002595
Richard Smith507840d2011-11-29 22:48:16 +00002596 From = ImpCastExprToType(From, ToType, CK_NoOp,
2597 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00002598 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002599
Douglas Gregor39c16d42008-10-24 04:54:22 +00002600 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002601 case ICK_Integral_Conversion:
Richard Smith507840d2011-11-29 22:48:16 +00002602 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2603 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002604 break;
2605
2606 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002607 case ICK_Floating_Conversion:
Richard Smith507840d2011-11-29 22:48:16 +00002608 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2609 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002610 break;
2611
2612 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00002613 case ICK_Complex_Conversion: {
2614 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2615 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2616 CastKind CK;
2617 if (FromEl->isRealFloatingType()) {
2618 if (ToEl->isRealFloatingType())
2619 CK = CK_FloatingComplexCast;
2620 else
2621 CK = CK_FloatingComplexToIntegralComplex;
2622 } else if (ToEl->isRealFloatingType()) {
2623 CK = CK_IntegralComplexToFloatingComplex;
2624 } else {
2625 CK = CK_IntegralComplexCast;
2626 }
Richard Smith507840d2011-11-29 22:48:16 +00002627 From = ImpCastExprToType(From, ToType, CK,
2628 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002629 break;
John McCall8cb679e2010-11-15 09:13:47 +00002630 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00002631
Douglas Gregor39c16d42008-10-24 04:54:22 +00002632 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00002633 if (ToType->isRealFloatingType())
Richard Smith507840d2011-11-29 22:48:16 +00002634 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2635 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002636 else
Richard Smith507840d2011-11-29 22:48:16 +00002637 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2638 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002639 break;
2640
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002641 case ICK_Compatible_Conversion:
Richard Smith507840d2011-11-29 22:48:16 +00002642 From = ImpCastExprToType(From, ToType, CK_NoOp,
2643 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002644 break;
2645
John McCall31168b02011-06-15 23:02:42 +00002646 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002647 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00002648 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002649 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00002650 if (Action == AA_Initializing || Action == AA_Assigning)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002651 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00002652 diag::ext_typecheck_convert_incompatible_pointer)
2653 << ToType << From->getType() << Action
Anna Zaks3b402712011-07-28 19:51:27 +00002654 << From->getSourceRange() << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00002655 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002656 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00002657 diag::ext_typecheck_convert_incompatible_pointer)
2658 << From->getType() << ToType << Action
Anna Zaks3b402712011-07-28 19:51:27 +00002659 << From->getSourceRange() << 0;
John McCall31168b02011-06-15 23:02:42 +00002660
Douglas Gregor33823722011-06-11 01:09:30 +00002661 if (From->getType()->isObjCObjectPointerType() &&
2662 ToType->isObjCObjectPointerType())
2663 EmitRelatedResultTypeNote(From);
Fariborz Jahanianf2913402011-07-08 17:41:42 +00002664 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00002665 else if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanianf2913402011-07-08 17:41:42 +00002666 !CheckObjCARCUnavailableWeakConversion(ToType,
2667 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00002668 if (Action == AA_Initializing)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002669 Diag(From->getLocStart(),
John McCall9c3467e2011-09-09 06:12:06 +00002670 diag::err_arc_weak_unavailable_assign);
2671 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002672 Diag(From->getLocStart(),
John McCall9c3467e2011-09-09 06:12:06 +00002673 diag::err_arc_convesion_of_weak_unavailable)
2674 << (Action == AA_Casting) << From->getType() << ToType
2675 << From->getSourceRange();
2676 }
Fariborz Jahanianf2913402011-07-08 17:41:42 +00002677
John McCall8cb679e2010-11-15 09:13:47 +00002678 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00002679 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00002680 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00002681 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00002682
2683 // Make sure we extend blocks if necessary.
2684 // FIXME: doing this here is really ugly.
2685 if (Kind == CK_BlockPointerToObjCPointerCast) {
2686 ExprResult E = From;
2687 (void) PrepareCastToObjCObjectPointer(E);
2688 From = E.take();
2689 }
2690
Richard Smith507840d2011-11-29 22:48:16 +00002691 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2692 .take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002693 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002694 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002695
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002696 case ICK_Pointer_Member: {
John McCall8cb679e2010-11-15 09:13:47 +00002697 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00002698 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00002699 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00002700 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00002701 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00002702 return ExprError();
Richard Smith507840d2011-11-29 22:48:16 +00002703 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2704 .take();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002705 break;
2706 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002707
Abramo Bagnara7ccce982011-04-07 09:26:19 +00002708 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002709 // Perform half-to-boolean conversion via float.
2710 if (From->getType()->isHalfType()) {
2711 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take();
2712 FromType = Context.FloatTy;
2713 }
2714
Richard Smith507840d2011-11-29 22:48:16 +00002715 From = ImpCastExprToType(From, Context.BoolTy,
2716 ScalarTypeToBooleanCastKind(FromType),
2717 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002718 break;
2719
Douglas Gregor88d292c2010-05-13 16:44:06 +00002720 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00002721 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002722 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00002723 ToType.getNonReferenceType(),
2724 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002725 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00002726 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00002727 CStyle))
John Wiegley01296292011-04-08 18:41:53 +00002728 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00002729
Richard Smith507840d2011-11-29 22:48:16 +00002730 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2731 CK_DerivedToBase, From->getValueKind(),
2732 &BasePath, CCK).take();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00002733 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00002734 }
2735
Douglas Gregor46188682010-05-18 22:42:18 +00002736 case ICK_Vector_Conversion:
Richard Smith507840d2011-11-29 22:48:16 +00002737 From = ImpCastExprToType(From, ToType, CK_BitCast,
2738 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor46188682010-05-18 22:42:18 +00002739 break;
2740
2741 case ICK_Vector_Splat:
Richard Smith507840d2011-11-29 22:48:16 +00002742 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2743 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor46188682010-05-18 22:42:18 +00002744 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002745
Douglas Gregor46188682010-05-18 22:42:18 +00002746 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00002747 // Case 1. x -> _Complex y
2748 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2749 QualType ElType = ToComplex->getElementType();
2750 bool isFloatingComplex = ElType->isRealFloatingType();
2751
2752 // x -> y
2753 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2754 // do nothing
2755 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00002756 From = ImpCastExprToType(From, ElType,
2757 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
John McCall8cb679e2010-11-15 09:13:47 +00002758 } else {
2759 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00002760 From = ImpCastExprToType(From, ElType,
2761 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
John McCall8cb679e2010-11-15 09:13:47 +00002762 }
2763 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00002764 From = ImpCastExprToType(From, ToType,
2765 isFloatingComplex ? CK_FloatingRealToComplex
2766 : CK_IntegralRealToComplex).take();
John McCall8cb679e2010-11-15 09:13:47 +00002767
2768 // Case 2. _Complex x -> y
2769 } else {
2770 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2771 assert(FromComplex);
2772
2773 QualType ElType = FromComplex->getElementType();
2774 bool isFloatingComplex = ElType->isRealFloatingType();
2775
2776 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00002777 From = ImpCastExprToType(From, ElType,
2778 isFloatingComplex ? CK_FloatingComplexToReal
2779 : CK_IntegralComplexToReal,
2780 VK_RValue, /*BasePath=*/0, CCK).take();
John McCall8cb679e2010-11-15 09:13:47 +00002781
2782 // x -> y
2783 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2784 // do nothing
2785 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00002786 From = ImpCastExprToType(From, ToType,
2787 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2788 VK_RValue, /*BasePath=*/0, CCK).take();
John McCall8cb679e2010-11-15 09:13:47 +00002789 } else {
2790 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00002791 From = ImpCastExprToType(From, ToType,
2792 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2793 VK_RValue, /*BasePath=*/0, CCK).take();
John McCall8cb679e2010-11-15 09:13:47 +00002794 }
2795 }
Douglas Gregor46188682010-05-18 22:42:18 +00002796 break;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002797
2798 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00002799 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2800 VK_RValue, /*BasePath=*/0, CCK).take();
John McCall31168b02011-06-15 23:02:42 +00002801 break;
2802 }
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002803
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00002804 case ICK_TransparentUnionConversion: {
John Wiegley01296292011-04-08 18:41:53 +00002805 ExprResult FromRes = Owned(From);
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00002806 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002807 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2808 if (FromRes.isInvalid())
2809 return ExprError();
2810 From = FromRes.take();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00002811 assert ((ConvTy == Sema::Compatible) &&
2812 "Improper transparent union conversion");
2813 (void)ConvTy;
2814 break;
2815 }
2816
Douglas Gregor46188682010-05-18 22:42:18 +00002817 case ICK_Lvalue_To_Rvalue:
2818 case ICK_Array_To_Pointer:
2819 case ICK_Function_To_Pointer:
2820 case ICK_Qualification:
2821 case ICK_Num_Conversion_Kinds:
David Blaikie83d382b2011-09-23 05:06:16 +00002822 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002823 }
2824
2825 switch (SCS.Third) {
2826 case ICK_Identity:
2827 // Nothing to do.
2828 break;
2829
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002830 case ICK_Qualification: {
2831 // The qualification keeps the category of the inner expression, unless the
2832 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00002833 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanbe4b3632011-09-27 21:58:52 +00002834 From->getValueKind() : VK_RValue;
Richard Smith507840d2011-11-29 22:48:16 +00002835 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2836 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
Douglas Gregore489a7d2010-02-28 18:30:25 +00002837
Douglas Gregore981bb02011-03-14 16:13:32 +00002838 if (SCS.DeprecatedStringLiteralToCharPtr &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002839 !getLangOpts().WritableStrings)
Douglas Gregore489a7d2010-02-28 18:30:25 +00002840 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2841 << ToType.getNonReferenceType();
2842
Douglas Gregor39c16d42008-10-24 04:54:22 +00002843 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002844 }
2845
Douglas Gregor39c16d42008-10-24 04:54:22 +00002846 default:
David Blaikie83d382b2011-09-23 05:06:16 +00002847 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002848 }
2849
Douglas Gregor298f43d2012-04-12 20:42:30 +00002850 // If this conversion sequence involved a scalar -> atomic conversion, perform
2851 // that conversion now.
2852 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>())
2853 if (Context.hasSameType(ToAtomic->getValueType(), From->getType()))
2854 From = ImpCastExprToType(From, ToType, CK_NonAtomicToAtomic, VK_RValue, 0,
2855 CCK).take();
2856
John Wiegley01296292011-04-08 18:41:53 +00002857 return Owned(From);
Douglas Gregor39c16d42008-10-24 04:54:22 +00002858}
2859
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002860ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor54e5b132010-09-09 16:14:44 +00002861 SourceLocation KWLoc,
2862 ParsedType Ty,
2863 SourceLocation RParen) {
2864 TypeSourceInfo *TSInfo;
2865 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump11289f42009-09-09 15:08:12 +00002866
Douglas Gregor54e5b132010-09-09 16:14:44 +00002867 if (!TSInfo)
2868 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002869 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor54e5b132010-09-09 16:14:44 +00002870}
2871
Chandler Carruth8e172c62011-05-01 06:51:22 +00002872/// \brief Check the completeness of a type in a unary type trait.
2873///
2874/// If the particular type trait requires a complete type, tries to complete
2875/// it. If completing the type fails, a diagnostic is emitted and false
2876/// returned. If completing the type succeeds or no completion was required,
2877/// returns true.
2878static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2879 UnaryTypeTrait UTT,
2880 SourceLocation Loc,
2881 QualType ArgTy) {
2882 // C++0x [meta.unary.prop]p3:
2883 // For all of the class templates X declared in this Clause, instantiating
2884 // that template with a template argument that is a class template
2885 // specialization may result in the implicit instantiation of the template
2886 // argument if and only if the semantics of X require that the argument
2887 // must be a complete type.
2888 // We apply this rule to all the type trait expressions used to implement
2889 // these class templates. We also try to follow any GCC documented behavior
2890 // in these expressions to ensure portability of standard libraries.
2891 switch (UTT) {
Chandler Carruth8e172c62011-05-01 06:51:22 +00002892 // is_complete_type somewhat obviously cannot require a complete type.
2893 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002894 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00002895
2896 // These traits are modeled on the type predicates in C++0x
2897 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2898 // requiring a complete type, as whether or not they return true cannot be
2899 // impacted by the completeness of the type.
2900 case UTT_IsVoid:
2901 case UTT_IsIntegral:
2902 case UTT_IsFloatingPoint:
2903 case UTT_IsArray:
2904 case UTT_IsPointer:
2905 case UTT_IsLvalueReference:
2906 case UTT_IsRvalueReference:
2907 case UTT_IsMemberFunctionPointer:
2908 case UTT_IsMemberObjectPointer:
2909 case UTT_IsEnum:
2910 case UTT_IsUnion:
2911 case UTT_IsClass:
2912 case UTT_IsFunction:
2913 case UTT_IsReference:
2914 case UTT_IsArithmetic:
2915 case UTT_IsFundamental:
2916 case UTT_IsObject:
2917 case UTT_IsScalar:
2918 case UTT_IsCompound:
2919 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002920 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00002921
2922 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2923 // which requires some of its traits to have the complete type. However,
2924 // the completeness of the type cannot impact these traits' semantics, and
2925 // so they don't require it. This matches the comments on these traits in
2926 // Table 49.
2927 case UTT_IsConst:
2928 case UTT_IsVolatile:
2929 case UTT_IsSigned:
2930 case UTT_IsUnsigned:
2931 return true;
2932
2933 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002934 // applied to a complete type.
Chandler Carruth8e172c62011-05-01 06:51:22 +00002935 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00002936 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00002937 case UTT_IsStandardLayout:
2938 case UTT_IsPOD:
2939 case UTT_IsLiteral:
2940 case UTT_IsEmpty:
2941 case UTT_IsPolymorphic:
2942 case UTT_IsAbstract:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002943 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00002944
Douglas Gregordca70af2011-12-03 18:14:24 +00002945 // These traits require a complete type.
2946 case UTT_IsFinal:
2947
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002948 // These trait expressions are designed to help implement predicates in
Chandler Carruth8e172c62011-05-01 06:51:22 +00002949 // [meta.unary.prop] despite not being named the same. They are specified
2950 // by both GCC and the Embarcadero C++ compiler, and require the complete
2951 // type due to the overarching C++0x type predicates being implemented
2952 // requiring the complete type.
2953 case UTT_HasNothrowAssign:
2954 case UTT_HasNothrowConstructor:
2955 case UTT_HasNothrowCopy:
2956 case UTT_HasTrivialAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00002957 case UTT_HasTrivialDefaultConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00002958 case UTT_HasTrivialCopy:
2959 case UTT_HasTrivialDestructor:
2960 case UTT_HasVirtualDestructor:
2961 // Arrays of unknown bound are expressly allowed.
2962 QualType ElTy = ArgTy;
2963 if (ArgTy->isIncompleteArrayType())
2964 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2965
2966 // The void type is expressly allowed.
2967 if (ElTy->isVoidType())
2968 return true;
2969
2970 return !S.RequireCompleteType(
2971 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00002972 }
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +00002973 llvm_unreachable("Type trait not handled by switch");
Chandler Carruth8e172c62011-05-01 06:51:22 +00002974}
2975
2976static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2977 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00002978 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00002979
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002980 ASTContext &C = Self.Context;
2981 switch(UTT) {
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002982 // Type trait expressions corresponding to the primary type category
2983 // predicates in C++0x [meta.unary.cat].
2984 case UTT_IsVoid:
2985 return T->isVoidType();
2986 case UTT_IsIntegral:
2987 return T->isIntegralType(C);
2988 case UTT_IsFloatingPoint:
2989 return T->isFloatingType();
2990 case UTT_IsArray:
2991 return T->isArrayType();
2992 case UTT_IsPointer:
2993 return T->isPointerType();
2994 case UTT_IsLvalueReference:
2995 return T->isLValueReferenceType();
2996 case UTT_IsRvalueReference:
2997 return T->isRValueReferenceType();
2998 case UTT_IsMemberFunctionPointer:
2999 return T->isMemberFunctionPointerType();
3000 case UTT_IsMemberObjectPointer:
3001 return T->isMemberDataPointerType();
3002 case UTT_IsEnum:
3003 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00003004 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00003005 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003006 case UTT_IsClass:
Chandler Carruthaf858862011-05-01 09:29:58 +00003007 return T->isClassType() || T->isStructureType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003008 case UTT_IsFunction:
3009 return T->isFunctionType();
3010
3011 // Type trait expressions which correspond to the convenient composition
3012 // predicates in C++0x [meta.unary.comp].
3013 case UTT_IsReference:
3014 return T->isReferenceType();
3015 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00003016 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003017 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00003018 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003019 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00003020 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003021 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00003022 // Note: semantic analysis depends on Objective-C lifetime types to be
3023 // considered scalar types. However, such types do not actually behave
3024 // like scalar types at run time (since they may require retain/release
3025 // operations), so we report them as non-scalar.
3026 if (T->isObjCLifetimeType()) {
3027 switch (T.getObjCLifetime()) {
3028 case Qualifiers::OCL_None:
3029 case Qualifiers::OCL_ExplicitNone:
3030 return true;
3031
3032 case Qualifiers::OCL_Strong:
3033 case Qualifiers::OCL_Weak:
3034 case Qualifiers::OCL_Autoreleasing:
3035 return false;
3036 }
3037 }
3038
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00003039 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003040 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00003041 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003042 case UTT_IsMemberPointer:
3043 return T->isMemberPointerType();
3044
3045 // Type trait expressions which correspond to the type property predicates
3046 // in C++0x [meta.unary.prop].
3047 case UTT_IsConst:
3048 return T.isConstQualified();
3049 case UTT_IsVolatile:
3050 return T.isVolatileQualified();
3051 case UTT_IsTrivial:
John McCall31168b02011-06-15 23:02:42 +00003052 return T.isTrivialType(Self.Context);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00003053 case UTT_IsTriviallyCopyable:
John McCall31168b02011-06-15 23:02:42 +00003054 return T.isTriviallyCopyableType(Self.Context);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003055 case UTT_IsStandardLayout:
3056 return T->isStandardLayoutType();
3057 case UTT_IsPOD:
Benjamin Kramera3c0dad2012-04-28 10:00:33 +00003058 return T.isPODType(Self.Context);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003059 case UTT_IsLiteral:
3060 return T->isLiteralType();
3061 case UTT_IsEmpty:
3062 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3063 return !RD->isUnion() && RD->isEmpty();
3064 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003065 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00003066 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3067 return RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003068 return false;
3069 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00003070 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3071 return RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003072 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00003073 case UTT_IsFinal:
3074 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3075 return RD->hasAttr<FinalAttr>();
3076 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00003077 case UTT_IsSigned:
3078 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00003079 case UTT_IsUnsigned:
3080 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003081
3082 // Type trait expressions which query classes regarding their construction,
3083 // destruction, and copying. Rather than being based directly on the
3084 // related type predicates in the standard, they are specified by both
3085 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
3086 // specifications.
3087 //
3088 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
3089 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Alexis Huntf479f1b2011-05-09 18:22:59 +00003090 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003091 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3092 // If __is_pod (type) is true then the trait is true, else if type is
3093 // a cv class or union type (or array thereof) with a trivial default
3094 // constructor ([class.ctor]) then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00003095 if (T.isPODType(Self.Context))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003096 return true;
3097 if (const RecordType *RT =
3098 C.getBaseElementType(T)->getAs<RecordType>())
Alexis Huntf479f1b2011-05-09 18:22:59 +00003099 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003100 return false;
3101 case UTT_HasTrivialCopy:
3102 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3103 // If __is_pod (type) is true or type is a reference type then
3104 // the trait is true, else if type is a cv class or union type
3105 // with a trivial copy constructor ([class.copy]) then the trait
3106 // is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00003107 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003108 return true;
3109 if (const RecordType *RT = T->getAs<RecordType>())
3110 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
3111 return false;
3112 case UTT_HasTrivialAssign:
3113 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3114 // If type is const qualified or is a reference type then the
3115 // trait is false. Otherwise if __is_pod (type) is true then the
3116 // trait is true, else if type is a cv class or union type with
3117 // a trivial copy assignment ([class.copy]) then the trait is
3118 // true, else it is false.
3119 // Note: the const and reference restrictions are interesting,
3120 // given that const and reference members don't prevent a class
3121 // from having a trivial copy assignment operator (but do cause
3122 // errors if the copy assignment operator is actually used, q.v.
3123 // [class.copy]p12).
3124
3125 if (C.getBaseElementType(T).isConstQualified())
3126 return false;
John McCall31168b02011-06-15 23:02:42 +00003127 if (T.isPODType(Self.Context))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003128 return true;
3129 if (const RecordType *RT = T->getAs<RecordType>())
3130 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
3131 return false;
3132 case UTT_HasTrivialDestructor:
3133 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3134 // If __is_pod (type) is true or type is a reference type
3135 // then the trait is true, else if type is a cv class or union
3136 // type (or array thereof) with a trivial destructor
3137 // ([class.dtor]) then the trait is true, else it is
3138 // false.
John McCall31168b02011-06-15 23:02:42 +00003139 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003140 return true;
John McCall31168b02011-06-15 23:02:42 +00003141
3142 // Objective-C++ ARC: autorelease types don't require destruction.
3143 if (T->isObjCLifetimeType() &&
3144 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
3145 return true;
3146
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003147 if (const RecordType *RT =
3148 C.getBaseElementType(T)->getAs<RecordType>())
3149 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
3150 return false;
3151 // TODO: Propagate nothrowness for implicitly declared special members.
3152 case UTT_HasNothrowAssign:
3153 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3154 // If type is const qualified or is a reference type then the
3155 // trait is false. Otherwise if __has_trivial_assign (type)
3156 // is true then the trait is true, else if type is a cv class
3157 // or union type with copy assignment operators that are known
3158 // not to throw an exception then the trait is true, else it is
3159 // false.
3160 if (C.getBaseElementType(T).isConstQualified())
3161 return false;
3162 if (T->isReferenceType())
3163 return false;
John McCall31168b02011-06-15 23:02:42 +00003164 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
3165 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003166 if (const RecordType *RT = T->getAs<RecordType>()) {
3167 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
3168 if (RD->hasTrivialCopyAssignment())
3169 return true;
3170
3171 bool FoundAssign = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003172 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redl058fc822010-09-14 23:40:14 +00003173 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
3174 Sema::LookupOrdinaryName);
3175 if (Self.LookupQualifiedName(Res, RD)) {
Douglas Gregor6a0e23f2011-10-12 15:40:49 +00003176 Res.suppressDiagnostics();
Sebastian Redl058fc822010-09-14 23:40:14 +00003177 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
3178 Op != OpEnd; ++Op) {
Douglas Gregor6a0e23f2011-10-12 15:40:49 +00003179 if (isa<FunctionTemplateDecl>(*Op))
3180 continue;
3181
Sebastian Redl058fc822010-09-14 23:40:14 +00003182 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
3183 if (Operator->isCopyAssignmentOperator()) {
3184 FoundAssign = true;
3185 const FunctionProtoType *CPT
3186 = Operator->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00003187 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3188 if (!CPT)
3189 return false;
Richard Smith938f40b2011-06-11 17:19:42 +00003190 if (CPT->getExceptionSpecType() == EST_Delayed)
3191 return false;
3192 if (!CPT->isNothrow(Self.Context))
3193 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003194 }
3195 }
3196 }
Douglas Gregor6a0e23f2011-10-12 15:40:49 +00003197
Richard Smith938f40b2011-06-11 17:19:42 +00003198 return FoundAssign;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003199 }
3200 return false;
3201 case UTT_HasNothrowCopy:
3202 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3203 // If __has_trivial_copy (type) is true then the trait is true, else
3204 // if type is a cv class or union type with copy constructors that are
3205 // known not to throw an exception then the trait is true, else it is
3206 // false.
John McCall31168b02011-06-15 23:02:42 +00003207 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003208 return true;
3209 if (const RecordType *RT = T->getAs<RecordType>()) {
3210 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3211 if (RD->hasTrivialCopyConstructor())
3212 return true;
3213
3214 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003215 unsigned FoundTQs;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003216 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl951006f2010-09-13 21:10:20 +00003217 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003218 Con != ConEnd; ++Con) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00003219 // A template constructor is never a copy constructor.
3220 // FIXME: However, it may actually be selected at the actual overload
3221 // resolution point.
3222 if (isa<FunctionTemplateDecl>(*Con))
3223 continue;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003224 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3225 if (Constructor->isCopyConstructor(FoundTQs)) {
3226 FoundConstructor = true;
3227 const FunctionProtoType *CPT
3228 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00003229 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3230 if (!CPT)
3231 return false;
Richard Smith938f40b2011-06-11 17:19:42 +00003232 if (CPT->getExceptionSpecType() == EST_Delayed)
3233 return false;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003234 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00003235 // For now, we'll be conservative and assume that they can throw.
Richard Smith938f40b2011-06-11 17:19:42 +00003236 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
3237 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003238 }
3239 }
3240
Richard Smith938f40b2011-06-11 17:19:42 +00003241 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003242 }
3243 return false;
3244 case UTT_HasNothrowConstructor:
3245 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3246 // If __has_trivial_constructor (type) is true then the trait is
3247 // true, else if type is a cv class or union type (or array
3248 // thereof) with a default constructor that is known not to
3249 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00003250 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003251 return true;
3252 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
3253 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntf479f1b2011-05-09 18:22:59 +00003254 if (RD->hasTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003255 return true;
3256
Sebastian Redlc15c3262010-09-13 22:02:47 +00003257 DeclContext::lookup_const_iterator Con, ConEnd;
3258 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
3259 Con != ConEnd; ++Con) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00003260 // FIXME: In C++0x, a constructor template can be a default constructor.
3261 if (isa<FunctionTemplateDecl>(*Con))
3262 continue;
Sebastian Redlc15c3262010-09-13 22:02:47 +00003263 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3264 if (Constructor->isDefaultConstructor()) {
3265 const FunctionProtoType *CPT
3266 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00003267 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3268 if (!CPT)
3269 return false;
Richard Smith938f40b2011-06-11 17:19:42 +00003270 if (CPT->getExceptionSpecType() == EST_Delayed)
3271 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00003272 // TODO: check whether evaluating default arguments can throw.
3273 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl31ad7542011-03-13 17:09:40 +00003274 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
Sebastian Redlc15c3262010-09-13 22:02:47 +00003275 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003276 }
3277 }
3278 return false;
3279 case UTT_HasVirtualDestructor:
3280 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3281 // If type is a class type with a virtual destructor ([class.dtor])
3282 // then the trait is true, else it is false.
3283 if (const RecordType *Record = T->getAs<RecordType>()) {
3284 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redl058fc822010-09-14 23:40:14 +00003285 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003286 return Destructor->isVirtual();
3287 }
3288 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003289
3290 // These type trait expressions are modeled on the specifications for the
3291 // Embarcadero C++0x type trait functions:
3292 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3293 case UTT_IsCompleteType:
3294 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3295 // Returns True if and only if T is a complete type at the point of the
3296 // function call.
3297 return !T->isIncompleteType();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003298 }
Chandler Carruthb42fb192011-05-01 07:44:17 +00003299 llvm_unreachable("Type trait not covered by switch");
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003300}
3301
3302ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor54e5b132010-09-09 16:14:44 +00003303 SourceLocation KWLoc,
3304 TypeSourceInfo *TSInfo,
3305 SourceLocation RParen) {
3306 QualType T = TSInfo->getType();
Chandler Carruthb0776202011-04-30 10:07:32 +00003307 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
3308 return ExprError();
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003309
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003310 bool Value = false;
3311 if (!T->isDependentType())
Chandler Carruth8e172c62011-05-01 06:51:22 +00003312 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003313
3314 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson1f9648d2009-07-07 19:06:02 +00003315 RParen, Context.BoolTy));
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003316}
Sebastian Redl5822f082009-02-07 20:10:22 +00003317
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003318ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
3319 SourceLocation KWLoc,
3320 ParsedType LhsTy,
3321 ParsedType RhsTy,
3322 SourceLocation RParen) {
3323 TypeSourceInfo *LhsTSInfo;
3324 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3325 if (!LhsTSInfo)
3326 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3327
3328 TypeSourceInfo *RhsTSInfo;
3329 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3330 if (!RhsTSInfo)
3331 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3332
3333 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3334}
3335
Douglas Gregor29c42f22012-02-24 07:38:34 +00003336static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
3337 ArrayRef<TypeSourceInfo *> Args,
3338 SourceLocation RParenLoc) {
3339 switch (Kind) {
3340 case clang::TT_IsTriviallyConstructible: {
3341 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00003342 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00003343 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00003344 // is_constructible<T, Args...>::value is true and the variable
3345 // definition for is_constructible, as defined below, is known to call no
3346 // operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00003347 //
3348 // The predicate condition for a template specialization
3349 // is_constructible<T, Args...> shall be satisfied if and only if the
3350 // following variable definition would be well-formed for some invented
3351 // variable t:
3352 //
3353 // T t(create<Args>()...);
3354 if (Args.empty()) {
3355 S.Diag(KWLoc, diag::err_type_trait_arity)
3356 << 1 << 1 << 1 << (int)Args.size();
3357 return false;
3358 }
3359
3360 bool SawVoid = false;
3361 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3362 if (Args[I]->getType()->isVoidType()) {
3363 SawVoid = true;
3364 continue;
3365 }
3366
3367 if (!Args[I]->getType()->isIncompleteType() &&
3368 S.RequireCompleteType(KWLoc, Args[I]->getType(),
3369 diag::err_incomplete_type_used_in_type_trait_expr))
3370 return false;
3371 }
3372
3373 // If any argument was 'void', of course it won't type-check.
3374 if (SawVoid)
3375 return false;
3376
3377 llvm::SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
3378 llvm::SmallVector<Expr *, 2> ArgExprs;
3379 ArgExprs.reserve(Args.size() - 1);
3380 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
3381 QualType T = Args[I]->getType();
3382 if (T->isObjectType() || T->isFunctionType())
3383 T = S.Context.getRValueReferenceType(T);
3384 OpaqueArgExprs.push_back(
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003385 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
Douglas Gregor29c42f22012-02-24 07:38:34 +00003386 T.getNonLValueExprType(S.Context),
3387 Expr::getValueKindForType(T)));
3388 ArgExprs.push_back(&OpaqueArgExprs.back());
3389 }
3390
3391 // Perform the initialization in an unevaluated context within a SFINAE
3392 // trap at translation unit scope.
3393 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
3394 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3395 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3396 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
3397 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
3398 RParenLoc));
3399 InitializationSequence Init(S, To, InitKind,
3400 ArgExprs.begin(), ArgExprs.size());
3401 if (Init.Failed())
3402 return false;
3403
3404 ExprResult Result = Init.Perform(S, To, InitKind,
3405 MultiExprArg(ArgExprs.data(),
3406 ArgExprs.size()));
3407 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3408 return false;
3409
3410 // The initialization succeeded; not make sure there are no non-trivial
3411 // calls.
3412 return !Result.get()->hasNonTrivialCall(S.Context);
3413 }
3414 }
3415
3416 return false;
3417}
3418
3419ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3420 ArrayRef<TypeSourceInfo *> Args,
3421 SourceLocation RParenLoc) {
3422 bool Dependent = false;
3423 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3424 if (Args[I]->getType()->isDependentType()) {
3425 Dependent = true;
3426 break;
3427 }
3428 }
3429
3430 bool Value = false;
3431 if (!Dependent)
3432 Value = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
3433
3434 return TypeTraitExpr::Create(Context, Context.BoolTy, KWLoc, Kind,
3435 Args, RParenLoc, Value);
3436}
3437
3438ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3439 ArrayRef<ParsedType> Args,
3440 SourceLocation RParenLoc) {
3441 llvm::SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
3442 ConvertedArgs.reserve(Args.size());
3443
3444 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3445 TypeSourceInfo *TInfo;
3446 QualType T = GetTypeFromParser(Args[I], &TInfo);
3447 if (!TInfo)
3448 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
3449
3450 ConvertedArgs.push_back(TInfo);
3451 }
3452
3453 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
3454}
3455
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003456static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3457 QualType LhsT, QualType RhsT,
3458 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00003459 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3460 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003461
3462 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00003463 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003464 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00003465 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003466 // Base and Derived are not unions and name the same class type without
3467 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003468
John McCall388ef532011-01-28 22:02:36 +00003469 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3470 if (!lhsRecord) return false;
3471
3472 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3473 if (!rhsRecord) return false;
3474
3475 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3476 == (lhsRecord == rhsRecord));
3477
3478 if (lhsRecord == rhsRecord)
3479 return !lhsRecord->getDecl()->isUnion();
3480
3481 // C++0x [meta.rel]p2:
3482 // If Base and Derived are class types and are different types
3483 // (ignoring possible cv-qualifiers) then Derived shall be a
3484 // complete type.
3485 if (Self.RequireCompleteType(KeyLoc, RhsT,
3486 diag::err_incomplete_type_used_in_type_trait_expr))
3487 return false;
3488
3489 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3490 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3491 }
John Wiegley65497cc2011-04-27 23:09:49 +00003492 case BTT_IsSame:
3493 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichet34b21132010-12-08 22:35:30 +00003494 case BTT_TypeCompatible:
3495 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3496 RhsT.getUnqualifiedType());
John Wiegley65497cc2011-04-27 23:09:49 +00003497 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00003498 case BTT_IsConvertibleTo: {
3499 // C++0x [meta.rel]p4:
3500 // Given the following function prototype:
3501 //
3502 // template <class T>
3503 // typename add_rvalue_reference<T>::type create();
3504 //
3505 // the predicate condition for a template specialization
3506 // is_convertible<From, To> shall be satisfied if and only if
3507 // the return expression in the following code would be
3508 // well-formed, including any implicit conversions to the return
3509 // type of the function:
3510 //
3511 // To test() {
3512 // return create<From>();
3513 // }
3514 //
3515 // Access checking is performed as if in a context unrelated to To and
3516 // From. Only the validity of the immediate context of the expression
3517 // of the return-statement (including conversions to the return type)
3518 // is considered.
3519 //
3520 // We model the initialization as a copy-initialization of a temporary
3521 // of the appropriate type, which for this expression is identical to the
3522 // return statement (since NRVO doesn't apply).
3523 if (LhsT->isObjectType() || LhsT->isFunctionType())
3524 LhsT = Self.Context.getRValueReferenceType(LhsT);
3525
3526 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00003527 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00003528 Expr::getValueKindForType(LhsT));
3529 Expr *FromPtr = &From;
3530 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3531 SourceLocation()));
3532
Eli Friedmana59b1902012-01-25 01:05:57 +00003533 // Perform the initialization in an unevaluated context within a SFINAE
3534 // trap at translation unit scope.
3535 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00003536 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3537 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor8006e762011-01-27 20:28:01 +00003538 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00003539 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00003540 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00003541
Douglas Gregor8006e762011-01-27 20:28:01 +00003542 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
3543 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3544 }
Douglas Gregor1be329d2012-02-23 07:33:15 +00003545
3546 case BTT_IsTriviallyAssignable: {
3547 // C++11 [meta.unary.prop]p3:
3548 // is_trivially_assignable is defined as:
3549 // is_assignable<T, U>::value is true and the assignment, as defined by
3550 // is_assignable, is known to call no operation that is not trivial
3551 //
3552 // is_assignable is defined as:
3553 // The expression declval<T>() = declval<U>() is well-formed when
3554 // treated as an unevaluated operand (Clause 5).
3555 //
3556 // For both, T and U shall be complete types, (possibly cv-qualified)
3557 // void, or arrays of unknown bound.
3558 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
3559 Self.RequireCompleteType(KeyLoc, LhsT,
3560 diag::err_incomplete_type_used_in_type_trait_expr))
3561 return false;
3562 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
3563 Self.RequireCompleteType(KeyLoc, RhsT,
3564 diag::err_incomplete_type_used_in_type_trait_expr))
3565 return false;
3566
3567 // cv void is never assignable.
3568 if (LhsT->isVoidType() || RhsT->isVoidType())
3569 return false;
3570
3571 // Build expressions that emulate the effect of declval<T>() and
3572 // declval<U>().
3573 if (LhsT->isObjectType() || LhsT->isFunctionType())
3574 LhsT = Self.Context.getRValueReferenceType(LhsT);
3575 if (RhsT->isObjectType() || RhsT->isFunctionType())
3576 RhsT = Self.Context.getRValueReferenceType(RhsT);
3577 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
3578 Expr::getValueKindForType(LhsT));
3579 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
3580 Expr::getValueKindForType(RhsT));
3581
3582 // Attempt the assignment in an unevaluated context within a SFINAE
3583 // trap at translation unit scope.
3584 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
3585 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3586 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
3587 ExprResult Result = Self.BuildBinOp(/*S=*/0, KeyLoc, BO_Assign, &Lhs, &Rhs);
3588 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3589 return false;
3590
3591 return !Result.get()->hasNonTrivialCall(Self.Context);
3592 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003593 }
3594 llvm_unreachable("Unknown type trait or not implemented");
3595}
3596
3597ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3598 SourceLocation KWLoc,
3599 TypeSourceInfo *LhsTSInfo,
3600 TypeSourceInfo *RhsTSInfo,
3601 SourceLocation RParen) {
3602 QualType LhsT = LhsTSInfo->getType();
3603 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003604
John McCall388ef532011-01-28 22:02:36 +00003605 if (BTT == BTT_TypeCompatible) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003606 if (getLangOpts().CPlusPlus) {
Francois Pichet34b21132010-12-08 22:35:30 +00003607 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3608 << SourceRange(KWLoc, RParen);
3609 return ExprError();
3610 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003611 }
3612
3613 bool Value = false;
3614 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3615 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3616
Francois Pichet34b21132010-12-08 22:35:30 +00003617 // Select trait result type.
3618 QualType ResultType;
3619 switch (BTT) {
Francois Pichet34b21132010-12-08 22:35:30 +00003620 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
John Wiegley65497cc2011-04-27 23:09:49 +00003621 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3622 case BTT_IsSame: ResultType = Context.BoolTy; break;
Francois Pichet34b21132010-12-08 22:35:30 +00003623 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor8006e762011-01-27 20:28:01 +00003624 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Douglas Gregor1be329d2012-02-23 07:33:15 +00003625 case BTT_IsTriviallyAssignable: ResultType = Context.BoolTy;
Francois Pichet34b21132010-12-08 22:35:30 +00003626 }
3627
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003628 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3629 RhsTSInfo, Value, RParen,
Francois Pichet34b21132010-12-08 22:35:30 +00003630 ResultType));
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003631}
3632
John Wiegley6242b6a2011-04-28 00:16:57 +00003633ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3634 SourceLocation KWLoc,
3635 ParsedType Ty,
3636 Expr* DimExpr,
3637 SourceLocation RParen) {
3638 TypeSourceInfo *TSInfo;
3639 QualType T = GetTypeFromParser(Ty, &TSInfo);
3640 if (!TSInfo)
3641 TSInfo = Context.getTrivialTypeSourceInfo(T);
3642
3643 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3644}
3645
3646static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3647 QualType T, Expr *DimExpr,
3648 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00003649 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00003650
3651 switch(ATT) {
3652 case ATT_ArrayRank:
3653 if (T->isArrayType()) {
3654 unsigned Dim = 0;
3655 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3656 ++Dim;
3657 T = AT->getElementType();
3658 }
3659 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00003660 }
John Wiegleyd3522222011-04-28 02:06:46 +00003661 return 0;
3662
John Wiegley6242b6a2011-04-28 00:16:57 +00003663 case ATT_ArrayExtent: {
3664 llvm::APSInt Value;
3665 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00003666 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00003667 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00003668 false).isInvalid())
3669 return 0;
3670 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00003671 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
3672 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00003673 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00003674 }
Richard Smithf4c51d92012-02-04 09:53:13 +00003675 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00003676
3677 if (T->isArrayType()) {
3678 unsigned D = 0;
3679 bool Matched = false;
3680 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3681 if (Dim == D) {
3682 Matched = true;
3683 break;
3684 }
3685 ++D;
3686 T = AT->getElementType();
3687 }
3688
John Wiegleyd3522222011-04-28 02:06:46 +00003689 if (Matched && T->isArrayType()) {
3690 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3691 return CAT->getSize().getLimitedValue();
3692 }
John Wiegley6242b6a2011-04-28 00:16:57 +00003693 }
John Wiegleyd3522222011-04-28 02:06:46 +00003694 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00003695 }
3696 }
3697 llvm_unreachable("Unknown type trait or not implemented");
3698}
3699
3700ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3701 SourceLocation KWLoc,
3702 TypeSourceInfo *TSInfo,
3703 Expr* DimExpr,
3704 SourceLocation RParen) {
3705 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00003706
Chandler Carruthc5276e52011-05-01 08:48:21 +00003707 // FIXME: This should likely be tracked as an APInt to remove any host
3708 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00003709 uint64_t Value = 0;
3710 if (!T->isDependentType())
3711 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3712
Chandler Carruthc5276e52011-05-01 08:48:21 +00003713 // While the specification for these traits from the Embarcadero C++
3714 // compiler's documentation says the return type is 'unsigned int', Clang
3715 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3716 // compiler, there is no difference. On several other platforms this is an
3717 // important distinction.
John Wiegley6242b6a2011-04-28 00:16:57 +00003718 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
Chandler Carruth9cf632c2011-05-01 07:49:26 +00003719 DimExpr, RParen,
Chandler Carruthc5276e52011-05-01 08:48:21 +00003720 Context.getSizeType()));
John Wiegley6242b6a2011-04-28 00:16:57 +00003721}
3722
John Wiegleyf9f65842011-04-25 06:54:41 +00003723ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003724 SourceLocation KWLoc,
3725 Expr *Queried,
3726 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00003727 // If error parsing the expression, ignore.
3728 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003729 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00003730
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003731 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00003732
3733 return move(Result);
3734}
3735
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003736static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3737 switch (ET) {
3738 case ET_IsLValueExpr: return E->isLValue();
3739 case ET_IsRValueExpr: return E->isRValue();
3740 }
3741 llvm_unreachable("Expression trait not covered by switch");
3742}
3743
John Wiegleyf9f65842011-04-25 06:54:41 +00003744ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003745 SourceLocation KWLoc,
3746 Expr *Queried,
3747 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00003748 if (Queried->isTypeDependent()) {
3749 // Delay type-checking for type-dependent expressions.
3750 } else if (Queried->getType()->isPlaceholderType()) {
3751 ExprResult PE = CheckPlaceholderExpr(Queried);
3752 if (PE.isInvalid()) return ExprError();
3753 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3754 }
3755
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003756 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00003757
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003758 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3759 RParen, Context.BoolTy));
John Wiegleyf9f65842011-04-25 06:54:41 +00003760}
3761
Richard Trieu82402a02011-09-15 21:56:47 +00003762QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00003763 ExprValueKind &VK,
3764 SourceLocation Loc,
3765 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00003766 assert(!LHS.get()->getType()->isPlaceholderType() &&
3767 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00003768 "placeholders should have been weeded out by now");
3769
3770 // The LHS undergoes lvalue conversions if this is ->*.
3771 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00003772 LHS = DefaultLvalueConversion(LHS.take());
3773 if (LHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00003774 }
3775
3776 // The RHS always undergoes lvalue conversions.
Richard Trieu82402a02011-09-15 21:56:47 +00003777 RHS = DefaultLvalueConversion(RHS.take());
3778 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00003779
Sebastian Redl5822f082009-02-07 20:10:22 +00003780 const char *OpSpelling = isIndirect ? "->*" : ".*";
3781 // C++ 5.5p2
3782 // The binary operator .* [p3: ->*] binds its second operand, which shall
3783 // be of type "pointer to member of T" (where T is a completely-defined
3784 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00003785 QualType RHSType = RHS.get()->getType();
3786 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00003787 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00003788 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00003789 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00003790 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00003791 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00003792
Sebastian Redl5822f082009-02-07 20:10:22 +00003793 QualType Class(MemPtr->getClass(), 0);
3794
Douglas Gregord07ba342010-10-13 20:41:14 +00003795 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3796 // member pointer points must be completely-defined. However, there is no
3797 // reason for this semantic distinction, and the rule is not enforced by
3798 // other compilers. Therefore, we do not check this property, as it is
3799 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00003800
Sebastian Redl5822f082009-02-07 20:10:22 +00003801 // C++ 5.5p2
3802 // [...] to its first operand, which shall be of class T or of a class of
3803 // which T is an unambiguous and accessible base class. [p3: a pointer to
3804 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00003805 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00003806 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00003807 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
3808 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00003809 else {
3810 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00003811 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00003812 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00003813 return QualType();
3814 }
3815 }
3816
Richard Trieu82402a02011-09-15 21:56:47 +00003817 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00003818 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003819 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
3820 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00003821 return QualType();
3822 }
Anders Carlssona70cff62010-04-24 19:06:50 +00003823 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00003824 /*DetectVirtual=*/false);
Mike Stump87c57ac2009-05-16 07:39:55 +00003825 // FIXME: Would it be useful to print full ambiguity paths, or is that
3826 // overkill?
Richard Trieu82402a02011-09-15 21:56:47 +00003827 if (!IsDerivedFrom(LHSType, Class, Paths) ||
Sebastian Redl5822f082009-02-07 20:10:22 +00003828 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3829 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00003830 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00003831 return QualType();
3832 }
Eli Friedman1fcf66b2010-01-16 00:00:48 +00003833 // Cast LHS to type of use.
3834 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanbe4b3632011-09-27 21:58:52 +00003835 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003836
John McCallcf142162010-08-07 06:22:56 +00003837 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00003838 BuildBasePathArray(Paths, BasePath);
Richard Trieu82402a02011-09-15 21:56:47 +00003839 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
3840 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00003841 }
3842
Richard Trieu82402a02011-09-15 21:56:47 +00003843 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00003844 // Diagnose use of pointer-to-member type which when used as
3845 // the functional cast in a pointer-to-member expression.
3846 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3847 return QualType();
3848 }
John McCall7decc9e2010-11-18 06:31:45 +00003849
Sebastian Redl5822f082009-02-07 20:10:22 +00003850 // C++ 5.5p2
3851 // The result is an object or a function of the type specified by the
3852 // second operand.
3853 // The cv qualifiers are the union of those in the pointer and the left side,
3854 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00003855 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00003856 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00003857
Douglas Gregor1d042092011-01-26 16:40:18 +00003858 // C++0x [expr.mptr.oper]p6:
3859 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003860 // ill-formed if the second operand is a pointer to member function with
3861 // ref-qualifier &. In a ->* expression or in a .* expression whose object
3862 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00003863 // is a pointer to member function with ref-qualifier &&.
3864 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3865 switch (Proto->getRefQualifier()) {
3866 case RQ_None:
3867 // Do nothing
3868 break;
3869
3870 case RQ_LValue:
Richard Trieu82402a02011-09-15 21:56:47 +00003871 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00003872 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00003873 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00003874 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003875
Douglas Gregor1d042092011-01-26 16:40:18 +00003876 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00003877 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00003878 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00003879 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00003880 break;
3881 }
3882 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003883
John McCall7decc9e2010-11-18 06:31:45 +00003884 // C++ [expr.mptr.oper]p6:
3885 // The result of a .* expression whose second operand is a pointer
3886 // to a data member is of the same value category as its
3887 // first operand. The result of a .* expression whose second
3888 // operand is a pointer to a member function is a prvalue. The
3889 // result of an ->* expression is an lvalue if its second operand
3890 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00003891 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00003892 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00003893 return Context.BoundMemberTy;
3894 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00003895 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00003896 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00003897 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00003898 }
John McCall7decc9e2010-11-18 06:31:45 +00003899
Sebastian Redl5822f082009-02-07 20:10:22 +00003900 return Result;
3901}
Sebastian Redl1a99f442009-04-16 17:51:27 +00003902
Sebastian Redl1a99f442009-04-16 17:51:27 +00003903/// \brief Try to convert a type to another according to C++0x 5.16p3.
3904///
3905/// This is part of the parameter validation for the ? operator. If either
3906/// value operand is a class type, the two operands are attempted to be
3907/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00003908/// It returns true if the program is ill-formed and has already been diagnosed
3909/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003910static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3911 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00003912 bool &HaveConversion,
3913 QualType &ToType) {
3914 HaveConversion = false;
3915 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003916
3917 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00003918 SourceLocation());
Sebastian Redl1a99f442009-04-16 17:51:27 +00003919 // C++0x 5.16p3
3920 // The process for determining whether an operand expression E1 of type T1
3921 // can be converted to match an operand expression E2 of type T2 is defined
3922 // as follows:
3923 // -- If E2 is an lvalue:
John McCall086a4642010-11-24 05:12:34 +00003924 bool ToIsLvalue = To->isLValue();
Douglas Gregorf9edf802010-03-26 20:59:55 +00003925 if (ToIsLvalue) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003926 // E1 can be converted to match E2 if E1 can be implicitly converted to
3927 // type "lvalue reference to T2", subject to the constraint that in the
3928 // conversion the reference must bind directly to E1.
Douglas Gregor838fcc32010-03-26 20:14:36 +00003929 QualType T = Self.Context.getLValueReferenceType(ToType);
3930 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003931
Douglas Gregor838fcc32010-03-26 20:14:36 +00003932 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3933 if (InitSeq.isDirectReferenceBinding()) {
3934 ToType = T;
3935 HaveConversion = true;
3936 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003937 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003938
Douglas Gregor838fcc32010-03-26 20:14:36 +00003939 if (InitSeq.isAmbiguous())
3940 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003941 }
John McCall65eb8792010-02-25 01:37:24 +00003942
Sebastian Redl1a99f442009-04-16 17:51:27 +00003943 // -- If E2 is an rvalue, or if the conversion above cannot be done:
3944 // -- if E1 and E2 have class type, and the underlying class types are
3945 // the same or one is a base class of the other:
3946 QualType FTy = From->getType();
3947 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003948 const RecordType *FRec = FTy->getAs<RecordType>();
3949 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003950 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregor838fcc32010-03-26 20:14:36 +00003951 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003952 if (FRec && TRec &&
Douglas Gregor838fcc32010-03-26 20:14:36 +00003953 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003954 // E1 can be converted to match E2 if the class of T2 is the
3955 // same type as, or a base class of, the class of T1, and
3956 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00003957 if (FRec == TRec || FDerivedFromT) {
3958 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00003959 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3960 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00003961 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00003962 HaveConversion = true;
3963 return false;
3964 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003965
Douglas Gregor838fcc32010-03-26 20:14:36 +00003966 if (InitSeq.isAmbiguous())
3967 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003968 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003969 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003970
Douglas Gregor838fcc32010-03-26 20:14:36 +00003971 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003972 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003973
Douglas Gregor838fcc32010-03-26 20:14:36 +00003974 // -- Otherwise: E1 can be converted to match E2 if E1 can be
3975 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003976 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00003977 // an rvalue).
3978 //
3979 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3980 // to the array-to-pointer or function-to-pointer conversions.
3981 if (!TTy->getAs<TagType>())
3982 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003983
Douglas Gregor838fcc32010-03-26 20:14:36 +00003984 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3985 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00003986 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00003987 ToType = TTy;
3988 if (InitSeq.isAmbiguous())
3989 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3990
Sebastian Redl1a99f442009-04-16 17:51:27 +00003991 return false;
3992}
3993
3994/// \brief Try to find a common type for two according to C++0x 5.16p5.
3995///
3996/// This is part of the parameter validation for the ? operator. If either
3997/// value operand is a class type, overload resolution is used to find a
3998/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00003999static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004000 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004001 Expr *Args[2] = { LHS.get(), RHS.get() };
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004002 OverloadCandidateSet CandidateSet(QuestionLoc);
4003 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
4004 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004005
4006 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004007 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00004008 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004009 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley01296292011-04-08 18:41:53 +00004010 ExprResult LHSRes =
4011 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
4012 Best->Conversions[0], Sema::AA_Converting);
4013 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00004014 break;
John Wiegley01296292011-04-08 18:41:53 +00004015 LHS = move(LHSRes);
4016
4017 ExprResult RHSRes =
4018 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
4019 Best->Conversions[1], Sema::AA_Converting);
4020 if (RHSRes.isInvalid())
4021 break;
4022 RHS = move(RHSRes);
Chandler Carruth30141632011-02-25 19:41:05 +00004023 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00004024 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004025 return false;
John Wiegley01296292011-04-08 18:41:53 +00004026 }
4027
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004028 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004029
4030 // Emit a better diagnostic if one of the expressions is a null pointer
4031 // constant and the other is a pointer type. In this case, the user most
4032 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004033 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004034 return true;
4035
4036 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00004037 << LHS.get()->getType() << RHS.get()->getType()
4038 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004039 return true;
4040
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004041 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004042 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00004043 << LHS.get()->getType() << RHS.get()->getType()
4044 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00004045 // FIXME: Print the possible common types by printing the return types of
4046 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004047 break;
4048
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004049 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00004050 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00004051 }
4052 return true;
4053}
4054
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004055/// \brief Perform an "extended" implicit conversion as returned by
4056/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00004057static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00004058 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley01296292011-04-08 18:41:53 +00004059 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00004060 SourceLocation());
John Wiegley01296292011-04-08 18:41:53 +00004061 Expr *Arg = E.take();
4062 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
4063 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
Douglas Gregor838fcc32010-03-26 20:14:36 +00004064 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004065 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004066
John Wiegley01296292011-04-08 18:41:53 +00004067 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004068 return false;
4069}
4070
Sebastian Redl1a99f442009-04-16 17:51:27 +00004071/// \brief Check the operands of ?: under C++ semantics.
4072///
4073/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
4074/// extension. In this case, LHS == Cond. (But they're not aliases.)
John Wiegley01296292011-04-08 18:41:53 +00004075QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCallc07a0c72011-02-17 10:25:35 +00004076 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00004077 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00004078 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
4079 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004080
4081 // C++0x 5.16p1
4082 // The first expression is contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00004083 if (!Cond.get()->isTypeDependent()) {
4084 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
4085 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00004086 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004087 Cond = move(CondRes);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004088 }
4089
John McCall7decc9e2010-11-18 06:31:45 +00004090 // Assume r-value.
4091 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004092 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00004093
Sebastian Redl1a99f442009-04-16 17:51:27 +00004094 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00004095 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00004096 return Context.DependentTy;
4097
4098 // C++0x 5.16p2
4099 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00004100 QualType LTy = LHS.get()->getType();
4101 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004102 bool LVoid = LTy->isVoidType();
4103 bool RVoid = RTy->isVoidType();
4104 if (LVoid || RVoid) {
4105 // ... then the [l2r] conversions are performed on the second and third
4106 // operands ...
John Wiegley01296292011-04-08 18:41:53 +00004107 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
4108 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
4109 if (LHS.isInvalid() || RHS.isInvalid())
4110 return QualType();
4111 LTy = LHS.get()->getType();
4112 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004113
4114 // ... and one of the following shall hold:
4115 // -- The second or the third operand (but not both) is a throw-
4116 // expression; the result is of the type of the other and is an rvalue.
John Wiegley01296292011-04-08 18:41:53 +00004117 bool LThrow = isa<CXXThrowExpr>(LHS.get());
4118 bool RThrow = isa<CXXThrowExpr>(RHS.get());
Sebastian Redl1a99f442009-04-16 17:51:27 +00004119 if (LThrow && !RThrow)
4120 return RTy;
4121 if (RThrow && !LThrow)
4122 return LTy;
4123
4124 // -- Both the second and third operands have type void; the result is of
4125 // type void and is an rvalue.
4126 if (LVoid && RVoid)
4127 return Context.VoidTy;
4128
4129 // Neither holds, error.
4130 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
4131 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00004132 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004133 return QualType();
4134 }
4135
4136 // Neither is void.
4137
4138 // C++0x 5.16p3
4139 // Otherwise, if the second and third operand have different types, and
4140 // either has (cv) class type, and attempt is made to convert each of those
4141 // operands to the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004142 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00004143 (LTy->isRecordType() || RTy->isRecordType())) {
4144 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
4145 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00004146 QualType L2RType, R2LType;
4147 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00004148 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00004149 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004150 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00004151 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004152
Sebastian Redl1a99f442009-04-16 17:51:27 +00004153 // If both can be converted, [...] the program is ill-formed.
4154 if (HaveL2R && HaveR2L) {
4155 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00004156 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004157 return QualType();
4158 }
4159
4160 // If exactly one conversion is possible, that conversion is applied to
4161 // the chosen operand and the converted operands are used in place of the
4162 // original operands for the remainder of this section.
4163 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00004164 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00004165 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004166 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004167 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00004168 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00004169 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004170 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004171 }
4172 }
4173
4174 // C++0x 5.16p4
John McCall7decc9e2010-11-18 06:31:45 +00004175 // If the second and third operands are glvalues of the same value
4176 // category and have the same type, the result is of that type and
4177 // value category and it is a bit-field if the second or the third
4178 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00004179 // We only extend this to bitfields, not to the crazy other kinds of
4180 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00004181 bool Same = Context.hasSameType(LTy, RTy);
John McCall7decc9e2010-11-18 06:31:45 +00004182 if (Same &&
John Wiegley01296292011-04-08 18:41:53 +00004183 LHS.get()->isGLValue() &&
4184 LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
4185 LHS.get()->isOrdinaryOrBitFieldObject() &&
4186 RHS.get()->isOrdinaryOrBitFieldObject()) {
4187 VK = LHS.get()->getValueKind();
4188 if (LHS.get()->getObjectKind() == OK_BitField ||
4189 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00004190 OK = OK_BitField;
John McCall7decc9e2010-11-18 06:31:45 +00004191 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00004192 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004193
4194 // C++0x 5.16p5
4195 // Otherwise, the result is an rvalue. If the second and third operands
4196 // do not have the same type, and either has (cv) class type, ...
4197 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
4198 // ... overload resolution is used to determine the conversions (if any)
4199 // to be applied to the operands. If the overload resolution fails, the
4200 // program is ill-formed.
4201 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
4202 return QualType();
4203 }
4204
4205 // C++0x 5.16p6
4206 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
4207 // conversions are performed on the second and third operands.
John Wiegley01296292011-04-08 18:41:53 +00004208 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
4209 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
4210 if (LHS.isInvalid() || RHS.isInvalid())
4211 return QualType();
4212 LTy = LHS.get()->getType();
4213 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004214
4215 // After those conversions, one of the following shall hold:
4216 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00004217 // is of that type. If the operands have class type, the result
4218 // is a prvalue temporary of the result type, which is
4219 // copy-initialized from either the second operand or the third
4220 // operand depending on the value of the first operand.
4221 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
4222 if (LTy->isRecordType()) {
4223 // The operands have class type. Make a temporary copy.
4224 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004225 ExprResult LHSCopy = PerformCopyInitialization(Entity,
4226 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00004227 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00004228 if (LHSCopy.isInvalid())
4229 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004230
4231 ExprResult RHSCopy = PerformCopyInitialization(Entity,
4232 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00004233 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00004234 if (RHSCopy.isInvalid())
4235 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004236
John Wiegley01296292011-04-08 18:41:53 +00004237 LHS = LHSCopy;
4238 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00004239 }
4240
Sebastian Redl1a99f442009-04-16 17:51:27 +00004241 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00004242 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004243
Douglas Gregor46188682010-05-18 22:42:18 +00004244 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004245 if (LTy->isVectorType() || RTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004246 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00004247
Sebastian Redl1a99f442009-04-16 17:51:27 +00004248 // -- The second and third operands have arithmetic or enumeration type;
4249 // the usual arithmetic conversions are performed to bring them to a
4250 // common type, and the result is of that type.
4251 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
4252 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004253 if (LHS.isInvalid() || RHS.isInvalid())
4254 return QualType();
4255 return LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004256 }
4257
4258 // -- The second and third operands have pointer type, or one has pointer
4259 // type and the other is a null pointer constant; pointer conversions
4260 // and qualification conversions are performed to bring them to their
4261 // composite pointer type. The result is of the composite pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00004262 // -- The second and third operands have pointer to member type, or one has
4263 // pointer to member type and the other is a null pointer constant;
4264 // pointer to member conversions and qualification conversions are
4265 // performed to bring them to a common type, whose cv-qualification
4266 // shall match the cv-qualification of either the second or the third
4267 // operand. The result is of the common type.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004268 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00004269 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004270 isSFINAEContext()? 0 : &NonStandardCompositeType);
4271 if (!Composite.isNull()) {
4272 if (NonStandardCompositeType)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004273 Diag(QuestionLoc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004274 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
4275 << LTy << RTy << Composite
John Wiegley01296292011-04-08 18:41:53 +00004276 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004277
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004278 return Composite;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004279 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004280
Douglas Gregor697a3912010-04-01 22:47:07 +00004281 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00004282 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
4283 if (!Composite.isNull())
4284 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004285
Chandler Carruth9c9127e2011-02-19 00:13:59 +00004286 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00004287 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00004288 return QualType();
4289
Sebastian Redl1a99f442009-04-16 17:51:27 +00004290 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00004291 << LHS.get()->getType() << RHS.get()->getType()
4292 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004293 return QualType();
4294}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004295
4296/// \brief Find a merged pointer type and convert the two expressions to it.
4297///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004298/// This finds the composite pointer type (or member pointer type) for @p E1
4299/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
4300/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004301/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004302///
Douglas Gregor19175ff2010-04-16 23:20:25 +00004303/// \param Loc The location of the operator requiring these two expressions to
4304/// be converted to the composite pointer type.
4305///
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004306/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
4307/// a non-standard (but still sane) composite type to which both expressions
4308/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
4309/// will be set true.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004310QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00004311 Expr *&E1, Expr *&E2,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004312 bool *NonStandardCompositeType) {
4313 if (NonStandardCompositeType)
4314 *NonStandardCompositeType = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004315
David Blaikiebbafb8a2012-03-11 07:00:24 +00004316 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004317 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004318
Fariborz Jahanian33e148f2009-12-08 20:04:24 +00004319 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
4320 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004321 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004322
4323 // C++0x 5.9p2
4324 // Pointer conversions and qualification conversions are performed on
4325 // pointer operands to bring them to their composite pointer type. If
4326 // one operand is a null pointer constant, the composite pointer type is
4327 // the type of the other operand.
Douglas Gregor56751b52009-09-25 04:25:58 +00004328 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004329 if (T2->isMemberPointerType())
John Wiegley01296292011-04-08 18:41:53 +00004330 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004331 else
John Wiegley01296292011-04-08 18:41:53 +00004332 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004333 return T2;
4334 }
Douglas Gregor56751b52009-09-25 04:25:58 +00004335 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004336 if (T1->isMemberPointerType())
John Wiegley01296292011-04-08 18:41:53 +00004337 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004338 else
John Wiegley01296292011-04-08 18:41:53 +00004339 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004340 return T1;
4341 }
Mike Stump11289f42009-09-09 15:08:12 +00004342
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004343 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00004344 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
4345 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004346 return QualType();
4347
4348 // Otherwise, of one of the operands has type "pointer to cv1 void," then
4349 // the other has type "pointer to cv2 T" and the composite pointer type is
4350 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
4351 // Otherwise, the composite pointer type is a pointer type similar to the
4352 // type of one of the operands, with a cv-qualification signature that is
4353 // the union of the cv-qualification signatures of the operand types.
4354 // In practice, the first part here is redundant; it's subsumed by the second.
4355 // What we do here is, we build the two possible composite types, and try the
4356 // conversions in both directions. If only one works, or if the two composite
4357 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00004358 // FIXME: extended qualifiers?
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004359 typedef SmallVector<unsigned, 4> QualifierVector;
Sebastian Redl658262f2009-11-16 21:03:45 +00004360 QualifierVector QualifierUnion;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004361 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
Sebastian Redl658262f2009-11-16 21:03:45 +00004362 ContainingClassVector;
4363 ContainingClassVector MemberOfClass;
4364 QualType Composite1 = Context.getCanonicalType(T1),
4365 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004366 unsigned NeedConstBefore = 0;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004367 do {
4368 const PointerType *Ptr1, *Ptr2;
4369 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
4370 (Ptr2 = Composite2->getAs<PointerType>())) {
4371 Composite1 = Ptr1->getPointeeType();
4372 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004373
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004374 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004375 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004376 if (NonStandardCompositeType &&
4377 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4378 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004379
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004380 QualifierUnion.push_back(
4381 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4382 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
4383 continue;
4384 }
Mike Stump11289f42009-09-09 15:08:12 +00004385
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004386 const MemberPointerType *MemPtr1, *MemPtr2;
4387 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
4388 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
4389 Composite1 = MemPtr1->getPointeeType();
4390 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004391
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004392 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004393 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004394 if (NonStandardCompositeType &&
4395 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4396 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004397
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004398 QualifierUnion.push_back(
4399 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4400 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
4401 MemPtr2->getClass()));
4402 continue;
4403 }
Mike Stump11289f42009-09-09 15:08:12 +00004404
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004405 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00004406
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004407 // Cannot unwrap any more types.
4408 break;
4409 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00004410
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004411 if (NeedConstBefore && NonStandardCompositeType) {
4412 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004413 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004414 // requirements of C++ [conv.qual]p4 bullet 3.
4415 for (unsigned I = 0; I != NeedConstBefore; ++I) {
4416 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
4417 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
4418 *NonStandardCompositeType = true;
4419 }
4420 }
4421 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004422
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004423 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-11-16 21:03:45 +00004424 ContainingClassVector::reverse_iterator MOC
4425 = MemberOfClass.rbegin();
4426 for (QualifierVector::reverse_iterator
4427 I = QualifierUnion.rbegin(),
4428 E = QualifierUnion.rend();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004429 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00004430 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004431 if (MOC->first && MOC->second) {
4432 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00004433 Composite1 = Context.getMemberPointerType(
4434 Context.getQualifiedType(Composite1, Quals),
4435 MOC->first);
4436 Composite2 = Context.getMemberPointerType(
4437 Context.getQualifiedType(Composite2, Quals),
4438 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004439 } else {
4440 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00004441 Composite1
4442 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
4443 Composite2
4444 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004445 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004446 }
4447
Douglas Gregor19175ff2010-04-16 23:20:25 +00004448 // Try to convert to the first composite pointer type.
4449 InitializedEntity Entity1
4450 = InitializedEntity::InitializeTemporary(Composite1);
4451 InitializationKind Kind
4452 = InitializationKind::CreateCopy(Loc, SourceLocation());
4453 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
4454 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump11289f42009-09-09 15:08:12 +00004455
Douglas Gregor19175ff2010-04-16 23:20:25 +00004456 if (E1ToC1 && E2ToC1) {
4457 // Conversion to Composite1 is viable.
4458 if (!Context.hasSameType(Composite1, Composite2)) {
4459 // Composite2 is a different type from Composite1. Check whether
4460 // Composite2 is also viable.
4461 InitializedEntity Entity2
4462 = InitializedEntity::InitializeTemporary(Composite2);
4463 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4464 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4465 if (E1ToC2 && E2ToC2) {
4466 // Both Composite1 and Composite2 are viable and are different;
4467 // this is an ambiguity.
4468 return QualType();
4469 }
4470 }
4471
4472 // Convert E1 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00004473 ExprResult E1Result
John McCall37ad5512010-08-23 06:44:23 +00004474 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00004475 if (E1Result.isInvalid())
4476 return QualType();
4477 E1 = E1Result.takeAs<Expr>();
4478
4479 // Convert E2 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00004480 ExprResult E2Result
John McCall37ad5512010-08-23 06:44:23 +00004481 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00004482 if (E2Result.isInvalid())
4483 return QualType();
4484 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004485
Douglas Gregor19175ff2010-04-16 23:20:25 +00004486 return Composite1;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004487 }
4488
Douglas Gregor19175ff2010-04-16 23:20:25 +00004489 // Check whether Composite2 is viable.
4490 InitializedEntity Entity2
4491 = InitializedEntity::InitializeTemporary(Composite2);
4492 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4493 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4494 if (!E1ToC2 || !E2ToC2)
4495 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004496
Douglas Gregor19175ff2010-04-16 23:20:25 +00004497 // Convert E1 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00004498 ExprResult E1Result
John McCall37ad5512010-08-23 06:44:23 +00004499 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00004500 if (E1Result.isInvalid())
4501 return QualType();
4502 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004503
Douglas Gregor19175ff2010-04-16 23:20:25 +00004504 // Convert E2 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00004505 ExprResult E2Result
John McCall37ad5512010-08-23 06:44:23 +00004506 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00004507 if (E2Result.isInvalid())
4508 return QualType();
4509 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004510
Douglas Gregor19175ff2010-04-16 23:20:25 +00004511 return Composite2;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004512}
Anders Carlsson85a307d2009-05-17 18:41:29 +00004513
John McCalldadc5752010-08-24 06:29:42 +00004514ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00004515 if (!E)
4516 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004517
John McCall31168b02011-06-15 23:02:42 +00004518 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4519
4520 // If the result is a glvalue, we shouldn't bind it.
4521 if (!E->isRValue())
Anders Carlssonf86a8d12009-08-15 23:41:35 +00004522 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00004523
John McCall31168b02011-06-15 23:02:42 +00004524 // In ARC, calls that return a retainable type can return retained,
4525 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004526 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00004527 E->getType()->isObjCRetainableType()) {
4528
4529 bool ReturnsRetained;
4530
4531 // For actual calls, we compute this by examining the type of the
4532 // called value.
4533 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4534 Expr *Callee = Call->getCallee()->IgnoreParens();
4535 QualType T = Callee->getType();
4536
4537 if (T == Context.BoundMemberTy) {
4538 // Handle pointer-to-members.
4539 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4540 T = BinOp->getRHS()->getType();
4541 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4542 T = Mem->getMemberDecl()->getType();
4543 }
4544
4545 if (const PointerType *Ptr = T->getAs<PointerType>())
4546 T = Ptr->getPointeeType();
4547 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4548 T = Ptr->getPointeeType();
4549 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4550 T = MemPtr->getPointeeType();
4551
4552 const FunctionType *FTy = T->getAs<FunctionType>();
4553 assert(FTy && "call to value not of function type?");
4554 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4555
4556 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4557 // type always produce a +1 object.
4558 } else if (isa<StmtExpr>(E)) {
4559 ReturnsRetained = true;
4560
Ted Kremeneke65b0862012-03-06 20:05:56 +00004561 // We hit this case with the lambda conversion-to-block optimization;
4562 // we don't want any extra casts here.
4563 } else if (isa<CastExpr>(E) &&
4564 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
4565 return Owned(E);
4566
John McCall31168b02011-06-15 23:02:42 +00004567 // For message sends and property references, we try to find an
4568 // actual method. FIXME: we should infer retention by selector in
4569 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00004570 } else {
4571 ObjCMethodDecl *D = 0;
4572 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4573 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00004574 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
4575 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00004576 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
4577 D = ArrayLit->getArrayWithObjectsMethod();
4578 } else if (ObjCDictionaryLiteral *DictLit
4579 = dyn_cast<ObjCDictionaryLiteral>(E)) {
4580 D = DictLit->getDictWithObjectsMethod();
4581 }
John McCall31168b02011-06-15 23:02:42 +00004582
4583 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00004584
4585 // Don't do reclaims on performSelector calls; despite their
4586 // return type, the invoked method doesn't necessarily actually
4587 // return an object.
4588 if (!ReturnsRetained &&
4589 D && D->getMethodFamily() == OMF_performSelector)
4590 return Owned(E);
John McCall31168b02011-06-15 23:02:42 +00004591 }
4592
John McCall16de4d22011-11-14 19:53:16 +00004593 // Don't reclaim an object of Class type.
4594 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4595 return Owned(E);
4596
John McCall4db5c3c2011-07-07 06:58:02 +00004597 ExprNeedsCleanups = true;
4598
John McCall2d637d22011-09-10 06:18:15 +00004599 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4600 : CK_ARCReclaimReturnedObject);
John McCall4db5c3c2011-07-07 06:58:02 +00004601 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4602 VK_RValue));
John McCall31168b02011-06-15 23:02:42 +00004603 }
4604
David Blaikiebbafb8a2012-03-11 07:00:24 +00004605 if (!getLangOpts().CPlusPlus)
John McCall31168b02011-06-15 23:02:42 +00004606 return Owned(E);
Douglas Gregor363b1512009-12-24 18:51:59 +00004607
Peter Collingbournec331a1e2012-01-26 03:33:51 +00004608 // Search for the base element type (cf. ASTContext::getBaseElementType) with
4609 // a fast path for the common case that the type is directly a RecordType.
4610 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
4611 const RecordType *RT = 0;
4612 while (!RT) {
4613 switch (T->getTypeClass()) {
4614 case Type::Record:
4615 RT = cast<RecordType>(T);
4616 break;
4617 case Type::ConstantArray:
4618 case Type::IncompleteArray:
4619 case Type::VariableArray:
4620 case Type::DependentSizedArray:
4621 T = cast<ArrayType>(T)->getElementType().getTypePtr();
4622 break;
4623 default:
4624 return Owned(E);
4625 }
4626 }
Mike Stump11289f42009-09-09 15:08:12 +00004627
Richard Smithfd555f62012-02-22 02:04:18 +00004628 // That should be enough to guarantee that this type is complete, if we're
4629 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00004630 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00004631 if (RD->isInvalidDecl() || RD->isDependentContext())
John McCall67da35c2010-02-04 22:26:26 +00004632 return Owned(E);
Richard Smithfd555f62012-02-22 02:04:18 +00004633
4634 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
4635 CXXDestructorDecl *Destructor = IsDecltype ? 0 : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00004636
John McCall31168b02011-06-15 23:02:42 +00004637 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00004638 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00004639 CheckDestructorAccess(E->getExprLoc(), Destructor,
4640 PDiag(diag::err_access_dtor_temp)
4641 << E->getType());
Richard Smitheec915d62012-02-18 04:13:32 +00004642 DiagnoseUseOfDecl(Destructor, E->getExprLoc());
John McCall31168b02011-06-15 23:02:42 +00004643
Richard Smithfd555f62012-02-22 02:04:18 +00004644 // If destructor is trivial, we can avoid the extra copy.
4645 if (Destructor->isTrivial())
4646 return Owned(E);
Richard Smitheec915d62012-02-18 04:13:32 +00004647
John McCall28fc7092011-11-10 05:35:25 +00004648 // We need a cleanup, but we don't need to remember the temporary.
John McCall31168b02011-06-15 23:02:42 +00004649 ExprNeedsCleanups = true;
Richard Smithfd555f62012-02-22 02:04:18 +00004650 }
Richard Smitheec915d62012-02-18 04:13:32 +00004651
4652 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00004653 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
4654
4655 if (IsDecltype)
4656 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
4657
4658 return Owned(Bind);
Anders Carlsson2d4cada2009-05-30 20:36:53 +00004659}
4660
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004661ExprResult
John McCall5d413782010-12-06 08:20:24 +00004662Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004663 if (SubExpr.isInvalid())
4664 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004665
John McCall5d413782010-12-06 08:20:24 +00004666 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004667}
4668
John McCall28fc7092011-11-10 05:35:25 +00004669Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
4670 assert(SubExpr && "sub expression can't be null!");
4671
Eli Friedman3bda6b12012-02-02 23:15:15 +00004672 CleanupVarDeclMarking();
4673
John McCall28fc7092011-11-10 05:35:25 +00004674 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
4675 assert(ExprCleanupObjects.size() >= FirstCleanup);
4676 assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
4677 if (!ExprNeedsCleanups)
4678 return SubExpr;
4679
4680 ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
4681 = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
4682 ExprCleanupObjects.size() - FirstCleanup);
4683
4684 Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
4685 DiscardCleanupsInEvaluationContext();
4686
4687 return E;
4688}
4689
John McCall5d413782010-12-06 08:20:24 +00004690Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004691 assert(SubStmt && "sub statement can't be null!");
4692
Eli Friedman3bda6b12012-02-02 23:15:15 +00004693 CleanupVarDeclMarking();
4694
John McCall31168b02011-06-15 23:02:42 +00004695 if (!ExprNeedsCleanups)
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004696 return SubStmt;
4697
4698 // FIXME: In order to attach the temporaries, wrap the statement into
4699 // a StmtExpr; currently this is only used for asm statements.
4700 // This is hacky, either create a new CXXStmtWithTemporaries statement or
4701 // a new AsmStmtWithTemporaries.
4702 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
4703 SourceLocation(),
4704 SourceLocation());
4705 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
4706 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00004707 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004708}
4709
Richard Smithfd555f62012-02-22 02:04:18 +00004710/// Process the expression contained within a decltype. For such expressions,
4711/// certain semantic checks on temporaries are delayed until this point, and
4712/// are omitted for the 'topmost' call in the decltype expression. If the
4713/// topmost call bound a temporary, strip that temporary off the expression.
4714ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
4715 ExpressionEvaluationContextRecord &Rec = ExprEvalContexts.back();
4716 assert(Rec.IsDecltype && "not in a decltype expression");
4717
4718 // C++11 [expr.call]p11:
4719 // If a function call is a prvalue of object type,
4720 // -- if the function call is either
4721 // -- the operand of a decltype-specifier, or
4722 // -- the right operand of a comma operator that is the operand of a
4723 // decltype-specifier,
4724 // a temporary object is not introduced for the prvalue.
4725
4726 // Recursively rebuild ParenExprs and comma expressions to strip out the
4727 // outermost CXXBindTemporaryExpr, if any.
4728 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4729 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
4730 if (SubExpr.isInvalid())
4731 return ExprError();
4732 if (SubExpr.get() == PE->getSubExpr())
4733 return Owned(E);
4734 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.take());
4735 }
4736 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4737 if (BO->getOpcode() == BO_Comma) {
4738 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
4739 if (RHS.isInvalid())
4740 return ExprError();
4741 if (RHS.get() == BO->getRHS())
4742 return Owned(E);
4743 return Owned(new (Context) BinaryOperator(BO->getLHS(), RHS.take(),
4744 BO_Comma, BO->getType(),
4745 BO->getValueKind(),
4746 BO->getObjectKind(),
4747 BO->getOperatorLoc()));
4748 }
4749 }
4750
4751 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
4752 if (TopBind)
4753 E = TopBind->getSubExpr();
4754
4755 // Disable the special decltype handling now.
4756 Rec.IsDecltype = false;
4757
4758 // Perform the semantic checks we delayed until this point.
4759 CallExpr *TopCall = dyn_cast<CallExpr>(E);
4760 for (unsigned I = 0, N = Rec.DelayedDecltypeCalls.size(); I != N; ++I) {
4761 CallExpr *Call = Rec.DelayedDecltypeCalls[I];
4762 if (Call == TopCall)
4763 continue;
4764
4765 if (CheckCallReturnType(Call->getCallReturnType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004766 Call->getLocStart(),
Richard Smithfd555f62012-02-22 02:04:18 +00004767 Call, Call->getDirectCallee()))
4768 return ExprError();
4769 }
4770
4771 // Now all relevant types are complete, check the destructors are accessible
4772 // and non-deleted, and annotate them on the temporaries.
4773 for (unsigned I = 0, N = Rec.DelayedDecltypeBinds.size(); I != N; ++I) {
4774 CXXBindTemporaryExpr *Bind = Rec.DelayedDecltypeBinds[I];
4775 if (Bind == TopBind)
4776 continue;
4777
4778 CXXTemporary *Temp = Bind->getTemporary();
4779
4780 CXXRecordDecl *RD =
4781 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
4782 CXXDestructorDecl *Destructor = LookupDestructor(RD);
4783 Temp->setDestructor(Destructor);
4784
Richard Smith7d847b12012-05-11 22:20:10 +00004785 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
4786 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00004787 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00004788 << Bind->getType());
4789 DiagnoseUseOfDecl(Destructor, Bind->getExprLoc());
Richard Smithfd555f62012-02-22 02:04:18 +00004790
4791 // We need a cleanup, but we don't need to remember the temporary.
4792 ExprNeedsCleanups = true;
4793 }
4794
4795 // Possibly strip off the top CXXBindTemporaryExpr.
4796 return Owned(E);
4797}
4798
John McCalldadc5752010-08-24 06:29:42 +00004799ExprResult
John McCallb268a282010-08-23 23:25:46 +00004800Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallba7bf592010-08-24 05:47:05 +00004801 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00004802 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004803 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004804 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00004805 if (Result.isInvalid()) return ExprError();
4806 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00004807
John McCall526ab472011-10-25 17:37:35 +00004808 Result = CheckPlaceholderExpr(Base);
4809 if (Result.isInvalid()) return ExprError();
4810 Base = Result.take();
4811
John McCallb268a282010-08-23 23:25:46 +00004812 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00004813 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004814 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00004815 // If we have a pointer to a dependent type and are using the -> operator,
4816 // the object type is the type that the pointer points to. We might still
4817 // have enough information about that type to do something useful.
4818 if (OpKind == tok::arrow)
4819 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4820 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004821
John McCallba7bf592010-08-24 05:47:05 +00004822 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00004823 MayBePseudoDestructor = true;
John McCallb268a282010-08-23 23:25:46 +00004824 return Owned(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004825 }
Mike Stump11289f42009-09-09 15:08:12 +00004826
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004827 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00004828 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004829 // returned, with the original second operand.
4830 if (OpKind == tok::arrow) {
John McCallc1538c02009-09-30 01:01:30 +00004831 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00004832 llvm::SmallPtrSet<CanQualType,8> CTypes;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004833 SmallVector<SourceLocation, 8> Locations;
John McCallbd0465b2009-09-30 01:30:54 +00004834 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004835
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004836 while (BaseType->isRecordType()) {
John McCallb268a282010-08-23 23:25:46 +00004837 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
4838 if (Result.isInvalid())
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004839 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00004840 Base = Result.get();
4841 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonfbd2d492009-10-13 22:55:59 +00004842 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallb268a282010-08-23 23:25:46 +00004843 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00004844 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCallbd0465b2009-09-30 01:30:54 +00004845 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00004846 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00004847 for (unsigned i = 0; i < Locations.size(); i++)
4848 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00004849 return ExprError();
4850 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004851 }
Mike Stump11289f42009-09-09 15:08:12 +00004852
Douglas Gregorbf3a8262012-01-12 16:11:24 +00004853 if (BaseType->isPointerType() || BaseType->isObjCObjectPointerType())
Douglas Gregore4f764f2009-11-20 19:58:21 +00004854 BaseType = BaseType->getPointeeType();
4855 }
Mike Stump11289f42009-09-09 15:08:12 +00004856
Douglas Gregorbf3a8262012-01-12 16:11:24 +00004857 // Objective-C properties allow "." access on Objective-C pointer types,
4858 // so adjust the base type to the object type itself.
4859 if (BaseType->isObjCObjectPointerType())
4860 BaseType = BaseType->getPointeeType();
4861
4862 // C++ [basic.lookup.classref]p2:
4863 // [...] If the type of the object expression is of pointer to scalar
4864 // type, the unqualified-id is looked up in the context of the complete
4865 // postfix-expression.
4866 //
4867 // This also indicates that we could be parsing a pseudo-destructor-name.
4868 // Note that Objective-C class and object types can be pseudo-destructor
4869 // expressions or normal member (ivar or property) access expressions.
4870 if (BaseType->isObjCObjectOrInterfaceType()) {
4871 MayBePseudoDestructor = true;
4872 } else if (!BaseType->isRecordType()) {
John McCallba7bf592010-08-24 05:47:05 +00004873 ObjectType = ParsedType();
Douglas Gregore610ada2010-02-24 18:44:31 +00004874 MayBePseudoDestructor = true;
John McCallb268a282010-08-23 23:25:46 +00004875 return Owned(Base);
Douglas Gregor2b6ca462009-09-03 21:38:09 +00004876 }
Mike Stump11289f42009-09-09 15:08:12 +00004877
Douglas Gregor3024f072012-04-16 07:05:22 +00004878 // The object type must be complete (or dependent), or
4879 // C++11 [expr.prim.general]p3:
4880 // Unlike the object expression in other contexts, *this is not required to
4881 // be of complete type for purposes of class member access (5.2.5) outside
4882 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00004883 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00004884 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004885 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00004886 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004887
Douglas Gregor2b6ca462009-09-03 21:38:09 +00004888 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004889 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00004890 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00004891 // type C (or of pointer to a class type C), the unqualified-id is looked
4892 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00004893 ObjectType = ParsedType::make(BaseType);
Mike Stump11289f42009-09-09 15:08:12 +00004894 return move(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004895}
4896
John McCalldadc5752010-08-24 06:29:42 +00004897ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCallb268a282010-08-23 23:25:46 +00004898 Expr *MemExpr) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004899 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCallb268a282010-08-23 23:25:46 +00004900 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
4901 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregora771f462010-03-31 17:46:05 +00004902 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004903
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004904 return ActOnCallExpr(/*Scope*/ 0,
John McCallb268a282010-08-23 23:25:46 +00004905 MemExpr,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004906 /*LPLoc*/ ExpectedLParenLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00004907 MultiExprArg(),
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004908 /*RPLoc*/ ExpectedLParenLoc);
4909}
Douglas Gregore610ada2010-02-24 18:44:31 +00004910
Eli Friedman6601b552012-01-25 04:29:24 +00004911static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00004912 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00004913 if (Base->hasPlaceholderType()) {
4914 ExprResult result = S.CheckPlaceholderExpr(Base);
4915 if (result.isInvalid()) return true;
4916 Base = result.take();
4917 }
4918 ObjectType = Base->getType();
4919
David Blaikie1d578782011-12-16 16:03:09 +00004920 // C++ [expr.pseudo]p2:
4921 // The left-hand side of the dot operator shall be of scalar type. The
4922 // left-hand side of the arrow operator shall be of pointer to scalar type.
4923 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00004924 // Note that this is rather different from the normal handling for the
4925 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00004926 if (OpKind == tok::arrow) {
4927 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4928 ObjectType = Ptr->getPointeeType();
4929 } else if (!Base->isTypeDependent()) {
4930 // The user wrote "p->" when she probably meant "p."; fix it.
4931 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4932 << ObjectType << true
4933 << FixItHint::CreateReplacement(OpLoc, ".");
4934 if (S.isSFINAEContext())
4935 return true;
4936
4937 OpKind = tok::period;
4938 }
4939 }
4940
4941 return false;
4942}
4943
John McCalldadc5752010-08-24 06:29:42 +00004944ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00004945 SourceLocation OpLoc,
4946 tok::TokenKind OpKind,
4947 const CXXScopeSpec &SS,
4948 TypeSourceInfo *ScopeTypeInfo,
4949 SourceLocation CCLoc,
4950 SourceLocation TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00004951 PseudoDestructorTypeStorage Destructed,
John McCalla2c4e722011-02-25 05:21:17 +00004952 bool HasTrailingLParen) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00004953 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004954
Eli Friedman0ce4de42012-01-25 04:35:06 +00004955 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00004956 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4957 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004958
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004959 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004960 if (getLangOpts().MicrosoftMode && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00004961 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Nico Weber58829272012-01-23 05:50:57 +00004962 else
4963 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
4964 << ObjectType << Base->getSourceRange();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004965 return ExprError();
4966 }
4967
4968 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004969 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004970 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00004971 if (DestructedTypeInfo) {
4972 QualType DestructedType = DestructedTypeInfo->getType();
4973 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004974 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00004975 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
4976 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
4977 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
4978 << ObjectType << DestructedType << Base->getSourceRange()
4979 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004980
John McCall31168b02011-06-15 23:02:42 +00004981 // Recover by setting the destructed type to the object type.
4982 DestructedType = ObjectType;
4983 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregor678f90d2010-02-25 01:56:36 +00004984 DestructedTypeStart);
John McCall31168b02011-06-15 23:02:42 +00004985 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4986 } else if (DestructedType.getObjCLifetime() !=
4987 ObjectType.getObjCLifetime()) {
4988
4989 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
4990 // Okay: just pretend that the user provided the correctly-qualified
4991 // type.
4992 } else {
4993 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
4994 << ObjectType << DestructedType << Base->getSourceRange()
4995 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4996 }
4997
4998 // Recover by setting the destructed type to the object type.
4999 DestructedType = ObjectType;
5000 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
5001 DestructedTypeStart);
5002 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5003 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00005004 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005005 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005006
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005007 // C++ [expr.pseudo]p2:
5008 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
5009 // form
5010 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005011 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005012 //
5013 // shall designate the same scalar type.
5014 if (ScopeTypeInfo) {
5015 QualType ScopeType = ScopeTypeInfo->getType();
5016 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00005017 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005018
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00005019 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005020 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00005021 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00005022 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005023
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005024 ScopeType = QualType();
5025 ScopeTypeInfo = 0;
5026 }
5027 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005028
John McCallb268a282010-08-23 23:25:46 +00005029 Expr *Result
5030 = new (Context) CXXPseudoDestructorExpr(Context, Base,
5031 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00005032 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00005033 ScopeTypeInfo,
5034 CCLoc,
5035 TildeLoc,
5036 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005037
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005038 if (HasTrailingLParen)
John McCallb268a282010-08-23 23:25:46 +00005039 return Owned(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005040
John McCallb268a282010-08-23 23:25:46 +00005041 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005042}
5043
John McCalldadc5752010-08-24 06:29:42 +00005044ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00005045 SourceLocation OpLoc,
5046 tok::TokenKind OpKind,
5047 CXXScopeSpec &SS,
5048 UnqualifiedId &FirstTypeName,
5049 SourceLocation CCLoc,
5050 SourceLocation TildeLoc,
5051 UnqualifiedId &SecondTypeName,
5052 bool HasTrailingLParen) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005053 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5054 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5055 "Invalid first type name in pseudo-destructor");
5056 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5057 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5058 "Invalid second type name in pseudo-destructor");
5059
Eli Friedman0ce4de42012-01-25 04:35:06 +00005060 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00005061 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5062 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00005063
5064 // Compute the object type that we should use for name lookup purposes. Only
5065 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00005066 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00005067 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00005068 if (ObjectType->isRecordType())
5069 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00005070 else if (ObjectType->isDependentType())
5071 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00005072 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005073
5074 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005075 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005076 QualType DestructedType;
5077 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregor678f90d2010-02-25 01:56:36 +00005078 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005079 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005080 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00005081 SecondTypeName.StartLocation,
Fariborz Jahanian87967422011-02-08 18:05:59 +00005082 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005083 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00005084 ((SS.isSet() && !computeDeclContext(SS, false)) ||
5085 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005086 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00005087 // couldn't find anything useful in scope. Just store the identifier and
5088 // it's location, and we'll perform (qualified) name lookup again at
5089 // template instantiation time.
5090 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
5091 SecondTypeName.StartLocation);
5092 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005093 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005094 diag::err_pseudo_dtor_destructor_non_type)
5095 << SecondTypeName.Identifier << ObjectType;
5096 if (isSFINAEContext())
5097 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005098
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005099 // Recover by assuming we had the right type all along.
5100 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005101 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005102 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005103 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005104 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005105 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005106 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5107 TemplateId->getTemplateArgs(),
5108 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00005109 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00005110 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00005111 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005112 TemplateId->TemplateNameLoc,
5113 TemplateId->LAngleLoc,
5114 TemplateArgsPtr,
5115 TemplateId->RAngleLoc);
5116 if (T.isInvalid() || !T.get()) {
5117 // Recover by assuming we had the right type all along.
5118 DestructedType = ObjectType;
5119 } else
5120 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005121 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005122
5123 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005124 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00005125 if (!DestructedType.isNull()) {
5126 if (!DestructedTypeInfo)
5127 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005128 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00005129 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5130 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005131
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005132 // Convert the name of the scope type (the type prior to '::') into a type.
5133 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005134 QualType ScopeType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005135 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005136 FirstTypeName.Identifier) {
5137 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005138 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00005139 FirstTypeName.StartLocation,
Douglas Gregora6ce6082011-02-25 18:19:59 +00005140 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005141 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005142 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005143 diag::err_pseudo_dtor_destructor_non_type)
5144 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005145
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005146 if (isSFINAEContext())
5147 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005148
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005149 // Just drop this type. It's unnecessary anyway.
5150 ScopeType = QualType();
5151 } else
5152 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005153 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005154 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005155 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005156 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5157 TemplateId->getTemplateArgs(),
5158 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00005159 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00005160 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00005161 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005162 TemplateId->TemplateNameLoc,
5163 TemplateId->LAngleLoc,
5164 TemplateArgsPtr,
5165 TemplateId->RAngleLoc);
5166 if (T.isInvalid() || !T.get()) {
5167 // Recover by dropping this type.
5168 ScopeType = QualType();
5169 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005170 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005171 }
5172 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005173
Douglas Gregor90ad9222010-02-24 23:02:30 +00005174 if (!ScopeType.isNull() && !ScopeTypeInfo)
5175 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
5176 FirstTypeName.StartLocation);
5177
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005178
John McCallb268a282010-08-23 23:25:46 +00005179 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00005180 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00005181 Destructed, HasTrailingLParen);
Douglas Gregore610ada2010-02-24 18:44:31 +00005182}
5183
David Blaikie1d578782011-12-16 16:03:09 +00005184ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5185 SourceLocation OpLoc,
5186 tok::TokenKind OpKind,
5187 SourceLocation TildeLoc,
5188 const DeclSpec& DS,
5189 bool HasTrailingLParen) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00005190 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00005191 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5192 return ExprError();
5193
5194 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
5195
5196 TypeLocBuilder TLB;
5197 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
5198 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
5199 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
5200 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
5201
5202 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
5203 0, SourceLocation(), TildeLoc,
5204 Destructed, HasTrailingLParen);
5205}
5206
John Wiegley01296292011-04-08 18:41:53 +00005207ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00005208 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005209 bool HadMultipleCandidates) {
Eli Friedman98b01ed2012-03-01 04:01:32 +00005210 if (Method->getParent()->isLambda() &&
5211 Method->getConversionType()->isBlockPointerType()) {
5212 // This is a lambda coversion to block pointer; check if the argument
5213 // is a LambdaExpr.
5214 Expr *SubE = E;
5215 CastExpr *CE = dyn_cast<CastExpr>(SubE);
5216 if (CE && CE->getCastKind() == CK_NoOp)
5217 SubE = CE->getSubExpr();
5218 SubE = SubE->IgnoreParens();
5219 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
5220 SubE = BE->getSubExpr();
5221 if (isa<LambdaExpr>(SubE)) {
5222 // For the conversion to block pointer on a lambda expression, we
5223 // construct a special BlockLiteral instead; this doesn't really make
5224 // a difference in ARC, but outside of ARC the resulting block literal
5225 // follows the normal lifetime rules for block literals instead of being
5226 // autoreleased.
5227 DiagnosticErrorTrap Trap(Diags);
5228 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
5229 E->getExprLoc(),
5230 Method, E);
5231 if (Exp.isInvalid())
5232 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
5233 return Exp;
5234 }
5235 }
5236
5237
John Wiegley01296292011-04-08 18:41:53 +00005238 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
5239 FoundDecl, Method);
5240 if (Exp.isInvalid())
Douglas Gregor668443e2011-01-20 00:18:04 +00005241 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00005242
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005243 MemberExpr *ME =
John Wiegley01296292011-04-08 18:41:53 +00005244 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005245 SourceLocation(), Context.BoundMemberTy,
John McCall7decc9e2010-11-18 06:31:45 +00005246 VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005247 if (HadMultipleCandidates)
5248 ME->setHadMultipleCandidates(true);
5249
John McCall7decc9e2010-11-18 06:31:45 +00005250 QualType ResultType = Method->getResultType();
5251 ExprValueKind VK = Expr::getValueKindForType(ResultType);
5252 ResultType = ResultType.getNonLValueExprType(Context);
5253
Eli Friedmanfa0df832012-02-02 03:46:19 +00005254 MarkFunctionReferenced(Exp.get()->getLocStart(), Method);
Douglas Gregor27381f32009-11-23 12:27:39 +00005255 CXXMemberCallExpr *CE =
John McCall7decc9e2010-11-18 06:31:45 +00005256 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
John Wiegley01296292011-04-08 18:41:53 +00005257 Exp.get()->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005258 return CE;
5259}
5260
Sebastian Redl4202c0f2010-09-10 20:55:43 +00005261ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5262 SourceLocation RParen) {
Richard Smithf623c962012-04-17 00:58:00 +00005263 CanThrowResult CanThrow = canThrow(Operand);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00005264 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
Richard Smithf623c962012-04-17 00:58:00 +00005265 CanThrow, KeyLoc, RParen));
Sebastian Redl4202c0f2010-09-10 20:55:43 +00005266}
5267
5268ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
5269 Expr *Operand, SourceLocation RParen) {
5270 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00005271}
5272
Eli Friedmanf798f652012-05-24 22:04:19 +00005273static bool IsSpecialDiscardedValue(Expr *E) {
5274 // In C++11, discarded-value expressions of a certain form are special,
5275 // according to [expr]p10:
5276 // The lvalue-to-rvalue conversion (4.1) is applied only if the
5277 // expression is an lvalue of volatile-qualified type and it has
5278 // one of the following forms:
5279 E = E->IgnoreParens();
5280
Eli Friedmanc49c2262012-05-24 22:36:31 +00005281 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00005282 if (isa<DeclRefExpr>(E))
5283 return true;
5284
Eli Friedmanc49c2262012-05-24 22:36:31 +00005285 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00005286 if (isa<ArraySubscriptExpr>(E))
5287 return true;
5288
Eli Friedmanc49c2262012-05-24 22:36:31 +00005289 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00005290 if (isa<MemberExpr>(E))
5291 return true;
5292
Eli Friedmanc49c2262012-05-24 22:36:31 +00005293 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00005294 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
5295 if (UO->getOpcode() == UO_Deref)
5296 return true;
5297
5298 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00005299 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00005300 if (BO->isPtrMemOp())
5301 return true;
5302
Eli Friedmanc49c2262012-05-24 22:36:31 +00005303 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00005304 if (BO->getOpcode() == BO_Comma)
5305 return IsSpecialDiscardedValue(BO->getRHS());
5306 }
5307
Eli Friedmanc49c2262012-05-24 22:36:31 +00005308 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00005309 // operands are one of the above, or
5310 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
5311 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
5312 IsSpecialDiscardedValue(CO->getFalseExpr());
5313 // The related edge case of "*x ?: *x".
5314 if (BinaryConditionalOperator *BCO =
5315 dyn_cast<BinaryConditionalOperator>(E)) {
5316 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
5317 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
5318 IsSpecialDiscardedValue(BCO->getFalseExpr());
5319 }
5320
5321 // Objective-C++ extensions to the rule.
5322 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
5323 return true;
5324
5325 return false;
5326}
5327
John McCall34376a62010-12-04 03:47:34 +00005328/// Perform the conversions required for an expression used in a
5329/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00005330ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00005331 if (E->hasPlaceholderType()) {
5332 ExprResult result = CheckPlaceholderExpr(E);
5333 if (result.isInvalid()) return Owned(E);
5334 E = result.take();
5335 }
5336
John McCallfee942d2010-12-02 02:07:15 +00005337 // C99 6.3.2.1:
5338 // [Except in specific positions,] an lvalue that does not have
5339 // array type is converted to the value stored in the
5340 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00005341 if (E->isRValue()) {
5342 // In C, function designators (i.e. expressions of function type)
5343 // are r-values, but we still want to do function-to-pointer decay
5344 // on them. This is both technically correct and convenient for
5345 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005346 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00005347 return DefaultFunctionArrayConversion(E);
5348
5349 return Owned(E);
5350 }
John McCallfee942d2010-12-02 02:07:15 +00005351
Eli Friedmanf798f652012-05-24 22:04:19 +00005352 if (getLangOpts().CPlusPlus) {
5353 // The C++11 standard defines the notion of a discarded-value expression;
5354 // normally, we don't need to do anything to handle it, but if it is a
5355 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
5356 // conversion.
5357 if (getLangOpts().CPlusPlus0x && E->isGLValue() &&
5358 E->getType().isVolatileQualified() &&
5359 IsSpecialDiscardedValue(E)) {
5360 ExprResult Res = DefaultLvalueConversion(E);
5361 if (Res.isInvalid())
5362 return Owned(E);
5363 E = Res.take();
5364 }
5365 return Owned(E);
5366 }
John McCall34376a62010-12-04 03:47:34 +00005367
5368 // GCC seems to also exclude expressions of incomplete enum type.
5369 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
5370 if (!T->getDecl()->isComplete()) {
5371 // FIXME: stupid workaround for a codegen bug!
John Wiegley01296292011-04-08 18:41:53 +00005372 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
5373 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00005374 }
5375 }
5376
John Wiegley01296292011-04-08 18:41:53 +00005377 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
5378 if (Res.isInvalid())
5379 return Owned(E);
5380 E = Res.take();
5381
John McCallca61b652010-12-04 12:29:11 +00005382 if (!E->getType()->isVoidType())
5383 RequireCompleteType(E->getExprLoc(), E->getType(),
5384 diag::err_incomplete_type);
John Wiegley01296292011-04-08 18:41:53 +00005385 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00005386}
5387
David Blaikiea5696df2012-05-16 04:20:04 +00005388ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC) {
John Wiegley01296292011-04-08 18:41:53 +00005389 ExprResult FullExpr = Owned(FE);
5390
5391 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00005392 return ExprError();
John McCall34376a62010-12-04 03:47:34 +00005393
John Wiegley01296292011-04-08 18:41:53 +00005394 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00005395 return ExprError();
5396
Douglas Gregor95715f92011-12-15 00:53:32 +00005397 // Top-level message sends default to 'id' when we're in a debugger.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005398 if (getLangOpts().DebuggerCastResultToId &&
Douglas Gregor95715f92011-12-15 00:53:32 +00005399 FullExpr.get()->getType() == Context.UnknownAnyTy &&
5400 isa<ObjCMessageExpr>(FullExpr.get())) {
5401 FullExpr = forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdType());
5402 if (FullExpr.isInvalid())
5403 return ExprError();
5404 }
5405
John McCall3aef3d82011-04-10 19:13:55 +00005406 FullExpr = CheckPlaceholderExpr(FullExpr.take());
5407 if (FullExpr.isInvalid())
5408 return ExprError();
Douglas Gregor0ec210b2011-03-07 02:05:23 +00005409
John Wiegley01296292011-04-08 18:41:53 +00005410 FullExpr = IgnoredValueConversions(FullExpr.take());
5411 if (FullExpr.isInvalid())
5412 return ExprError();
5413
David Blaikiea5696df2012-05-16 04:20:04 +00005414 CheckImplicitConversions(FullExpr.get(), CC);
John McCall5d413782010-12-06 08:20:24 +00005415 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00005416}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00005417
5418StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
5419 if (!FullStmt) return StmtError();
5420
John McCall5d413782010-12-06 08:20:24 +00005421 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00005422}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00005423
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00005424Sema::IfExistsResult
5425Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
5426 CXXScopeSpec &SS,
5427 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00005428 DeclarationName TargetName = TargetNameInfo.getName();
5429 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00005430 return IER_DoesNotExist;
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00005431
Douglas Gregor43edb322011-10-24 22:31:10 +00005432 // If the name itself is dependent, then the result is dependent.
5433 if (TargetName.isDependentName())
5434 return IER_Dependent;
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00005435
Francois Pichet4a7de3e2011-05-06 20:48:22 +00005436 // Do the redeclaration lookup in the current scope.
5437 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
5438 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00005439 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00005440 R.suppressDiagnostics();
Douglas Gregor43edb322011-10-24 22:31:10 +00005441
5442 switch (R.getResultKind()) {
5443 case LookupResult::Found:
5444 case LookupResult::FoundOverloaded:
5445 case LookupResult::FoundUnresolvedValue:
5446 case LookupResult::Ambiguous:
5447 return IER_Exists;
5448
5449 case LookupResult::NotFound:
5450 return IER_DoesNotExist;
5451
5452 case LookupResult::NotFoundInCurrentInstantiation:
5453 return IER_Dependent;
5454 }
David Blaikie8a40f702012-01-17 06:56:22 +00005455
5456 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00005457}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00005458
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00005459Sema::IfExistsResult
5460Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
5461 bool IsIfExists, CXXScopeSpec &SS,
5462 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00005463 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00005464
5465 // Check for unexpanded parameter packs.
5466 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
5467 collectUnexpandedParameterPacks(SS, Unexpanded);
5468 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
5469 if (!Unexpanded.empty()) {
5470 DiagnoseUnexpandedParameterPacks(KeywordLoc,
5471 IsIfExists? UPPC_IfExists
5472 : UPPC_IfNotExists,
5473 Unexpanded);
5474 return IER_Error;
5475 }
5476
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00005477 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
5478}