blob: 73fe0003f024acb201ee1db3668f811de190d8fb [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/AnalysisBasedWarnings.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/AST/ASTContext.h"
Douglas Gregorcc8a5d52010-04-29 00:18:15 +000019#include "clang/AST/CXXInheritance.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000023#include "clang/AST/Expr.h"
Chris Lattner04421082008-04-08 04:40:51 +000024#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000026#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000027#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000031#include "clang/Lex/LiteralSupport.h"
32#include "clang/Lex/Preprocessor.h"
John McCall19510852010-08-20 18:27:03 +000033#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Designator.h"
35#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000036#include "clang/Sema/ScopeInfo.h"
John McCall19510852010-08-20 18:27:03 +000037#include "clang/Sema/ParsedTemplate.h"
John McCall7cd088e2010-08-24 07:21:54 +000038#include "clang/Sema/Template.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000039using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000040using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000041
David Chisnall0f436562009-08-17 16:35:33 +000042
Douglas Gregor48f3bb92009-02-18 21:56:37 +000043/// \brief Determine whether the use of this declaration is valid, and
44/// emit any corresponding diagnostics.
45///
46/// This routine diagnoses various problems with referencing
47/// declarations that can occur when using a declaration. For example,
48/// it might warn if a deprecated or unavailable declaration is being
49/// used, or produce an error (and return true) if a C++0x deleted
50/// function is being used.
51///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000052/// If IgnoreDeprecated is set to true, this should not warn about deprecated
Chris Lattner52338262009-10-25 22:31:57 +000053/// decls.
54///
Douglas Gregor48f3bb92009-02-18 21:56:37 +000055/// \returns true if there was an error (this declaration cannot be
56/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +000057///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000058bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +000059 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor9b623632010-10-12 23:32:35 +000060 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
61 // If there were any diagnostics suppressed by template argument deduction,
62 // emit them now.
63 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
64 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
65 if (Pos != SuppressedDiagnostics.end()) {
66 llvm::SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
67 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
68 Diag(Suppressed[I].first, Suppressed[I].second);
69
70 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000071 // them again for this specialization. However, we don't obsolete this
Douglas Gregor9b623632010-10-12 23:32:35 +000072 // entry from the table, because we want to avoid ever emitting these
73 // diagnostics again.
74 Suppressed.clear();
75 }
76 }
77
Richard Smith34b41d92011-02-20 03:19:35 +000078 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smith483b9f32011-02-21 20:05:19 +000079 if (ParsingInitForAutoVars.count(D)) {
80 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
81 << D->getDeclName();
82 return true;
Richard Smith34b41d92011-02-20 03:19:35 +000083 }
84
Douglas Gregor48f3bb92009-02-18 21:56:37 +000085 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000086 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000087 if (FD->isDeleted()) {
88 Diag(Loc, diag::err_deleted_function_use);
89 Diag(D->getLocation(), diag::note_unavailable_here) << true;
90 return true;
91 }
Douglas Gregor25d944a2009-02-24 04:26:15 +000092 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +000093
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000094 // See if this declaration is unavailable or deprecated.
95 std::string Message;
96 switch (D->getAvailability(&Message)) {
97 case AR_Available:
98 case AR_NotYetIntroduced:
99 break;
100
101 case AR_Deprecated:
102 EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
103 break;
104
105 case AR_Unavailable:
106 if (Message.empty()) {
107 if (!UnknownObjCClass)
108 Diag(Loc, diag::err_unavailable) << D->getDeclName();
109 else
110 Diag(Loc, diag::warn_unavailable_fwdclass_message)
111 << D->getDeclName();
112 }
113 else
114 Diag(Loc, diag::err_unavailable_message)
115 << D->getDeclName() << Message;
116 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
117 break;
118 }
119
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000120 // Warn if this is used but marked unused.
121 if (D->hasAttr<UnusedAttr>())
122 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
123
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000124 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000125}
126
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000127/// \brief Retrieve the message suffix that should be added to a
128/// diagnostic complaining about the given function being deleted or
129/// unavailable.
130std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
131 // FIXME: C++0x implicitly-deleted special member functions could be
132 // detected here so that we could improve diagnostics to say, e.g.,
133 // "base class 'A' had a deleted copy constructor".
134 if (FD->isDeleted())
135 return std::string();
136
137 std::string Message;
138 if (FD->getAvailability(&Message))
139 return ": " + Message;
140
141 return std::string();
142}
143
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000144/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +0000145/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000146/// attribute. It warns if call does not have the sentinel argument.
147///
148void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000149 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000150 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000151 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000152 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000153
154 // FIXME: In C++0x, if any of the arguments are parameter pack
155 // expansions, we can't check for the sentinel now.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000156 int sentinelPos = attr->getSentinel();
157 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +0000158
Mike Stump390b4cc2009-05-16 07:39:55 +0000159 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
160 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000161 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000162 bool warnNotEnoughArgs = false;
163 int isMethod = 0;
164 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
165 // skip over named parameters.
166 ObjCMethodDecl::param_iterator P, E = MD->param_end();
167 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
168 if (nullPos)
169 --nullPos;
170 else
171 ++i;
172 }
173 warnNotEnoughArgs = (P != E || i >= NumArgs);
174 isMethod = 1;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000175 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000176 // skip over named parameters.
177 ObjCMethodDecl::param_iterator P, E = FD->param_end();
178 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
179 if (nullPos)
180 --nullPos;
181 else
182 ++i;
183 }
184 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000185 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000186 // block or function pointer call.
187 QualType Ty = V->getType();
188 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000189 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000190 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
191 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000192 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
193 unsigned NumArgsInProto = Proto->getNumArgs();
194 unsigned k;
195 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
196 if (nullPos)
197 --nullPos;
198 else
199 ++i;
200 }
201 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
202 }
203 if (Ty->isBlockPointerType())
204 isMethod = 2;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000205 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000206 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000207 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000208 return;
209
210 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000211 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000212 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000213 return;
214 }
215 int sentinel = i;
216 while (sentinelPos > 0 && i < NumArgs-1) {
217 --sentinelPos;
218 ++i;
219 }
220 if (sentinelPos > 0) {
221 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000222 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000223 return;
224 }
225 while (i < NumArgs-1) {
226 ++i;
227 ++sentinel;
228 }
229 Expr *sentinelExpr = Args[sentinel];
John McCall8eb662e2010-05-06 23:53:00 +0000230 if (!sentinelExpr) return;
231 if (sentinelExpr->isTypeDependent()) return;
232 if (sentinelExpr->isValueDependent()) return;
Anders Carlsson343e6ff2010-11-05 15:21:33 +0000233
234 // nullptr_t is always treated as null.
235 if (sentinelExpr->getType()->isNullPtrType()) return;
236
Fariborz Jahanian9ccd7252010-07-14 16:37:51 +0000237 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall8eb662e2010-05-06 23:53:00 +0000238 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
239 Expr::NPC_ValueDependentIsNull))
240 return;
241
242 // Unfortunately, __null has type 'int'.
243 if (isa<GNUNullExpr>(sentinelExpr)) return;
244
245 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
246 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000247}
248
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000249SourceRange Sema::getExprRange(ExprTy *E) const {
250 Expr *Ex = (Expr *)E;
251 return Ex? Ex->getSourceRange() : SourceRange();
252}
253
Chris Lattnere7a2e912008-07-25 21:10:04 +0000254//===----------------------------------------------------------------------===//
255// Standard Promotions and Conversions
256//===----------------------------------------------------------------------===//
257
Chris Lattnere7a2e912008-07-25 21:10:04 +0000258/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000259ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000260 QualType Ty = E->getType();
261 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
262
Chris Lattnere7a2e912008-07-25 21:10:04 +0000263 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000264 E = ImpCastExprToType(E, Context.getPointerType(Ty),
265 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000266 else if (Ty->isArrayType()) {
267 // In C90 mode, arrays only promote to pointers if the array expression is
268 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
269 // type 'array of type' is converted to an expression that has type 'pointer
270 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
271 // that has type 'array of type' ...". The relevant change is "an lvalue"
272 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000273 //
274 // C++ 4.2p1:
275 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
276 // T" can be converted to an rvalue of type "pointer to T".
277 //
John McCall7eb0a9e2010-11-24 05:12:34 +0000278 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000279 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
280 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000281 }
John Wiegley429bb272011-04-08 18:41:53 +0000282 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000283}
284
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000285static void CheckForNullPointerDereference(Sema &S, Expr *E) {
286 // Check to see if we are dereferencing a null pointer. If so,
287 // and if not volatile-qualified, this is undefined behavior that the
288 // optimizer will delete, so warn about it. People sometimes try to use this
289 // to get a deterministic trap and are surprised by clang's behavior. This
290 // only handles the pattern "*null", which is a very syntactic check.
291 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
292 if (UO->getOpcode() == UO_Deref &&
293 UO->getSubExpr()->IgnoreParenCasts()->
294 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
295 !UO->getType().isVolatileQualified()) {
296 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
297 S.PDiag(diag::warn_indirection_through_null)
298 << UO->getSubExpr()->getSourceRange());
299 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
300 S.PDiag(diag::note_indirection_through_null));
301 }
302}
303
John Wiegley429bb272011-04-08 18:41:53 +0000304ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000305 // C++ [conv.lval]p1:
306 // A glvalue of a non-function, non-array type T can be
307 // converted to a prvalue.
John Wiegley429bb272011-04-08 18:41:53 +0000308 if (!E->isGLValue()) return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +0000309
John McCall409fa9a2010-12-06 20:48:59 +0000310 QualType T = E->getType();
311 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000312
John McCall409fa9a2010-12-06 20:48:59 +0000313 // Create a load out of an ObjCProperty l-value, if necessary.
314 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley429bb272011-04-08 18:41:53 +0000315 ExprResult Res = ConvertPropertyForRValue(E);
316 if (Res.isInvalid())
317 return Owned(E);
318 E = Res.take();
John McCall409fa9a2010-12-06 20:48:59 +0000319 if (!E->isGLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000320 return Owned(E);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000321 }
John McCall409fa9a2010-12-06 20:48:59 +0000322
323 // We don't want to throw lvalue-to-rvalue casts on top of
324 // expressions of certain types in C++.
325 if (getLangOptions().CPlusPlus &&
326 (E->getType() == Context.OverloadTy ||
327 T->isDependentType() ||
328 T->isRecordType()))
John Wiegley429bb272011-04-08 18:41:53 +0000329 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000330
331 // The C standard is actually really unclear on this point, and
332 // DR106 tells us what the result should be but not why. It's
333 // generally best to say that void types just doesn't undergo
334 // lvalue-to-rvalue at all. Note that expressions of unqualified
335 // 'void' type are never l-values, but qualified void can be.
336 if (T->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +0000337 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000338
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000339 CheckForNullPointerDereference(*this, E);
340
John McCall409fa9a2010-12-06 20:48:59 +0000341 // C++ [conv.lval]p1:
342 // [...] If T is a non-class type, the type of the prvalue is the
343 // cv-unqualified version of T. Otherwise, the type of the
344 // rvalue is T.
345 //
346 // C99 6.3.2.1p2:
347 // If the lvalue has qualified type, the value has the unqualified
348 // version of the type of the lvalue; otherwise, the value has the
349 // type of the lvalue.
350 if (T.hasQualifiers())
351 T = T.getUnqualifiedType();
352
Ted Kremenek3aea4da2011-03-01 18:41:00 +0000353 CheckArrayAccess(E);
Ted Kremeneka0125d82011-02-16 01:57:07 +0000354
John Wiegley429bb272011-04-08 18:41:53 +0000355 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
356 E, 0, VK_RValue));
John McCall409fa9a2010-12-06 20:48:59 +0000357}
358
John Wiegley429bb272011-04-08 18:41:53 +0000359ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
360 ExprResult Res = DefaultFunctionArrayConversion(E);
361 if (Res.isInvalid())
362 return ExprError();
363 Res = DefaultLvalueConversion(Res.take());
364 if (Res.isInvalid())
365 return ExprError();
366 return move(Res);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000367}
368
369
Chris Lattnere7a2e912008-07-25 21:10:04 +0000370/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000371/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000372/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000373/// apply if the array is an argument to the sizeof or address (&) operators.
374/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000375ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000376 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000377 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
378 if (Res.isInvalid())
379 return Owned(E);
380 E = Res.take();
John McCall0ae287a2010-12-01 04:43:34 +0000381
382 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000383 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCall0ae287a2010-12-01 04:43:34 +0000384
385 // Try to perform integral promotions if the object has a theoretically
386 // promotable type.
387 if (Ty->isIntegralOrUnscopedEnumerationType()) {
388 // C99 6.3.1.1p2:
389 //
390 // The following may be used in an expression wherever an int or
391 // unsigned int may be used:
392 // - an object or expression with an integer type whose integer
393 // conversion rank is less than or equal to the rank of int
394 // and unsigned int.
395 // - A bit-field of type _Bool, int, signed int, or unsigned int.
396 //
397 // If an int can represent all values of the original type, the
398 // value is converted to an int; otherwise, it is converted to an
399 // unsigned int. These are called the integer promotions. All
400 // other types are unchanged by the integer promotions.
401
402 QualType PTy = Context.isPromotableBitField(E);
403 if (!PTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +0000404 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
405 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000406 }
407 if (Ty->isPromotableIntegerType()) {
408 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000409 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
410 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000411 }
Eli Friedman04e83572009-08-20 04:21:42 +0000412 }
John Wiegley429bb272011-04-08 18:41:53 +0000413 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000414}
415
Chris Lattner05faf172008-07-25 22:25:12 +0000416/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000417/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000418/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000419ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
420 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000421 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000422
John Wiegley429bb272011-04-08 18:41:53 +0000423 ExprResult Res = UsualUnaryConversions(E);
424 if (Res.isInvalid())
425 return Owned(E);
426 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000427
Chris Lattner05faf172008-07-25 22:25:12 +0000428 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000429 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000430 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
431
432 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000433}
434
Chris Lattner312531a2009-04-12 08:11:20 +0000435/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
436/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley429bb272011-04-08 18:41:53 +0000437/// interfaces passed by value.
438ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
Chris Lattner40378332010-05-16 04:01:30 +0000439 FunctionDecl *FDecl) {
John Wiegley429bb272011-04-08 18:41:53 +0000440 ExprResult ExprRes = DefaultArgumentPromotion(E);
441 if (ExprRes.isInvalid())
442 return ExprError();
443 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Chris Lattner40378332010-05-16 04:01:30 +0000445 // __builtin_va_start takes the second argument as a "varargs" argument, but
446 // it doesn't actually do anything with it. It doesn't need to be non-pod
447 // etc.
448 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
John Wiegley429bb272011-04-08 18:41:53 +0000449 return Owned(E);
Chris Lattner40378332010-05-16 04:01:30 +0000450
John Wiegley429bb272011-04-08 18:41:53 +0000451 if (E->getType()->isObjCObjectType() &&
452 DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000453 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
John Wiegley429bb272011-04-08 18:41:53 +0000454 << E->getType() << CT))
455 return ExprError();
Douglas Gregor75b699a2009-12-12 07:25:49 +0000456
John Wiegley429bb272011-04-08 18:41:53 +0000457 if (!E->getType()->isPODType() &&
458 DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000459 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
John Wiegley429bb272011-04-08 18:41:53 +0000460 << E->getType() << CT))
461 return ExprError();
Chris Lattner312531a2009-04-12 08:11:20 +0000462
John Wiegley429bb272011-04-08 18:41:53 +0000463 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000464}
465
Chris Lattnere7a2e912008-07-25 21:10:04 +0000466/// UsualArithmeticConversions - Performs various conversions that are common to
467/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000468/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000469/// responsible for emitting appropriate error diagnostics.
470/// FIXME: verify the conversion rules for "complex int" are consistent with
471/// GCC.
John Wiegley429bb272011-04-08 18:41:53 +0000472QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr, ExprResult &rhsExpr,
Chris Lattnere7a2e912008-07-25 21:10:04 +0000473 bool isCompAssign) {
John Wiegley429bb272011-04-08 18:41:53 +0000474 if (!isCompAssign) {
475 lhsExpr = UsualUnaryConversions(lhsExpr.take());
476 if (lhsExpr.isInvalid())
477 return QualType();
478 }
Eli Friedmanab3a8522009-03-28 01:22:36 +0000479
John Wiegley429bb272011-04-08 18:41:53 +0000480 rhsExpr = UsualUnaryConversions(rhsExpr.take());
481 if (rhsExpr.isInvalid())
482 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000483
Mike Stump1eb44332009-09-09 15:08:12 +0000484 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000485 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000486 QualType lhs =
John Wiegley429bb272011-04-08 18:41:53 +0000487 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000488 QualType rhs =
John Wiegley429bb272011-04-08 18:41:53 +0000489 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000490
491 // If both types are identical, no conversion is needed.
492 if (lhs == rhs)
493 return lhs;
494
495 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
496 // The caller can deal with this (e.g. pointer + int).
497 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
498 return lhs;
499
John McCallcf33b242010-11-13 08:17:45 +0000500 // Apply unary and bitfield promotions to the LHS's type.
501 QualType lhs_unpromoted = lhs;
502 if (lhs->isPromotableIntegerType())
503 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley429bb272011-04-08 18:41:53 +0000504 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +0000505 if (!LHSBitfieldPromoteTy.isNull())
506 lhs = LHSBitfieldPromoteTy;
John McCallcf33b242010-11-13 08:17:45 +0000507 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000508 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000509
John McCallcf33b242010-11-13 08:17:45 +0000510 // If both types are identical, no conversion is needed.
511 if (lhs == rhs)
512 return lhs;
513
514 // At this point, we have two different arithmetic types.
515
516 // Handle complex types first (C99 6.3.1.8p1).
517 bool LHSComplexFloat = lhs->isComplexType();
518 bool RHSComplexFloat = rhs->isComplexType();
519 if (LHSComplexFloat || RHSComplexFloat) {
520 // if we have an integer operand, the result is the complex type.
521
John McCall2bb5d002010-11-13 09:02:35 +0000522 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
523 if (rhs->isIntegerType()) {
524 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000525 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
526 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000527 } else {
528 assert(rhs->isComplexIntegerType());
John Wiegley429bb272011-04-08 18:41:53 +0000529 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000530 }
John McCallcf33b242010-11-13 08:17:45 +0000531 return lhs;
532 }
533
John McCall2bb5d002010-11-13 09:02:35 +0000534 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
535 if (!isCompAssign) {
536 // int -> float -> _Complex float
537 if (lhs->isIntegerType()) {
538 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000539 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_IntegralToFloating);
540 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000541 } else {
542 assert(lhs->isComplexIntegerType());
John Wiegley429bb272011-04-08 18:41:53 +0000543 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000544 }
545 }
John McCallcf33b242010-11-13 08:17:45 +0000546 return rhs;
547 }
548
549 // This handles complex/complex, complex/float, or float/complex.
550 // When both operands are complex, the shorter operand is converted to the
551 // type of the longer, and that is the type of the result. This corresponds
552 // to what is done when combining two real floating-point operands.
553 // The fun begins when size promotion occur across type domains.
554 // From H&S 6.3.4: When one operand is complex and the other is a real
555 // floating-point type, the less precise type is converted, within it's
556 // real or complex domain, to the precision of the other type. For example,
557 // when combining a "long double" with a "double _Complex", the
558 // "double _Complex" is promoted to "long double _Complex".
559 int order = Context.getFloatingTypeOrder(lhs, rhs);
560
561 // If both are complex, just cast to the more precise type.
562 if (LHSComplexFloat && RHSComplexFloat) {
563 if (order > 0) {
564 // _Complex float -> _Complex double
John Wiegley429bb272011-04-08 18:41:53 +0000565 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000566 return lhs;
567
568 } else if (order < 0) {
569 // _Complex float -> _Complex double
570 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000571 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000572 return rhs;
573 }
574 return lhs;
575 }
576
577 // If just the LHS is complex, the RHS needs to be converted,
578 // and the LHS might need to be promoted.
579 if (LHSComplexFloat) {
580 if (order > 0) { // LHS is wider
581 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000582 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000583 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
584 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000585 return lhs;
586 }
587
588 // RHS is at least as wide. Find its corresponding complex type.
589 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
590
591 // double -> _Complex double
John Wiegley429bb272011-04-08 18:41:53 +0000592 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000593
594 // _Complex float -> _Complex double
595 if (!isCompAssign && order < 0)
John Wiegley429bb272011-04-08 18:41:53 +0000596 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000597
598 return result;
599 }
600
601 // Just the RHS is complex, so the LHS needs to be converted
602 // and the RHS might need to be promoted.
603 assert(RHSComplexFloat);
604
605 if (order < 0) { // RHS is wider
606 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000607 if (!isCompAssign) {
Argyrios Kyrtzidise1889332011-01-18 18:49:33 +0000608 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000609 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
610 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000611 }
John McCallcf33b242010-11-13 08:17:45 +0000612 return rhs;
613 }
614
615 // LHS is at least as wide. Find its corresponding complex type.
616 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
617
618 // double -> _Complex double
619 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000620 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000621
622 // _Complex float -> _Complex double
623 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +0000624 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000625
626 return result;
627 }
628
629 // Now handle "real" floating types (i.e. float, double, long double).
630 bool LHSFloat = lhs->isRealFloatingType();
631 bool RHSFloat = rhs->isRealFloatingType();
632 if (LHSFloat || RHSFloat) {
633 // If we have two real floating types, convert the smaller operand
634 // to the bigger result.
635 if (LHSFloat && RHSFloat) {
636 int order = Context.getFloatingTypeOrder(lhs, rhs);
637 if (order > 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000638 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCallcf33b242010-11-13 08:17:45 +0000639 return lhs;
640 }
641
642 assert(order < 0 && "illegal float comparison");
643 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000644 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCallcf33b242010-11-13 08:17:45 +0000645 return rhs;
646 }
647
648 // If we have an integer operand, the result is the real floating type.
649 if (LHSFloat) {
650 if (rhs->isIntegerType()) {
651 // Convert rhs to the lhs floating point type.
John Wiegley429bb272011-04-08 18:41:53 +0000652 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCallcf33b242010-11-13 08:17:45 +0000653 return lhs;
654 }
655
656 // Convert both sides to the appropriate complex float.
657 assert(rhs->isComplexIntegerType());
658 QualType result = Context.getComplexType(lhs);
659
660 // _Complex int -> _Complex float
John Wiegley429bb272011-04-08 18:41:53 +0000661 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000662
663 // float -> _Complex float
664 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000665 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000666
667 return result;
668 }
669
670 assert(RHSFloat);
671 if (lhs->isIntegerType()) {
672 // Convert lhs to the rhs floating point type.
673 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000674 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCallcf33b242010-11-13 08:17:45 +0000675 return rhs;
676 }
677
678 // Convert both sides to the appropriate complex float.
679 assert(lhs->isComplexIntegerType());
680 QualType result = Context.getComplexType(rhs);
681
682 // _Complex int -> _Complex float
683 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000684 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000685
686 // float -> _Complex float
John Wiegley429bb272011-04-08 18:41:53 +0000687 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000688
689 return result;
690 }
691
692 // Handle GCC complex int extension.
693 // FIXME: if the operands are (int, _Complex long), we currently
694 // don't promote the complex. Also, signedness?
695 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
696 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
697 if (lhsComplexInt && rhsComplexInt) {
698 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
699 rhsComplexInt->getElementType());
700 assert(order && "inequal types with equal element ordering");
701 if (order > 0) {
702 // _Complex int -> _Complex long
John Wiegley429bb272011-04-08 18:41:53 +0000703 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000704 return lhs;
705 }
706
707 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000708 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000709 return rhs;
710 } else if (lhsComplexInt) {
711 // int -> _Complex int
John Wiegley429bb272011-04-08 18:41:53 +0000712 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000713 return lhs;
714 } else if (rhsComplexInt) {
715 // int -> _Complex int
716 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000717 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000718 return rhs;
719 }
720
721 // Finally, we have two differing integer types.
722 // The rules for this case are in C99 6.3.1.8
723 int compare = Context.getIntegerTypeOrder(lhs, rhs);
724 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
725 rhsSigned = rhs->hasSignedIntegerRepresentation();
726 if (lhsSigned == rhsSigned) {
727 // Same signedness; use the higher-ranked type
728 if (compare >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000729 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000730 return lhs;
731 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000732 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000733 return rhs;
734 } else if (compare != (lhsSigned ? 1 : -1)) {
735 // The unsigned type has greater than or equal rank to the
736 // signed type, so use the unsigned type
737 if (rhsSigned) {
John Wiegley429bb272011-04-08 18:41:53 +0000738 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000739 return lhs;
740 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000741 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000742 return rhs;
743 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
744 // The two types are different widths; if we are here, that
745 // means the signed type is larger than the unsigned type, so
746 // use the signed type.
747 if (lhsSigned) {
John Wiegley429bb272011-04-08 18:41:53 +0000748 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000749 return lhs;
750 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000751 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000752 return rhs;
753 } else {
754 // The signed type is higher-ranked than the unsigned type,
755 // but isn't actually any bigger (like unsigned int and long
756 // on most 32-bit systems). Use the unsigned type corresponding
757 // to the signed type.
758 QualType result =
759 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
John Wiegley429bb272011-04-08 18:41:53 +0000760 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000761 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000762 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000763 return result;
764 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000765}
766
Chris Lattnere7a2e912008-07-25 21:10:04 +0000767//===----------------------------------------------------------------------===//
768// Semantic Analysis for various Expression Types
769//===----------------------------------------------------------------------===//
770
771
Peter Collingbournef111d932011-04-15 00:35:48 +0000772ExprResult
773Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
774 SourceLocation DefaultLoc,
775 SourceLocation RParenLoc,
776 Expr *ControllingExpr,
777 MultiTypeArg types,
778 MultiExprArg exprs) {
779 unsigned NumAssocs = types.size();
780 assert(NumAssocs == exprs.size());
781
782 ParsedType *ParsedTypes = types.release();
783 Expr **Exprs = exprs.release();
784
785 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
786 for (unsigned i = 0; i < NumAssocs; ++i) {
787 if (ParsedTypes[i])
788 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
789 else
790 Types[i] = 0;
791 }
792
793 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
794 ControllingExpr, Types, Exprs,
795 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +0000796 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +0000797 return ER;
798}
799
800ExprResult
801Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
802 SourceLocation DefaultLoc,
803 SourceLocation RParenLoc,
804 Expr *ControllingExpr,
805 TypeSourceInfo **Types,
806 Expr **Exprs,
807 unsigned NumAssocs) {
808 bool TypeErrorFound = false,
809 IsResultDependent = ControllingExpr->isTypeDependent(),
810 ContainsUnexpandedParameterPack
811 = ControllingExpr->containsUnexpandedParameterPack();
812
813 for (unsigned i = 0; i < NumAssocs; ++i) {
814 if (Exprs[i]->containsUnexpandedParameterPack())
815 ContainsUnexpandedParameterPack = true;
816
817 if (Types[i]) {
818 if (Types[i]->getType()->containsUnexpandedParameterPack())
819 ContainsUnexpandedParameterPack = true;
820
821 if (Types[i]->getType()->isDependentType()) {
822 IsResultDependent = true;
823 } else {
824 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
825 // complete object type other than a variably modified type."
826 unsigned D = 0;
827 if (Types[i]->getType()->isIncompleteType())
828 D = diag::err_assoc_type_incomplete;
829 else if (!Types[i]->getType()->isObjectType())
830 D = diag::err_assoc_type_nonobject;
831 else if (Types[i]->getType()->isVariablyModifiedType())
832 D = diag::err_assoc_type_variably_modified;
833
834 if (D != 0) {
835 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
836 << Types[i]->getTypeLoc().getSourceRange()
837 << Types[i]->getType();
838 TypeErrorFound = true;
839 }
840
841 // C1X 6.5.1.1p2 "No two generic associations in the same generic
842 // selection shall specify compatible types."
843 for (unsigned j = i+1; j < NumAssocs; ++j)
844 if (Types[j] && !Types[j]->getType()->isDependentType() &&
845 Context.typesAreCompatible(Types[i]->getType(),
846 Types[j]->getType())) {
847 Diag(Types[j]->getTypeLoc().getBeginLoc(),
848 diag::err_assoc_compatible_types)
849 << Types[j]->getTypeLoc().getSourceRange()
850 << Types[j]->getType()
851 << Types[i]->getType();
852 Diag(Types[i]->getTypeLoc().getBeginLoc(),
853 diag::note_compat_assoc)
854 << Types[i]->getTypeLoc().getSourceRange()
855 << Types[i]->getType();
856 TypeErrorFound = true;
857 }
858 }
859 }
860 }
861 if (TypeErrorFound)
862 return ExprError();
863
864 // If we determined that the generic selection is result-dependent, don't
865 // try to compute the result expression.
866 if (IsResultDependent)
867 return Owned(new (Context) GenericSelectionExpr(
868 Context, KeyLoc, ControllingExpr,
869 Types, Exprs, NumAssocs, DefaultLoc,
870 RParenLoc, ContainsUnexpandedParameterPack));
871
872 llvm::SmallVector<unsigned, 1> CompatIndices;
873 unsigned DefaultIndex = -1U;
874 for (unsigned i = 0; i < NumAssocs; ++i) {
875 if (!Types[i])
876 DefaultIndex = i;
877 else if (Context.typesAreCompatible(ControllingExpr->getType(),
878 Types[i]->getType()))
879 CompatIndices.push_back(i);
880 }
881
882 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
883 // type compatible with at most one of the types named in its generic
884 // association list."
885 if (CompatIndices.size() > 1) {
886 // We strip parens here because the controlling expression is typically
887 // parenthesized in macro definitions.
888 ControllingExpr = ControllingExpr->IgnoreParens();
889 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
890 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
891 << (unsigned) CompatIndices.size();
892 for (llvm::SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
893 E = CompatIndices.end(); I != E; ++I) {
894 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
895 diag::note_compat_assoc)
896 << Types[*I]->getTypeLoc().getSourceRange()
897 << Types[*I]->getType();
898 }
899 return ExprError();
900 }
901
902 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
903 // its controlling expression shall have type compatible with exactly one of
904 // the types named in its generic association list."
905 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
906 // We strip parens here because the controlling expression is typically
907 // parenthesized in macro definitions.
908 ControllingExpr = ControllingExpr->IgnoreParens();
909 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
910 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
911 return ExprError();
912 }
913
914 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
915 // type name that is compatible with the type of the controlling expression,
916 // then the result expression of the generic selection is the expression
917 // in that generic association. Otherwise, the result expression of the
918 // generic selection is the expression in the default generic association."
919 unsigned ResultIndex =
920 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
921
922 return Owned(new (Context) GenericSelectionExpr(
923 Context, KeyLoc, ControllingExpr,
924 Types, Exprs, NumAssocs, DefaultLoc,
925 RParenLoc, ContainsUnexpandedParameterPack,
926 ResultIndex));
927}
928
Steve Narofff69936d2007-09-16 03:34:24 +0000929/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000930/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
931/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
932/// multiple tokens. However, the common case is that StringToks points to one
933/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000934///
John McCall60d7b3a2010-08-24 06:29:42 +0000935ExprResult
Sean Hunt6cf75022010-08-30 17:47:05 +0000936Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000937 assert(NumStringToks && "Must have at least one string!");
938
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000939 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000940 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000941 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000942
943 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
944 for (unsigned i = 0; i != NumStringToks; ++i)
945 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000946
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000947 QualType StrTy = Context.CharTy;
Anders Carlsson96b4adc2011-04-06 18:42:48 +0000948 if (Literal.AnyWide)
949 StrTy = Context.getWCharType();
950 else if (Literal.Pascal)
951 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000952
953 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +0000954 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +0000955 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000956
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000957 // Get an array type for the string, according to C99 6.4.5. This includes
958 // the nul terminator character as well as the string length for pascal
959 // strings.
960 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000961 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000962 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000963
Reid Spencer5f016e22007-07-11 17:01:13 +0000964 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sean Hunt6cf75022010-08-30 17:47:05 +0000965 return Owned(StringLiteral::Create(Context, Literal.GetString(),
966 Literal.GetStringLength(),
Anders Carlsson3e2193c2011-04-14 00:40:03 +0000967 Literal.AnyWide, Literal.Pascal, StrTy,
Sean Hunt6cf75022010-08-30 17:47:05 +0000968 &StringTokLocs[0],
969 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000970}
971
John McCall469a1eb2011-02-02 13:00:07 +0000972enum CaptureResult {
973 /// No capture is required.
974 CR_NoCapture,
975
976 /// A capture is required.
977 CR_Capture,
978
John McCall6b5a61b2011-02-07 10:33:21 +0000979 /// A by-ref capture is required.
980 CR_CaptureByRef,
981
John McCall469a1eb2011-02-02 13:00:07 +0000982 /// An error occurred when trying to capture the given variable.
983 CR_Error
984};
985
986/// Diagnose an uncapturable value reference.
Chris Lattner639e2d32008-10-20 05:16:36 +0000987///
John McCall469a1eb2011-02-02 13:00:07 +0000988/// \param var - the variable referenced
989/// \param DC - the context which we couldn't capture through
990static CaptureResult
John McCall6b5a61b2011-02-07 10:33:21 +0000991diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +0000992 VarDecl *var, DeclContext *DC) {
993 switch (S.ExprEvalContexts.back().Context) {
994 case Sema::Unevaluated:
995 // The argument will never be evaluated, so don't complain.
996 return CR_NoCapture;
Mike Stump1eb44332009-09-09 15:08:12 +0000997
John McCall469a1eb2011-02-02 13:00:07 +0000998 case Sema::PotentiallyEvaluated:
999 case Sema::PotentiallyEvaluatedIfUsed:
1000 break;
Chris Lattner639e2d32008-10-20 05:16:36 +00001001
John McCall469a1eb2011-02-02 13:00:07 +00001002 case Sema::PotentiallyPotentiallyEvaluated:
1003 // FIXME: delay these!
1004 break;
Chris Lattner17f3a6d2009-04-21 22:26:47 +00001005 }
Mike Stump1eb44332009-09-09 15:08:12 +00001006
John McCall469a1eb2011-02-02 13:00:07 +00001007 // Don't diagnose about capture if we're not actually in code right
1008 // now; in general, there are more appropriate places that will
1009 // diagnose this.
1010 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1011
John McCall4f38f412011-03-22 23:15:50 +00001012 // Certain madnesses can happen with parameter declarations, which
1013 // we want to ignore.
1014 if (isa<ParmVarDecl>(var)) {
1015 // - If the parameter still belongs to the translation unit, then
1016 // we're actually just using one parameter in the declaration of
1017 // the next. This is useful in e.g. VLAs.
1018 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1019 return CR_NoCapture;
1020
1021 // - This particular madness can happen in ill-formed default
1022 // arguments; claim it's okay and let downstream code handle it.
1023 if (S.CurContext == var->getDeclContext()->getParent())
1024 return CR_NoCapture;
1025 }
John McCall469a1eb2011-02-02 13:00:07 +00001026
1027 DeclarationName functionName;
1028 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1029 functionName = fn->getDeclName();
1030 // FIXME: variable from enclosing block that we couldn't capture from!
1031
1032 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1033 << var->getIdentifier() << functionName;
1034 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1035 << var->getIdentifier();
1036
1037 return CR_Error;
Mike Stump1eb44332009-09-09 15:08:12 +00001038}
1039
John McCall6b5a61b2011-02-07 10:33:21 +00001040/// There is a well-formed capture at a particular scope level;
1041/// propagate it through all the nested blocks.
1042static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1043 const BlockDecl::Capture &capture) {
1044 VarDecl *var = capture.getVariable();
1045
1046 // Update all the inner blocks with the capture information.
1047 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1048 i != e; ++i) {
1049 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1050 innerBlock->Captures.push_back(
1051 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1052 /*nested*/ true, capture.getCopyExpr()));
1053 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1054 }
1055
1056 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1057}
1058
1059/// shouldCaptureValueReference - Determine if a reference to the
John McCall469a1eb2011-02-02 13:00:07 +00001060/// given value in the current context requires a variable capture.
1061///
1062/// This also keeps the captures set in the BlockScopeInfo records
1063/// up-to-date.
John McCall6b5a61b2011-02-07 10:33:21 +00001064static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +00001065 ValueDecl *value) {
1066 // Only variables ever require capture.
1067 VarDecl *var = dyn_cast<VarDecl>(value);
John McCall76a40212011-02-09 01:13:10 +00001068 if (!var) return CR_NoCapture;
John McCall469a1eb2011-02-02 13:00:07 +00001069
1070 // Fast path: variables from the current context never require capture.
1071 DeclContext *DC = S.CurContext;
1072 if (var->getDeclContext() == DC) return CR_NoCapture;
1073
1074 // Only variables with local storage require capture.
1075 // FIXME: What about 'const' variables in C++?
1076 if (!var->hasLocalStorage()) return CR_NoCapture;
1077
1078 // Otherwise, we need to capture.
1079
1080 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCall469a1eb2011-02-02 13:00:07 +00001081 do {
1082 // Only blocks (and eventually C++0x closures) can capture; other
1083 // scopes don't work.
1084 if (!isa<BlockDecl>(DC))
John McCall6b5a61b2011-02-07 10:33:21 +00001085 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCall469a1eb2011-02-02 13:00:07 +00001086
1087 BlockScopeInfo *blockScope =
1088 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1089 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1090
John McCall6b5a61b2011-02-07 10:33:21 +00001091 // Check whether we've already captured it in this block. If so,
1092 // we're done.
1093 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1094 return propagateCapture(S, functionScopesIndex,
1095 blockScope->Captures[indexPlus1 - 1]);
John McCall469a1eb2011-02-02 13:00:07 +00001096
1097 functionScopesIndex--;
1098 DC = cast<BlockDecl>(DC)->getDeclContext();
1099 } while (var->getDeclContext() != DC);
1100
John McCall6b5a61b2011-02-07 10:33:21 +00001101 // Okay, we descended all the way to the block that defines the variable.
1102 // Actually try to capture it.
1103 QualType type = var->getType();
1104
1105 // Prohibit variably-modified types.
1106 if (type->isVariablyModifiedType()) {
1107 S.Diag(loc, diag::err_ref_vm_type);
1108 S.Diag(var->getLocation(), diag::note_declared_at);
1109 return CR_Error;
1110 }
1111
1112 // Prohibit arrays, even in __block variables, but not references to
1113 // them.
1114 if (type->isArrayType()) {
1115 S.Diag(loc, diag::err_ref_array_type);
1116 S.Diag(var->getLocation(), diag::note_declared_at);
1117 return CR_Error;
1118 }
1119
1120 S.MarkDeclarationReferenced(loc, var);
1121
1122 // The BlocksAttr indicates the variable is bound by-reference.
1123 bool byRef = var->hasAttr<BlocksAttr>();
1124
1125 // Build a copy expression.
1126 Expr *copyExpr = 0;
1127 if (!byRef && S.getLangOptions().CPlusPlus &&
1128 !type->isDependentType() && type->isStructureOrClassType()) {
1129 // According to the blocks spec, the capture of a variable from
1130 // the stack requires a const copy constructor. This is not true
1131 // of the copy/move done to move a __block variable to the heap.
1132 type.addConst();
1133
1134 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1135 ExprResult result =
1136 S.PerformCopyInitialization(
1137 InitializedEntity::InitializeBlock(var->getLocation(),
1138 type, false),
1139 loc, S.Owned(declRef));
1140
1141 // Build a full-expression copy expression if initialization
1142 // succeeded and used a non-trivial constructor. Recover from
1143 // errors by pretending that the copy isn't necessary.
1144 if (!result.isInvalid() &&
1145 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1146 result = S.MaybeCreateExprWithCleanups(result);
1147 copyExpr = result.take();
1148 }
1149 }
1150
1151 // We're currently at the declarer; go back to the closure.
1152 functionScopesIndex++;
1153 BlockScopeInfo *blockScope =
1154 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1155
1156 // Build a valid capture in this scope.
1157 blockScope->Captures.push_back(
1158 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1159 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1160
1161 // Propagate that to inner captures if necessary.
1162 return propagateCapture(S, functionScopesIndex,
1163 blockScope->Captures.back());
1164}
1165
1166static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1167 const DeclarationNameInfo &NameInfo,
1168 bool byRef) {
1169 assert(isa<VarDecl>(vd) && "capturing non-variable");
1170
1171 VarDecl *var = cast<VarDecl>(vd);
1172 assert(var->hasLocalStorage() && "capturing non-local");
1173 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1174
1175 QualType exprType = var->getType().getNonReferenceType();
1176
1177 BlockDeclRefExpr *BDRE;
1178 if (!byRef) {
1179 // The variable will be bound by copy; make it const within the
1180 // closure, but record that this was done in the expression.
1181 bool constAdded = !exprType.isConstQualified();
1182 exprType.addConst();
1183
1184 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1185 NameInfo.getLoc(), false,
1186 constAdded);
1187 } else {
1188 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1189 NameInfo.getLoc(), true);
1190 }
1191
1192 return S.Owned(BDRE);
John McCall469a1eb2011-02-02 13:00:07 +00001193}
Chris Lattner639e2d32008-10-20 05:16:36 +00001194
John McCall60d7b3a2010-08-24 06:29:42 +00001195ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001196Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001197 SourceLocation Loc,
1198 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001199 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001200 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001201}
1202
John McCall76a40212011-02-09 01:13:10 +00001203/// BuildDeclRefExpr - Build an expression that references a
1204/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001205ExprResult
John McCall76a40212011-02-09 01:13:10 +00001206Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001207 const DeclarationNameInfo &NameInfo,
1208 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001209 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +00001210
John McCall7eb0a9e2010-11-24 05:12:34 +00001211 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +00001212 SS? SS->getWithLocInContext(Context)
1213 : NestedNameSpecifierLoc(),
John McCall7eb0a9e2010-11-24 05:12:34 +00001214 D, NameInfo, Ty, VK);
1215
1216 // Just in case we're building an illegal pointer-to-member.
1217 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1218 E->setObjectKind(OK_BitField);
1219
1220 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001221}
1222
John McCalldfa1edb2010-11-23 20:48:44 +00001223static ExprResult
1224BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1225 const CXXScopeSpec &SS, FieldDecl *Field,
1226 DeclAccessPair FoundDecl,
1227 const DeclarationNameInfo &MemberNameInfo);
1228
John McCall60d7b3a2010-08-24 06:29:42 +00001229ExprResult
John McCall5808ce42011-02-03 08:15:49 +00001230Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
1231 SourceLocation loc,
1232 IndirectFieldDecl *indirectField,
1233 Expr *baseObjectExpr,
1234 SourceLocation opLoc) {
1235 // First, build the expression that refers to the base object.
1236
1237 bool baseObjectIsPointer = false;
1238 Qualifiers baseQuals;
1239
1240 // Case 1: the base of the indirect field is not a field.
1241 VarDecl *baseVariable = indirectField->getVarDecl();
Douglas Gregorf5848322011-02-18 02:44:58 +00001242 CXXScopeSpec EmptySS;
John McCall5808ce42011-02-03 08:15:49 +00001243 if (baseVariable) {
1244 assert(baseVariable->getType()->isRecordType());
1245
1246 // In principle we could have a member access expression that
1247 // accesses an anonymous struct/union that's a static member of
1248 // the base object's class. However, under the current standard,
1249 // static data members cannot be anonymous structs or unions.
1250 // Supporting this is as easy as building a MemberExpr here.
1251 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1252
1253 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1254
1255 ExprResult result =
Douglas Gregorf5848322011-02-18 02:44:58 +00001256 BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
John McCall5808ce42011-02-03 08:15:49 +00001257 if (result.isInvalid()) return ExprError();
1258
1259 baseObjectExpr = result.take();
1260 baseObjectIsPointer = false;
1261 baseQuals = baseObjectExpr->getType().getQualifiers();
1262
1263 // Case 2: the base of the indirect field is a field and the user
1264 // wrote a member expression.
1265 } else if (baseObjectExpr) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001266 // The caller provided the base object expression. Determine
1267 // whether its a pointer and whether it adds any qualifiers to the
1268 // anonymous struct/union fields we're looking into.
John McCall5808ce42011-02-03 08:15:49 +00001269 QualType objectType = baseObjectExpr->getType();
1270
1271 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1272 baseObjectIsPointer = true;
1273 objectType = ptr->getPointeeType();
1274 } else {
1275 baseObjectIsPointer = false;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001276 }
John McCall5808ce42011-02-03 08:15:49 +00001277 baseQuals = objectType.getQualifiers();
1278
1279 // Case 3: the base of the indirect field is a field and we should
1280 // build an implicit member access.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001281 } else {
1282 // We've found a member of an anonymous struct/union that is
1283 // inside a non-anonymous struct/union, so in a well-formed
1284 // program our base object expression is "this".
John McCall5808ce42011-02-03 08:15:49 +00001285 CXXMethodDecl *method = tryCaptureCXXThis();
1286 if (!method) {
1287 Diag(loc, diag::err_invalid_member_use_in_static_method)
1288 << indirectField->getDeclName();
1289 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001290 }
1291
John McCall5808ce42011-02-03 08:15:49 +00001292 // Our base object expression is "this".
1293 baseObjectExpr =
1294 new (Context) CXXThisExpr(loc, method->getThisType(Context),
1295 /*isImplicit=*/ true);
1296 baseObjectIsPointer = true;
1297 baseQuals = Qualifiers::fromCVRMask(method->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001298 }
1299
1300 // Build the implicit member references to the field of the
1301 // anonymous struct/union.
John McCall5808ce42011-02-03 08:15:49 +00001302 Expr *result = baseObjectExpr;
1303 IndirectFieldDecl::chain_iterator
1304 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCalldfa1edb2010-11-23 20:48:44 +00001305
John McCall5808ce42011-02-03 08:15:49 +00001306 // Build the first member access in the chain with full information.
1307 if (!baseVariable) {
1308 FieldDecl *field = cast<FieldDecl>(*FI);
John McCalldfa1edb2010-11-23 20:48:44 +00001309
John McCall5808ce42011-02-03 08:15:49 +00001310 // FIXME: use the real found-decl info!
1311 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall0953e762009-09-24 19:53:00 +00001312
John McCall5808ce42011-02-03 08:15:49 +00001313 // Make a nameInfo that properly uses the anonymous name.
1314 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall0953e762009-09-24 19:53:00 +00001315
John McCall5808ce42011-02-03 08:15:49 +00001316 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Douglas Gregorf5848322011-02-18 02:44:58 +00001317 EmptySS, field, foundDecl,
John McCall5808ce42011-02-03 08:15:49 +00001318 memberNameInfo).take();
1319 baseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +00001320
John McCall5808ce42011-02-03 08:15:49 +00001321 // FIXME: check qualified member access
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001322 }
1323
John McCall5808ce42011-02-03 08:15:49 +00001324 // In all cases, we should now skip the first declaration in the chain.
1325 ++FI;
1326
Douglas Gregorf5848322011-02-18 02:44:58 +00001327 while (FI != FEnd) {
1328 FieldDecl *field = cast<FieldDecl>(*FI++);
John McCall5808ce42011-02-03 08:15:49 +00001329
1330 // FIXME: these are somewhat meaningless
1331 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1332 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall5808ce42011-02-03 08:15:49 +00001333
1334 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Douglas Gregorf5848322011-02-18 02:44:58 +00001335 (FI == FEnd? SS : EmptySS), field,
1336 foundDecl, memberNameInfo)
John McCall5808ce42011-02-03 08:15:49 +00001337 .take();
1338 }
1339
1340 return Owned(result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001341}
1342
Abramo Bagnara25777432010-08-11 22:01:17 +00001343/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001344/// possibly a list of template arguments.
1345///
1346/// If this produces template arguments, it is permitted to call
1347/// DecomposeTemplateName.
1348///
1349/// This actually loses a lot of source location information for
1350/// non-standard name kinds; we should consider preserving that in
1351/// some way.
1352static void DecomposeUnqualifiedId(Sema &SemaRef,
1353 const UnqualifiedId &Id,
1354 TemplateArgumentListInfo &Buffer,
Abramo Bagnara25777432010-08-11 22:01:17 +00001355 DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00001356 const TemplateArgumentListInfo *&TemplateArgs) {
1357 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1358 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1359 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1360
1361 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1362 Id.TemplateId->getTemplateArgs(),
1363 Id.TemplateId->NumArgs);
1364 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1365 TemplateArgsPtr.release();
1366
John McCall2b5289b2010-08-23 07:28:44 +00001367 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001368 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1369 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001370 TemplateArgs = &Buffer;
1371 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001372 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001373 TemplateArgs = 0;
1374 }
1375}
1376
John McCallaa81e162009-12-01 22:10:20 +00001377/// Determines if the given class is provably not derived from all of
1378/// the prospective base classes.
1379static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1380 CXXRecordDecl *Record,
1381 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCallb1b42562009-12-01 22:28:41 +00001382 if (Bases.count(Record->getCanonicalDecl()))
John McCallaa81e162009-12-01 22:10:20 +00001383 return false;
1384
Douglas Gregor952b0172010-02-11 01:04:33 +00001385 RecordDecl *RD = Record->getDefinition();
John McCallb1b42562009-12-01 22:28:41 +00001386 if (!RD) return false;
1387 Record = cast<CXXRecordDecl>(RD);
1388
John McCallaa81e162009-12-01 22:10:20 +00001389 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1390 E = Record->bases_end(); I != E; ++I) {
1391 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1392 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1393 if (!BaseRT) return false;
1394
1395 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCallaa81e162009-12-01 22:10:20 +00001396 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1397 return false;
1398 }
1399
1400 return true;
1401}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001402
John McCallaa81e162009-12-01 22:10:20 +00001403enum IMAKind {
1404 /// The reference is definitely not an instance member access.
1405 IMA_Static,
1406
1407 /// The reference may be an implicit instance member access.
1408 IMA_Mixed,
1409
1410 /// The reference may be to an instance member, but it is invalid if
1411 /// so, because the context is not an instance method.
1412 IMA_Mixed_StaticContext,
1413
1414 /// The reference may be to an instance member, but it is invalid if
1415 /// so, because the context is from an unrelated class.
1416 IMA_Mixed_Unrelated,
1417
1418 /// The reference is definitely an implicit instance member access.
1419 IMA_Instance,
1420
1421 /// The reference may be to an unresolved using declaration.
1422 IMA_Unresolved,
1423
1424 /// The reference may be to an unresolved using declaration and the
1425 /// context is not an instance method.
1426 IMA_Unresolved_StaticContext,
1427
John McCallaa81e162009-12-01 22:10:20 +00001428 /// All possible referrents are instance members and the current
1429 /// context is not an instance method.
1430 IMA_Error_StaticContext,
1431
1432 /// All possible referrents are instance members of an unrelated
1433 /// class.
1434 IMA_Error_Unrelated
1435};
1436
1437/// The given lookup names class member(s) and is not being used for
1438/// an address-of-member expression. Classify the type of access
1439/// according to whether it's possible that this reference names an
1440/// instance member. This is best-effort; it is okay to
1441/// conservatively answer "yes", in which case some errors will simply
1442/// not be caught until template-instantiation.
1443static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1444 const LookupResult &R) {
John McCall3b4294e2009-12-16 12:17:52 +00001445 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCallaa81e162009-12-01 22:10:20 +00001446
John McCallea1471e2010-05-20 01:18:31 +00001447 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCallaa81e162009-12-01 22:10:20 +00001448 bool isStaticContext =
John McCallea1471e2010-05-20 01:18:31 +00001449 (!isa<CXXMethodDecl>(DC) ||
1450 cast<CXXMethodDecl>(DC)->isStatic());
John McCallaa81e162009-12-01 22:10:20 +00001451
1452 if (R.isUnresolvableResult())
1453 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1454
1455 // Collect all the declaring classes of instance members we find.
1456 bool hasNonInstance = false;
Sebastian Redlf9780002010-11-26 16:28:07 +00001457 bool hasField = false;
John McCallaa81e162009-12-01 22:10:20 +00001458 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1459 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall161755a2010-04-06 21:38:20 +00001460 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00001461
John McCall161755a2010-04-06 21:38:20 +00001462 if (D->isCXXInstanceMember()) {
Sebastian Redlf9780002010-11-26 16:28:07 +00001463 if (dyn_cast<FieldDecl>(D))
1464 hasField = true;
1465
John McCallaa81e162009-12-01 22:10:20 +00001466 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCallaa81e162009-12-01 22:10:20 +00001467 Classes.insert(R->getCanonicalDecl());
1468 }
1469 else
1470 hasNonInstance = true;
1471 }
1472
1473 // If we didn't find any instance members, it can't be an implicit
1474 // member reference.
1475 if (Classes.empty())
1476 return IMA_Static;
1477
1478 // If the current context is not an instance method, it can't be
1479 // an implicit member reference.
Sebastian Redlf9780002010-11-26 16:28:07 +00001480 if (isStaticContext) {
1481 if (hasNonInstance)
1482 return IMA_Mixed_StaticContext;
1483
1484 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1485 // C++0x [expr.prim.general]p10:
1486 // An id-expression that denotes a non-static data member or non-static
1487 // member function of a class can only be used:
1488 // (...)
1489 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1490 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1491 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1492 if (isUnevaluatedExpression)
1493 return IMA_Mixed_StaticContext;
1494 }
1495
1496 return IMA_Error_StaticContext;
1497 }
John McCallaa81e162009-12-01 22:10:20 +00001498
Argyrios Kyrtzidis0d8dc462011-04-14 00:46:47 +00001499 CXXRecordDecl *
1500 contextClass = cast<CXXMethodDecl>(DC)->getParent()->getCanonicalDecl();
1501
1502 // [class.mfct.non-static]p3:
1503 // ...is used in the body of a non-static member function of class X,
1504 // if name lookup (3.4.1) resolves the name in the id-expression to a
1505 // non-static non-type member of some class C [...]
1506 // ...if C is not X or a base class of X, the class member access expression
1507 // is ill-formed.
1508 if (R.getNamingClass() &&
1509 contextClass != R.getNamingClass()->getCanonicalDecl() &&
1510 contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
1511 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1512
John McCallaa81e162009-12-01 22:10:20 +00001513 // If we can prove that the current context is unrelated to all the
1514 // declaring classes, it can't be an implicit member reference (in
1515 // which case it's an error if any of those members are selected).
Argyrios Kyrtzidis0d8dc462011-04-14 00:46:47 +00001516 if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
John McCallaa81e162009-12-01 22:10:20 +00001517 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1518
1519 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1520}
1521
1522/// Diagnose a reference to a field with no object available.
1523static void DiagnoseInstanceReference(Sema &SemaRef,
1524 const CXXScopeSpec &SS,
John McCall5808ce42011-02-03 08:15:49 +00001525 NamedDecl *rep,
1526 const DeclarationNameInfo &nameInfo) {
1527 SourceLocation Loc = nameInfo.getLoc();
John McCallaa81e162009-12-01 22:10:20 +00001528 SourceRange Range(Loc);
1529 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1530
John McCall5808ce42011-02-03 08:15:49 +00001531 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCallaa81e162009-12-01 22:10:20 +00001532 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1533 if (MD->isStatic()) {
1534 // "invalid use of member 'x' in static member function"
1535 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCall5808ce42011-02-03 08:15:49 +00001536 << Range << nameInfo.getName();
John McCallaa81e162009-12-01 22:10:20 +00001537 return;
1538 }
1539 }
1540
1541 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCall5808ce42011-02-03 08:15:49 +00001542 << nameInfo.getName() << Range;
John McCallaa81e162009-12-01 22:10:20 +00001543 return;
1544 }
1545
1546 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +00001547}
1548
John McCall578b69b2009-12-16 08:11:27 +00001549/// Diagnose an empty lookup.
1550///
1551/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001552bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1553 CorrectTypoContext CTC) {
John McCall578b69b2009-12-16 08:11:27 +00001554 DeclarationName Name = R.getLookupName();
1555
John McCall578b69b2009-12-16 08:11:27 +00001556 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001557 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001558 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1559 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001560 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001561 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001562 diagnostic_suggest = diag::err_undeclared_use_suggest;
1563 }
John McCall578b69b2009-12-16 08:11:27 +00001564
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001565 // If the original lookup was an unqualified lookup, fake an
1566 // unqualified lookup. This is useful when (for example) the
1567 // original lookup would not have found something because it was a
1568 // dependent name.
Nick Lewycky03d98c52010-07-06 19:51:49 +00001569 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001570 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +00001571 if (isa<CXXRecordDecl>(DC)) {
1572 LookupQualifiedName(R, DC);
1573
1574 if (!R.empty()) {
1575 // Don't give errors about ambiguities in this lookup.
1576 R.suppressDiagnostics();
1577
1578 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1579 bool isInstance = CurMethod &&
1580 CurMethod->isInstance() &&
1581 DC == CurMethod->getParent();
1582
1583 // Give a code modification hint to insert 'this->'.
1584 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1585 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +00001586 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +00001587 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1588 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001589 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +00001590 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +00001591 if (DepMethod) {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001592 Diag(R.getNameLoc(), diagnostic) << Name
1593 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1594 QualType DepThisType = DepMethod->getThisType(Context);
1595 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1596 R.getNameLoc(), DepThisType, false);
1597 TemplateArgumentListInfo TList;
1598 if (ULE->hasExplicitTemplateArgs())
1599 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001600
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001601 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00001602 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001603 CXXDependentScopeMemberExpr *DepExpr =
1604 CXXDependentScopeMemberExpr::Create(
1605 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001606 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001607 R.getLookupNameInfo(), &TList);
1608 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +00001609 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001610 // FIXME: we should be able to handle this case too. It is correct
1611 // to add this-> here. This is a workaround for PR7947.
1612 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +00001613 }
Nick Lewycky03d98c52010-07-06 19:51:49 +00001614 } else {
John McCall578b69b2009-12-16 08:11:27 +00001615 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001616 }
John McCall578b69b2009-12-16 08:11:27 +00001617
1618 // Do we really want to note all of these?
1619 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1620 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1621
1622 // Tell the callee to try to recover.
1623 return false;
1624 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001625
1626 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001627 }
1628 }
1629
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001630 // We didn't find anything, so try to correct for a typo.
Douglas Gregoraaf87162010-04-14 20:04:41 +00001631 DeclarationName Corrected;
Daniel Dunbardc32cdf2010-06-02 15:46:52 +00001632 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001633 if (!R.empty()) {
1634 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1635 if (SS.isEmpty())
1636 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1637 << FixItHint::CreateReplacement(R.getNameLoc(),
1638 R.getLookupName().getAsString());
1639 else
1640 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1641 << Name << computeDeclContext(SS, false) << R.getLookupName()
1642 << SS.getRange()
1643 << FixItHint::CreateReplacement(R.getNameLoc(),
1644 R.getLookupName().getAsString());
1645 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1646 Diag(ND->getLocation(), diag::note_previous_decl)
1647 << ND->getDeclName();
1648
1649 // Tell the callee to try to recover.
1650 return false;
1651 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001652
Douglas Gregoraaf87162010-04-14 20:04:41 +00001653 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1654 // FIXME: If we ended up with a typo for a type name or
1655 // Objective-C class name, we're in trouble because the parser
1656 // is in the wrong place to recover. Suggest the typo
1657 // correction, but don't make it a fix-it since we're not going
1658 // to recover well anyway.
1659 if (SS.isEmpty())
1660 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1661 else
1662 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1663 << Name << computeDeclContext(SS, false) << R.getLookupName()
1664 << SS.getRange();
1665
1666 // Don't try to recover; it won't work.
1667 return true;
1668 }
1669 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001670 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001671 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001672 if (SS.isEmpty())
Douglas Gregoraaf87162010-04-14 20:04:41 +00001673 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001674 else
Douglas Gregord203a162010-01-01 00:15:04 +00001675 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001676 << Name << computeDeclContext(SS, false) << Corrected
1677 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001678 return true;
1679 }
Douglas Gregord203a162010-01-01 00:15:04 +00001680 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001681 }
1682
1683 // Emit a special diagnostic for failed member lookups.
1684 // FIXME: computing the declaration context might fail here (?)
1685 if (!SS.isEmpty()) {
1686 Diag(R.getNameLoc(), diag::err_no_member)
1687 << Name << computeDeclContext(SS, false)
1688 << SS.getRange();
1689 return true;
1690 }
1691
John McCall578b69b2009-12-16 08:11:27 +00001692 // Give up, we can't recover.
1693 Diag(R.getNameLoc(), diagnostic) << Name;
1694 return true;
1695}
1696
Douglas Gregorca45da02010-11-02 20:36:02 +00001697ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1698 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001699 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1700 if (!IDecl)
1701 return 0;
1702 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1703 if (!ClassImpDecl)
1704 return 0;
Douglas Gregorca45da02010-11-02 20:36:02 +00001705 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001706 if (!property)
1707 return 0;
1708 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregorca45da02010-11-02 20:36:02 +00001709 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1710 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001711 return 0;
1712 return property;
1713}
1714
Douglas Gregorca45da02010-11-02 20:36:02 +00001715bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1716 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1717 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1718 if (!IDecl)
1719 return false;
1720 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1721 if (!ClassImpDecl)
1722 return false;
1723 if (ObjCPropertyImplDecl *PIDecl
1724 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1725 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1726 PIDecl->getPropertyIvarDecl())
1727 return false;
1728
1729 return true;
1730}
1731
Douglas Gregor312eadb2011-04-24 05:37:28 +00001732ObjCIvarDecl *Sema::SynthesizeProvisionalIvar(LookupResult &Lookup,
1733 IdentifierInfo *II,
1734 SourceLocation NameLoc) {
1735 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001736 bool LookForIvars;
1737 if (Lookup.empty())
1738 LookForIvars = true;
1739 else if (CurMeth->isClassMethod())
1740 LookForIvars = false;
1741 else
1742 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahaniand0fbadd2011-01-26 00:57:01 +00001743 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1744 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001745 if (!LookForIvars)
1746 return 0;
1747
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001748 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1749 if (!IDecl)
1750 return 0;
1751 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001752 if (!ClassImpDecl)
1753 return 0;
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001754 bool DynamicImplSeen = false;
Douglas Gregor312eadb2011-04-24 05:37:28 +00001755 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001756 if (!property)
1757 return 0;
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001758 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001759 DynamicImplSeen =
1760 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001761 // property implementation has a designated ivar. No need to assume a new
1762 // one.
1763 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1764 return 0;
1765 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001766 if (!DynamicImplSeen) {
Douglas Gregor312eadb2011-04-24 05:37:28 +00001767 QualType PropType = Context.getCanonicalType(property->getType());
1768 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001769 NameLoc, NameLoc,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001770 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian75049662010-12-15 23:29:04 +00001771 ObjCIvarDecl::Private,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001772 (Expr *)0, true);
1773 ClassImpDecl->addDecl(Ivar);
1774 IDecl->makeDeclVisibleInContext(Ivar, false);
1775 property->setPropertyIvarDecl(Ivar);
1776 return Ivar;
1777 }
1778 return 0;
1779}
1780
John McCall60d7b3a2010-08-24 06:29:42 +00001781ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001782 CXXScopeSpec &SS,
1783 UnqualifiedId &Id,
1784 bool HasTrailingLParen,
1785 bool isAddressOfOperand) {
John McCallf7a1a742009-11-24 19:00:30 +00001786 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1787 "cannot be direct & operand and have a trailing lparen");
1788
1789 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001790 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001791
John McCall129e2df2009-11-30 22:42:35 +00001792 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001793
1794 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001795 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001796 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnara25777432010-08-11 22:01:17 +00001797 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001798
Abramo Bagnara25777432010-08-11 22:01:17 +00001799 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001800 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001801 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001802
John McCallf7a1a742009-11-24 19:00:30 +00001803 // C++ [temp.dep.expr]p3:
1804 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001805 // -- an identifier that was declared with a dependent type,
1806 // (note: handled after lookup)
1807 // -- a template-id that is dependent,
1808 // (note: handled in BuildTemplateIdExpr)
1809 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001810 // -- a nested-name-specifier that contains a class-name that
1811 // names a dependent type.
1812 // Determine whether this is a member of an unknown specialization;
1813 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001814 bool DependentID = false;
1815 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1816 Name.getCXXNameType()->isDependentType()) {
1817 DependentID = true;
1818 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001819 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001820 if (RequireCompleteDeclContext(SS, DC))
1821 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001822 } else {
1823 DependentID = true;
1824 }
1825 }
1826
Chris Lattner337e5502011-02-18 01:27:55 +00001827 if (DependentID)
Abramo Bagnara25777432010-08-11 22:01:17 +00001828 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001829 TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001830
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001831 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001832 // Perform the required lookup.
Abramo Bagnara25777432010-08-11 22:01:17 +00001833 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001834 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001835 // Lookup the template name again to correctly establish the context in
1836 // which it was found. This is really unfortunate as we already did the
1837 // lookup to determine that it was a template name in the first place. If
1838 // this becomes a performance hit, we can work harder to preserve those
1839 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001840 bool MemberOfUnknownSpecialization;
1841 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1842 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001843
1844 if (MemberOfUnknownSpecialization ||
1845 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1846 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1847 TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001848 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001849 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001850 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001851
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001852 // If the result might be in a dependent base class, this is a dependent
1853 // id-expression.
1854 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1855 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1856 TemplateArgs);
1857
John McCallf7a1a742009-11-24 19:00:30 +00001858 // If this reference is in an Objective-C method, then we need to do
1859 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001860 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001861 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001862 if (E.isInvalid())
1863 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001864
Chris Lattner337e5502011-02-18 01:27:55 +00001865 if (Expr *Ex = E.takeAs<Expr>())
1866 return Owned(Ex);
1867
1868 // Synthesize ivars lazily.
Fariborz Jahaniane776f882011-01-03 18:08:02 +00001869 if (getLangOptions().ObjCDefaultSynthProperties &&
1870 getLangOptions().ObjCNonFragileABI2) {
Douglas Gregor312eadb2011-04-24 05:37:28 +00001871 if (SynthesizeProvisionalIvar(R, II, NameLoc)) {
Fariborz Jahaniande267602010-11-17 19:41:23 +00001872 if (const ObjCPropertyDecl *Property =
1873 canSynthesizeProvisionalIvar(II)) {
1874 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1875 Diag(Property->getLocation(), diag::note_property_declare);
1876 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001877 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1878 isAddressOfOperand);
Fariborz Jahaniande267602010-11-17 19:41:23 +00001879 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001880 }
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001881 // for further use, this must be set to false if in class method.
1882 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001883 }
Chris Lattner8a934232008-03-31 00:36:02 +00001884 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001885
John McCallf7a1a742009-11-24 19:00:30 +00001886 if (R.isAmbiguous())
1887 return ExprError();
1888
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001889 // Determine whether this name might be a candidate for
1890 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001891 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001892
John McCallf7a1a742009-11-24 19:00:30 +00001893 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001894 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001895 // in C90, extension in C99, forbidden in C++).
1896 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1897 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1898 if (D) R.addDecl(D);
1899 }
1900
1901 // If this name wasn't predeclared and if this is not a function
1902 // call, diagnose the problem.
1903 if (R.empty()) {
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001904 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001905 return ExprError();
1906
1907 assert(!R.empty() &&
1908 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001909
1910 // If we found an Objective-C instance variable, let
1911 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001912 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001913 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1914 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001915 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001916 assert(E.isInvalid() || E.get());
1917 return move(E);
1918 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001919 }
1920 }
Mike Stump1eb44332009-09-09 15:08:12 +00001921
John McCallf7a1a742009-11-24 19:00:30 +00001922 // This is guaranteed from this point on.
1923 assert(!R.empty() || ADL);
1924
John McCallaa81e162009-12-01 22:10:20 +00001925 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001926 // C++ [class.mfct.non-static]p3:
1927 // When an id-expression that is not part of a class member access
1928 // syntax and not used to form a pointer to member is used in the
1929 // body of a non-static member function of class X, if name lookup
1930 // resolves the name in the id-expression to a non-static non-type
1931 // member of some class C, the id-expression is transformed into a
1932 // class member access expression using (*this) as the
1933 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001934 //
1935 // But we don't actually need to do this for '&' operands if R
1936 // resolved to a function or overloaded function set, because the
1937 // expression is ill-formed if it actually works out to be a
1938 // non-static member function:
1939 //
1940 // C++ [expr.ref]p4:
1941 // Otherwise, if E1.E2 refers to a non-static member function. . .
1942 // [t]he expression can be used only as the left-hand operand of a
1943 // member function call.
1944 //
1945 // There are other safeguards against such uses, but it's important
1946 // to get this right here so that we don't end up making a
1947 // spuriously dependent expression if we're inside a dependent
1948 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001949 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001950 bool MightBeImplicitMember;
1951 if (!isAddressOfOperand)
1952 MightBeImplicitMember = true;
1953 else if (!SS.isEmpty())
1954 MightBeImplicitMember = false;
1955 else if (R.isOverloadedResult())
1956 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001957 else if (R.isUnresolvableResult())
1958 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001959 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001960 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1961 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001962
1963 if (MightBeImplicitMember)
John McCall3b4294e2009-12-16 12:17:52 +00001964 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001965 }
1966
John McCallf7a1a742009-11-24 19:00:30 +00001967 if (TemplateArgs)
1968 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001969
John McCallf7a1a742009-11-24 19:00:30 +00001970 return BuildDeclarationNameExpr(SS, R, ADL);
1971}
1972
John McCall3b4294e2009-12-16 12:17:52 +00001973/// Builds an expression which might be an implicit member expression.
John McCall60d7b3a2010-08-24 06:29:42 +00001974ExprResult
John McCall3b4294e2009-12-16 12:17:52 +00001975Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1976 LookupResult &R,
1977 const TemplateArgumentListInfo *TemplateArgs) {
1978 switch (ClassifyImplicitMemberAccess(*this, R)) {
1979 case IMA_Instance:
1980 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1981
John McCall3b4294e2009-12-16 12:17:52 +00001982 case IMA_Mixed:
1983 case IMA_Mixed_Unrelated:
1984 case IMA_Unresolved:
1985 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1986
1987 case IMA_Static:
1988 case IMA_Mixed_StaticContext:
1989 case IMA_Unresolved_StaticContext:
1990 if (TemplateArgs)
1991 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1992 return BuildDeclarationNameExpr(SS, R, false);
1993
1994 case IMA_Error_StaticContext:
1995 case IMA_Error_Unrelated:
John McCall5808ce42011-02-03 08:15:49 +00001996 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
1997 R.getLookupNameInfo());
John McCall3b4294e2009-12-16 12:17:52 +00001998 return ExprError();
1999 }
2000
2001 llvm_unreachable("unexpected instance member access kind");
2002 return ExprError();
2003}
2004
John McCall129e2df2009-11-30 22:42:35 +00002005/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2006/// declaration name, generally during template instantiation.
2007/// There's a large number of things which don't need to be done along
2008/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00002009ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002010Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002011 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00002012 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00002013 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00002014 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00002015
John McCall77bb1aa2010-05-01 00:40:08 +00002016 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00002017 return ExprError();
2018
Abramo Bagnara25777432010-08-11 22:01:17 +00002019 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00002020 LookupQualifiedName(R, DC);
2021
2022 if (R.isAmbiguous())
2023 return ExprError();
2024
2025 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002026 Diag(NameInfo.getLoc(), diag::err_no_member)
2027 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00002028 return ExprError();
2029 }
2030
2031 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
2032}
2033
2034/// LookupInObjCMethod - The parser has read a name in, and Sema has
2035/// detected that we're currently inside an ObjC method. Perform some
2036/// additional lookup.
2037///
2038/// Ideally, most of this would be done by lookup, but there's
2039/// actually quite a lot of extra work involved.
2040///
2041/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00002042ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002043Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00002044 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00002045 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00002046 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002047
John McCallf7a1a742009-11-24 19:00:30 +00002048 // There are two cases to handle here. 1) scoped lookup could have failed,
2049 // in which case we should look for an ivar. 2) scoped lookup could have
2050 // found a decl, but that decl is outside the current instance method (i.e.
2051 // a global variable). In these two cases, we do a lookup for an ivar with
2052 // this name, if the lookup sucedes, we replace it our current decl.
2053
2054 // If we're in a class method, we don't normally want to look for
2055 // ivars. But if we don't find anything else, and there's an
2056 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00002057 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00002058
2059 bool LookForIvars;
2060 if (Lookup.empty())
2061 LookForIvars = true;
2062 else if (IsClassMethod)
2063 LookForIvars = false;
2064 else
2065 LookForIvars = (Lookup.isSingleResult() &&
2066 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00002067 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00002068 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00002069 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00002070 ObjCInterfaceDecl *ClassDeclared;
2071 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2072 // Diagnose using an ivar in a class method.
2073 if (IsClassMethod)
2074 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2075 << IV->getDeclName());
2076
2077 // If we're referencing an invalid decl, just return this as a silent
2078 // error node. The error diagnostic was already emitted on the decl.
2079 if (IV->isInvalidDecl())
2080 return ExprError();
2081
2082 // Check if referencing a field with __attribute__((deprecated)).
2083 if (DiagnoseUseOfDecl(IV, Loc))
2084 return ExprError();
2085
2086 // Diagnose the use of an ivar outside of the declaring class.
2087 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2088 ClassDeclared != IFace)
2089 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2090
2091 // FIXME: This should use a new expr for a direct reference, don't
2092 // turn this into Self->ivar, just return a BareIVarExpr or something.
2093 IdentifierInfo &II = Context.Idents.get("self");
2094 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002095 SelfName.setIdentifier(&II, SourceLocation());
John McCallf7a1a742009-11-24 19:00:30 +00002096 CXXScopeSpec SelfScopeSpec;
John McCall60d7b3a2010-08-24 06:29:42 +00002097 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00002098 SelfName, false, false);
2099 if (SelfExpr.isInvalid())
2100 return ExprError();
2101
John Wiegley429bb272011-04-08 18:41:53 +00002102 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2103 if (SelfExpr.isInvalid())
2104 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00002105
John McCallf7a1a742009-11-24 19:00:30 +00002106 MarkDeclarationReferenced(Loc, IV);
Fariborz Jahanianb8f17ab2011-04-12 23:39:33 +00002107 Expr *base = SelfExpr.take();
2108 base = base->IgnoreParenImpCasts();
2109 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(base)) {
2110 const NamedDecl *ND = DE->getDecl();
2111 if (!isa<ImplicitParamDecl>(ND)) {
Fariborz Jahanianeefa76e2011-04-15 17:04:42 +00002112 // relax the rule such that it is allowed to have a shadow 'self'
2113 // where stand-alone ivar can be found in this 'self' object.
2114 // This is to match gcc's behavior.
2115 ObjCInterfaceDecl *selfIFace = 0;
2116 if (const ObjCObjectPointerType *OPT =
2117 base->getType()->getAsObjCInterfacePointerType())
2118 selfIFace = OPT->getInterfaceDecl();
2119 if (!selfIFace ||
2120 !selfIFace->lookupInstanceVariable(IV->getIdentifier())) {
Fariborz Jahanianb8f17ab2011-04-12 23:39:33 +00002121 Diag(Loc, diag::error_implicit_ivar_access)
2122 << IV->getDeclName();
2123 Diag(ND->getLocation(), diag::note_declared_at);
2124 return ExprError();
2125 }
Fariborz Jahanianeefa76e2011-04-15 17:04:42 +00002126 }
Fariborz Jahanianb8f17ab2011-04-12 23:39:33 +00002127 }
John McCallf7a1a742009-11-24 19:00:30 +00002128 return Owned(new (Context)
2129 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley429bb272011-04-08 18:41:53 +00002130 SelfExpr.take(), true, true));
John McCallf7a1a742009-11-24 19:00:30 +00002131 }
Chris Lattneraec43db2010-04-12 05:10:17 +00002132 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00002133 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00002134 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00002135 ObjCInterfaceDecl *ClassDeclared;
2136 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2137 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2138 IFace == ClassDeclared)
2139 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2140 }
2141 }
2142
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002143 if (Lookup.empty() && II && AllowBuiltinCreation) {
2144 // FIXME. Consolidate this with similar code in LookupName.
2145 if (unsigned BuiltinID = II->getBuiltinID()) {
2146 if (!(getLangOptions().CPlusPlus &&
2147 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2148 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2149 S, Lookup.isForRedeclaration(),
2150 Lookup.getNameLoc());
2151 if (D) Lookup.addDecl(D);
2152 }
2153 }
2154 }
John McCallf7a1a742009-11-24 19:00:30 +00002155 // Sentinel value saying that we didn't do anything special.
2156 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00002157}
John McCallba135432009-11-21 08:51:07 +00002158
John McCall6bb80172010-03-30 21:47:33 +00002159/// \brief Cast a base object to a member's actual type.
2160///
2161/// Logically this happens in three phases:
2162///
2163/// * First we cast from the base type to the naming class.
2164/// The naming class is the class into which we were looking
2165/// when we found the member; it's the qualifier type if a
2166/// qualifier was provided, and otherwise it's the base type.
2167///
2168/// * Next we cast from the naming class to the declaring class.
2169/// If the member we found was brought into a class's scope by
2170/// a using declaration, this is that class; otherwise it's
2171/// the class declaring the member.
2172///
2173/// * Finally we cast from the declaring class to the "true"
2174/// declaring class of the member. This conversion does not
2175/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00002176ExprResult
2177Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002178 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002179 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002180 NamedDecl *Member) {
2181 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2182 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00002183 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002184
Douglas Gregor5fccd362010-03-03 23:55:11 +00002185 QualType DestRecordType;
2186 QualType DestType;
2187 QualType FromRecordType;
2188 QualType FromType = From->getType();
2189 bool PointerConversions = false;
2190 if (isa<FieldDecl>(Member)) {
2191 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002192
Douglas Gregor5fccd362010-03-03 23:55:11 +00002193 if (FromType->getAs<PointerType>()) {
2194 DestType = Context.getPointerType(DestRecordType);
2195 FromRecordType = FromType->getPointeeType();
2196 PointerConversions = true;
2197 } else {
2198 DestType = DestRecordType;
2199 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002200 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002201 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2202 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00002203 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002204
Douglas Gregor5fccd362010-03-03 23:55:11 +00002205 DestType = Method->getThisType(Context);
2206 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002207
Douglas Gregor5fccd362010-03-03 23:55:11 +00002208 if (FromType->getAs<PointerType>()) {
2209 FromRecordType = FromType->getPointeeType();
2210 PointerConversions = true;
2211 } else {
2212 FromRecordType = FromType;
2213 DestType = DestRecordType;
2214 }
2215 } else {
2216 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00002217 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002218 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002219
Douglas Gregor5fccd362010-03-03 23:55:11 +00002220 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002221 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002222
Douglas Gregor5fccd362010-03-03 23:55:11 +00002223 // If the unqualified types are the same, no conversion is necessary.
2224 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002225 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002226
John McCall6bb80172010-03-30 21:47:33 +00002227 SourceRange FromRange = From->getSourceRange();
2228 SourceLocation FromLoc = FromRange.getBegin();
2229
John McCall5baba9d2010-08-25 10:28:54 +00002230 ExprValueKind VK = CastCategory(From);
Sebastian Redl906082e2010-07-20 04:20:21 +00002231
Douglas Gregor5fccd362010-03-03 23:55:11 +00002232 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002233 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002234 // class name.
2235 //
2236 // If the member was a qualified name and the qualified referred to a
2237 // specific base subobject type, we'll cast to that intermediate type
2238 // first and then to the object in which the member is declared. That allows
2239 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2240 //
2241 // class Base { public: int x; };
2242 // class Derived1 : public Base { };
2243 // class Derived2 : public Base { };
2244 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2245 //
2246 // void VeryDerived::f() {
2247 // x = 17; // error: ambiguous base subobjects
2248 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2249 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002250 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002251 QualType QType = QualType(Qualifier->getAsType(), 0);
2252 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2253 assert(QType->isRecordType() && "lookup done with non-record type");
2254
2255 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2256
2257 // In C++98, the qualifier type doesn't actually have to be a base
2258 // type of the object type, in which case we just ignore it.
2259 // Otherwise build the appropriate casts.
2260 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002261 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002262 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002263 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002264 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002265
Douglas Gregor5fccd362010-03-03 23:55:11 +00002266 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002267 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002268 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2269 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002270
2271 FromType = QType;
2272 FromRecordType = QRecordType;
2273
2274 // If the qualifier type was the same as the destination type,
2275 // we're done.
2276 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002277 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002278 }
2279 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002280
John McCall6bb80172010-03-30 21:47:33 +00002281 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002282
John McCall6bb80172010-03-30 21:47:33 +00002283 // If we actually found the member through a using declaration, cast
2284 // down to the using declaration's type.
2285 //
2286 // Pointer equality is fine here because only one declaration of a
2287 // class ever has member declarations.
2288 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2289 assert(isa<UsingShadowDecl>(FoundDecl));
2290 QualType URecordType = Context.getTypeDeclType(
2291 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2292
2293 // We only need to do this if the naming-class to declaring-class
2294 // conversion is non-trivial.
2295 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2296 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002297 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002298 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002299 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002300 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002301
John McCall6bb80172010-03-30 21:47:33 +00002302 QualType UType = URecordType;
2303 if (PointerConversions)
2304 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002305 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2306 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002307 FromType = UType;
2308 FromRecordType = URecordType;
2309 }
2310
2311 // We don't do access control for the conversion from the
2312 // declaring class to the true declaring class.
2313 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002314 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002315
John McCallf871d0c2010-08-07 06:22:56 +00002316 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002317 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2318 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002319 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002320 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002321
John Wiegley429bb272011-04-08 18:41:53 +00002322 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2323 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002324}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002325
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002326/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00002327static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00002328 const CXXScopeSpec &SS, ValueDecl *Member,
John McCall161755a2010-04-06 21:38:20 +00002329 DeclAccessPair FoundDecl,
Abramo Bagnara25777432010-08-11 22:01:17 +00002330 const DeclarationNameInfo &MemberNameInfo,
2331 QualType Ty,
John McCallf89e55a2010-11-18 06:31:45 +00002332 ExprValueKind VK, ExprObjectKind OK,
John McCallf7a1a742009-11-24 19:00:30 +00002333 const TemplateArgumentListInfo *TemplateArgs = 0) {
Douglas Gregor40d96a62011-02-28 21:54:11 +00002334 return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
Abramo Bagnara25777432010-08-11 22:01:17 +00002335 Member, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002336 TemplateArgs, Ty, VK, OK);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002337}
2338
John McCalldfa1edb2010-11-23 20:48:44 +00002339static ExprResult
2340BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2341 const CXXScopeSpec &SS, FieldDecl *Field,
2342 DeclAccessPair FoundDecl,
2343 const DeclarationNameInfo &MemberNameInfo) {
2344 // x.a is an l-value if 'a' has a reference type. Otherwise:
2345 // x.a is an l-value/x-value/pr-value if the base is (and note
2346 // that *x is always an l-value), except that if the base isn't
2347 // an ordinary object then we must have an rvalue.
2348 ExprValueKind VK = VK_LValue;
2349 ExprObjectKind OK = OK_Ordinary;
2350 if (!IsArrow) {
2351 if (BaseExpr->getObjectKind() == OK_Ordinary)
2352 VK = BaseExpr->getValueKind();
2353 else
2354 VK = VK_RValue;
2355 }
2356 if (VK != VK_RValue && Field->isBitField())
2357 OK = OK_BitField;
2358
2359 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2360 QualType MemberType = Field->getType();
2361 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2362 MemberType = Ref->getPointeeType();
2363 VK = VK_LValue;
2364 } else {
2365 QualType BaseType = BaseExpr->getType();
2366 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2367
2368 Qualifiers BaseQuals = BaseType.getQualifiers();
2369
2370 // GC attributes are never picked up by members.
2371 BaseQuals.removeObjCGCAttr();
2372
2373 // CVR attributes from the base are picked up by members,
2374 // except that 'mutable' members don't pick up 'const'.
2375 if (Field->isMutable()) BaseQuals.removeConst();
2376
2377 Qualifiers MemberQuals
2378 = S.Context.getCanonicalType(MemberType).getQualifiers();
2379
2380 // TR 18037 does not allow fields to be declared with address spaces.
2381 assert(!MemberQuals.hasAddressSpace());
2382
2383 Qualifiers Combined = BaseQuals + MemberQuals;
2384 if (Combined != MemberQuals)
2385 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2386 }
2387
2388 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
John Wiegley429bb272011-04-08 18:41:53 +00002389 ExprResult Base =
2390 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2391 FoundDecl, Field);
2392 if (Base.isInvalid())
John McCalldfa1edb2010-11-23 20:48:44 +00002393 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00002394 return S.Owned(BuildMemberExpr(S.Context, Base.take(), IsArrow, SS,
John McCalldfa1edb2010-11-23 20:48:44 +00002395 Field, FoundDecl, MemberNameInfo,
2396 MemberType, VK, OK));
2397}
2398
John McCallaa81e162009-12-01 22:10:20 +00002399/// Builds an implicit member access expression. The current context
2400/// is known to be an instance method, and the given unqualified lookup
2401/// set is known to contain only instance members, at least one of which
2402/// is from an appropriate type.
John McCall60d7b3a2010-08-24 06:29:42 +00002403ExprResult
John McCallaa81e162009-12-01 22:10:20 +00002404Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2405 LookupResult &R,
2406 const TemplateArgumentListInfo *TemplateArgs,
2407 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00002408 assert(!R.empty() && !R.isAmbiguous());
2409
John McCall5808ce42011-02-03 08:15:49 +00002410 SourceLocation loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00002411
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002412 // We may have found a field within an anonymous union or struct
2413 // (C++ [class.union]).
John McCallf7a1a742009-11-24 19:00:30 +00002414 // FIXME: template-ids inside anonymous structs?
Francois Pichet87c2e122010-11-21 06:08:52 +00002415 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCall5808ce42011-02-03 08:15:49 +00002416 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet87c2e122010-11-21 06:08:52 +00002417
John McCall5808ce42011-02-03 08:15:49 +00002418 // If this is known to be an instance access, go ahead and build an
2419 // implicit 'this' expression now.
John McCallaa81e162009-12-01 22:10:20 +00002420 // 'this' expression now.
John McCall5808ce42011-02-03 08:15:49 +00002421 CXXMethodDecl *method = tryCaptureCXXThis();
2422 assert(method && "didn't correctly pre-flight capture of 'this'");
2423
2424 QualType thisType = method->getThisType(Context);
2425 Expr *baseExpr = 0; // null signifies implicit access
John McCallaa81e162009-12-01 22:10:20 +00002426 if (IsKnownInstance) {
Douglas Gregor828a1972010-01-07 23:12:05 +00002427 SourceLocation Loc = R.getNameLoc();
2428 if (SS.getRange().isValid())
2429 Loc = SS.getRange().getBegin();
John McCall5808ce42011-02-03 08:15:49 +00002430 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
Douglas Gregor88a35142008-12-22 05:46:06 +00002431 }
2432
John McCall5808ce42011-02-03 08:15:49 +00002433 return BuildMemberReferenceExpr(baseExpr, thisType,
John McCallaa81e162009-12-01 22:10:20 +00002434 /*OpLoc*/ SourceLocation(),
2435 /*IsArrow*/ true,
John McCallc2233c52010-01-15 08:34:02 +00002436 SS,
2437 /*FirstQualifierInScope*/ 0,
2438 R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00002439}
2440
John McCallf7a1a742009-11-24 19:00:30 +00002441bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002442 const LookupResult &R,
2443 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002444 // Only when used directly as the postfix-expression of a call.
2445 if (!HasTrailingLParen)
2446 return false;
2447
2448 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002449 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002450 return false;
2451
2452 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00002453 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002454 return false;
2455
2456 // Turn off ADL when we find certain kinds of declarations during
2457 // normal lookup:
2458 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2459 NamedDecl *D = *I;
2460
2461 // C++0x [basic.lookup.argdep]p3:
2462 // -- a declaration of a class member
2463 // Since using decls preserve this property, we check this on the
2464 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002465 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002466 return false;
2467
2468 // C++0x [basic.lookup.argdep]p3:
2469 // -- a block-scope function declaration that is not a
2470 // using-declaration
2471 // NOTE: we also trigger this for function templates (in fact, we
2472 // don't check the decl type at all, since all other decl types
2473 // turn off ADL anyway).
2474 if (isa<UsingShadowDecl>(D))
2475 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2476 else if (D->getDeclContext()->isFunctionOrMethod())
2477 return false;
2478
2479 // C++0x [basic.lookup.argdep]p3:
2480 // -- a declaration that is neither a function or a function
2481 // template
2482 // And also for builtin functions.
2483 if (isa<FunctionDecl>(D)) {
2484 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2485
2486 // But also builtin functions.
2487 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2488 return false;
2489 } else if (!isa<FunctionTemplateDecl>(D))
2490 return false;
2491 }
2492
2493 return true;
2494}
2495
2496
John McCallba135432009-11-21 08:51:07 +00002497/// Diagnoses obvious problems with the use of the given declaration
2498/// as an expression. This is only actually called for lookups that
2499/// were not overloaded, and it doesn't promise that the declaration
2500/// will in fact be used.
2501static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002502 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002503 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2504 return true;
2505 }
2506
2507 if (isa<ObjCInterfaceDecl>(D)) {
2508 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2509 return true;
2510 }
2511
2512 if (isa<NamespaceDecl>(D)) {
2513 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2514 return true;
2515 }
2516
2517 return false;
2518}
2519
John McCall60d7b3a2010-08-24 06:29:42 +00002520ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002521Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002522 LookupResult &R,
2523 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002524 // If this is a single, fully-resolved result and we don't need ADL,
2525 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002526 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002527 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2528 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002529
2530 // We only need to check the declaration if there's exactly one
2531 // result, because in the overloaded case the results can only be
2532 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002533 if (R.isSingleResult() &&
2534 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002535 return ExprError();
2536
John McCallc373d482010-01-27 01:50:18 +00002537 // Otherwise, just build an unresolved lookup expression. Suppress
2538 // any lookup-related diagnostics; we'll hash these out later, when
2539 // we've picked a target.
2540 R.suppressDiagnostics();
2541
John McCallba135432009-11-21 08:51:07 +00002542 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002543 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002544 SS.getWithLocInContext(Context),
2545 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002546 NeedsADL, R.isOverloadedResult(),
2547 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002548
2549 return Owned(ULE);
2550}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002551
John McCallba135432009-11-21 08:51:07 +00002552/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002553ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002554Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002555 const DeclarationNameInfo &NameInfo,
2556 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002557 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002558 assert(!isa<FunctionTemplateDecl>(D) &&
2559 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002560
Abramo Bagnara25777432010-08-11 22:01:17 +00002561 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002562 if (CheckDeclInExpr(*this, Loc, D))
2563 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002564
Douglas Gregor9af2f522009-12-01 16:58:18 +00002565 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2566 // Specifically diagnose references to class templates that are missing
2567 // a template argument list.
2568 Diag(Loc, diag::err_template_decl_ref)
2569 << Template << SS.getRange();
2570 Diag(Template->getLocation(), diag::note_template_decl_here);
2571 return ExprError();
2572 }
2573
2574 // Make sure that we're referring to a value.
2575 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2576 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002577 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002578 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002579 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002580 return ExprError();
2581 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002582
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002583 // Check whether this declaration can be used. Note that we suppress
2584 // this check when we're going to perform argument-dependent lookup
2585 // on this function name, because this might not be the function
2586 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002587 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002588 return ExprError();
2589
Steve Naroffdd972f22008-09-05 22:11:13 +00002590 // Only create DeclRefExpr's for valid Decl's.
2591 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002592 return ExprError();
2593
John McCall5808ce42011-02-03 08:15:49 +00002594 // Handle members of anonymous structs and unions. If we got here,
2595 // and the reference is to a class member indirect field, then this
2596 // must be the subject of a pointer-to-member expression.
2597 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2598 if (!indirectField->isCXXClassMember())
2599 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2600 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002601
Chris Lattner639e2d32008-10-20 05:16:36 +00002602 // If the identifier reference is inside a block, and it refers to a value
2603 // that is outside the block, create a BlockDeclRefExpr instead of a
2604 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2605 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00002606 //
Chris Lattner639e2d32008-10-20 05:16:36 +00002607 // We do not do this for things like enum constants, global variables, etc,
2608 // as they do not get snapshotted.
2609 //
John McCall6b5a61b2011-02-07 10:33:21 +00002610 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCall469a1eb2011-02-02 13:00:07 +00002611 case CR_Error:
2612 return ExprError();
Mike Stump0d6fd572010-01-05 02:56:35 +00002613
John McCall469a1eb2011-02-02 13:00:07 +00002614 case CR_Capture:
John McCall6b5a61b2011-02-07 10:33:21 +00002615 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2616 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2617
2618 case CR_CaptureByRef:
2619 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2620 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCall76a40212011-02-09 01:13:10 +00002621
2622 case CR_NoCapture: {
2623 // If this reference is not in a block or if the referenced
2624 // variable is within the block, create a normal DeclRefExpr.
2625
2626 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002627 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002628
2629 switch (D->getKind()) {
2630 // Ignore all the non-ValueDecl kinds.
2631#define ABSTRACT_DECL(kind)
2632#define VALUE(type, base)
2633#define DECL(type, base) \
2634 case Decl::type:
2635#include "clang/AST/DeclNodes.inc"
2636 llvm_unreachable("invalid value decl kind");
2637 return ExprError();
2638
2639 // These shouldn't make it here.
2640 case Decl::ObjCAtDefsField:
2641 case Decl::ObjCIvar:
2642 llvm_unreachable("forming non-member reference to ivar?");
2643 return ExprError();
2644
2645 // Enum constants are always r-values and never references.
2646 // Unresolved using declarations are dependent.
2647 case Decl::EnumConstant:
2648 case Decl::UnresolvedUsingValue:
2649 valueKind = VK_RValue;
2650 break;
2651
2652 // Fields and indirect fields that got here must be for
2653 // pointer-to-member expressions; we just call them l-values for
2654 // internal consistency, because this subexpression doesn't really
2655 // exist in the high-level semantics.
2656 case Decl::Field:
2657 case Decl::IndirectField:
2658 assert(getLangOptions().CPlusPlus &&
2659 "building reference to field in C?");
2660
2661 // These can't have reference type in well-formed programs, but
2662 // for internal consistency we do this anyway.
2663 type = type.getNonReferenceType();
2664 valueKind = VK_LValue;
2665 break;
2666
2667 // Non-type template parameters are either l-values or r-values
2668 // depending on the type.
2669 case Decl::NonTypeTemplateParm: {
2670 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2671 type = reftype->getPointeeType();
2672 valueKind = VK_LValue; // even if the parameter is an r-value reference
2673 break;
2674 }
2675
2676 // For non-references, we need to strip qualifiers just in case
2677 // the template parameter was declared as 'const int' or whatever.
2678 valueKind = VK_RValue;
2679 type = type.getUnqualifiedType();
2680 break;
2681 }
2682
2683 case Decl::Var:
2684 // In C, "extern void blah;" is valid and is an r-value.
2685 if (!getLangOptions().CPlusPlus &&
2686 !type.hasQualifiers() &&
2687 type->isVoidType()) {
2688 valueKind = VK_RValue;
2689 break;
2690 }
2691 // fallthrough
2692
2693 case Decl::ImplicitParam:
2694 case Decl::ParmVar:
2695 // These are always l-values.
2696 valueKind = VK_LValue;
2697 type = type.getNonReferenceType();
2698 break;
2699
2700 case Decl::Function: {
John McCall755d8492011-04-12 00:42:48 +00002701 const FunctionType *fty = type->castAs<FunctionType>();
2702
2703 // If we're referring to a function with an __unknown_anytype
2704 // result type, make the entire expression __unknown_anytype.
2705 if (fty->getResultType() == Context.UnknownAnyTy) {
2706 type = Context.UnknownAnyTy;
2707 valueKind = VK_RValue;
2708 break;
2709 }
2710
John McCall76a40212011-02-09 01:13:10 +00002711 // Functions are l-values in C++.
2712 if (getLangOptions().CPlusPlus) {
2713 valueKind = VK_LValue;
2714 break;
2715 }
2716
2717 // C99 DR 316 says that, if a function type comes from a
2718 // function definition (without a prototype), that type is only
2719 // used for checking compatibility. Therefore, when referencing
2720 // the function, we pretend that we don't have the full function
2721 // type.
John McCall755d8492011-04-12 00:42:48 +00002722 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2723 isa<FunctionProtoType>(fty))
2724 type = Context.getFunctionNoProtoType(fty->getResultType(),
2725 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002726
2727 // Functions are r-values in C.
2728 valueKind = VK_RValue;
2729 break;
2730 }
2731
2732 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002733 // If we're referring to a method with an __unknown_anytype
2734 // result type, make the entire expression __unknown_anytype.
2735 // This should only be possible with a type written directly.
2736 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(VD->getType()))
2737 if (proto->getResultType() == Context.UnknownAnyTy) {
2738 type = Context.UnknownAnyTy;
2739 valueKind = VK_RValue;
2740 break;
2741 }
2742
John McCall76a40212011-02-09 01:13:10 +00002743 // C++ methods are l-values if static, r-values if non-static.
2744 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2745 valueKind = VK_LValue;
2746 break;
2747 }
2748 // fallthrough
2749
2750 case Decl::CXXConversion:
2751 case Decl::CXXDestructor:
2752 case Decl::CXXConstructor:
2753 valueKind = VK_RValue;
2754 break;
2755 }
2756
2757 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2758 }
2759
John McCall469a1eb2011-02-02 13:00:07 +00002760 }
John McCallf89e55a2010-11-18 06:31:45 +00002761
John McCall6b5a61b2011-02-07 10:33:21 +00002762 llvm_unreachable("unknown capture result");
2763 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002764}
2765
John McCall755d8492011-04-12 00:42:48 +00002766ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002767 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002768
Reid Spencer5f016e22007-07-11 17:01:13 +00002769 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00002770 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002771 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2772 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2773 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002774 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002775
Chris Lattnerfa28b302008-01-12 08:14:25 +00002776 // Pre-defined identifiers are of type char[x], where x is the length of the
2777 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002778
Anders Carlsson3a082d82009-09-08 18:24:21 +00002779 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002780 if (!currentDecl && getCurBlock())
2781 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002782 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002783 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002784 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002785 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002786
Anders Carlsson773f3972009-09-11 01:22:35 +00002787 QualType ResTy;
2788 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2789 ResTy = Context.DependentTy;
2790 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002791 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002792
Anders Carlsson773f3972009-09-11 01:22:35 +00002793 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00002794 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002795 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2796 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002797 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002798}
2799
John McCall60d7b3a2010-08-24 06:29:42 +00002800ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002801 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002802 bool Invalid = false;
2803 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2804 if (Invalid)
2805 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002806
Benjamin Kramerddeea562010-02-27 13:44:12 +00002807 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2808 PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00002809 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002810 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002811
Chris Lattnere8337df2009-12-30 21:19:39 +00002812 QualType Ty;
2813 if (!getLangOptions().CPlusPlus)
2814 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2815 else if (Literal.isWide())
2816 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedman136b0cd2010-02-03 18:21:45 +00002817 else if (Literal.isMultiChar())
2818 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002819 else
2820 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002821
Sebastian Redle91b3bc2009-01-20 22:23:13 +00002822 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2823 Literal.isWide(),
Chris Lattnere8337df2009-12-30 21:19:39 +00002824 Ty, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002825}
2826
John McCall60d7b3a2010-08-24 06:29:42 +00002827ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002828 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00002829 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2830 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002831 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00002832 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002833 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00002834 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002835 }
Ted Kremenek28396602009-01-13 23:19:12 +00002836
Reid Spencer5f016e22007-07-11 17:01:13 +00002837 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002838 // Add padding so that NumericLiteralParser can overread by one character.
2839 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002840 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002841
Reid Spencer5f016e22007-07-11 17:01:13 +00002842 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002843 bool Invalid = false;
2844 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2845 if (Invalid)
2846 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002847
Mike Stump1eb44332009-09-09 15:08:12 +00002848 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002849 Tok.getLocation(), PP);
2850 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002851 return ExprError();
2852
Chris Lattner5d661452007-08-26 03:42:43 +00002853 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002854
Chris Lattner5d661452007-08-26 03:42:43 +00002855 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002856 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002857 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002858 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002859 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002860 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002861 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002862 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002863
2864 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2865
John McCall94c939d2009-12-24 09:08:04 +00002866 using llvm::APFloat;
2867 APFloat Val(Format);
2868
2869 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00002870
2871 // Overflow is always an error, but underflow is only an error if
2872 // we underflowed to zero (APFloat reports denormals as underflow).
2873 if ((result & APFloat::opOverflow) ||
2874 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00002875 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002876 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00002877 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00002878 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00002879 APFloat::getLargest(Format).toString(buffer);
2880 } else {
John McCall2a0d7572010-02-26 23:35:57 +00002881 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00002882 APFloat::getSmallest(Format).toString(buffer);
2883 }
2884
2885 Diag(Tok.getLocation(), diagnostic)
2886 << Ty
2887 << llvm::StringRef(buffer.data(), buffer.size());
2888 }
2889
2890 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002891 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002892
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002893 if (Ty == Context.DoubleTy) {
2894 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002895 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002896 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2897 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002898 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002899 }
2900 }
Chris Lattner5d661452007-08-26 03:42:43 +00002901 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002902 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002903 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002904 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002905
Neil Boothb9449512007-08-29 22:00:19 +00002906 // long long is a C99 feature.
2907 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00002908 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00002909 Diag(Tok.getLocation(), diag::ext_longlong);
2910
Reid Spencer5f016e22007-07-11 17:01:13 +00002911 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00002912 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002913
Reid Spencer5f016e22007-07-11 17:01:13 +00002914 if (Literal.GetIntegerValue(ResultVal)) {
2915 // If this value didn't fit into uintmax_t, warn and force to ull.
2916 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002917 Ty = Context.UnsignedLongLongTy;
2918 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002919 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002920 } else {
2921 // If this value fits into a ULL, try to figure out what else it fits into
2922 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002923
Reid Spencer5f016e22007-07-11 17:01:13 +00002924 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2925 // be an unsigned int.
2926 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2927
2928 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002929 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002930 if (!Literal.isLong && !Literal.isLongLong) {
2931 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002932 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002933
Reid Spencer5f016e22007-07-11 17:01:13 +00002934 // Does it fit in a unsigned int?
2935 if (ResultVal.isIntN(IntSize)) {
2936 // Does it fit in a signed int?
2937 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002938 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002939 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002940 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002941 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002942 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002943 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002944
Reid Spencer5f016e22007-07-11 17:01:13 +00002945 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002946 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002947 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002948
Reid Spencer5f016e22007-07-11 17:01:13 +00002949 // Does it fit in a unsigned long?
2950 if (ResultVal.isIntN(LongSize)) {
2951 // Does it fit in a signed long?
2952 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002953 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002954 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002955 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002956 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002957 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002958 }
2959
Reid Spencer5f016e22007-07-11 17:01:13 +00002960 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002961 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002962 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002963
Reid Spencer5f016e22007-07-11 17:01:13 +00002964 // Does it fit in a unsigned long long?
2965 if (ResultVal.isIntN(LongLongSize)) {
2966 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002967 // To be compatible with MSVC, hex integer literals ending with the
2968 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002969 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2970 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002971 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002972 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002973 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002974 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002975 }
2976 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002977
Reid Spencer5f016e22007-07-11 17:01:13 +00002978 // If we still couldn't decide a type, we probably have something that
2979 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002980 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002981 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002982 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002983 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002984 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002985
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002986 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002987 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002988 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002989 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002990 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002991
Chris Lattner5d661452007-08-26 03:42:43 +00002992 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2993 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002994 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002995 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002996
2997 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002998}
2999
John McCall60d7b3a2010-08-24 06:29:42 +00003000ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCall9ae2f072010-08-23 23:25:46 +00003001 SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00003002 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00003003 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00003004}
3005
3006/// The UsualUnaryConversions() function is *not* called by this routine.
3007/// See C99 6.3.2.1p[2-4] for more details.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003008bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
3009 SourceLocation OpLoc,
3010 SourceRange ExprRange,
3011 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl28507842009-02-26 14:39:58 +00003012 if (exprType->isDependentType())
3013 return false;
3014
Sebastian Redl5d484e82009-11-23 17:18:46 +00003015 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3016 // the result is the size of the referenced type."
3017 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3018 // result shall be the alignment of the referenced type."
3019 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
3020 exprType = Ref->getPointeeType();
3021
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003022 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3023 // scalar or vector data type argument..."
3024 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3025 // type (C99 6.2.5p18) or void.
3026 if (ExprKind == UETT_VecStep) {
3027 if (!(exprType->isArithmeticType() || exprType->isVoidType() ||
3028 exprType->isVectorType())) {
3029 Diag(OpLoc, diag::err_vecstep_non_scalar_vector_type)
3030 << exprType << ExprRange;
3031 return true;
3032 }
3033 }
3034
Reid Spencer5f016e22007-07-11 17:01:13 +00003035 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00003036 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003037 // alignof(function) is allowed as an extension.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003038 if (ExprKind == UETT_SizeOf)
3039 Diag(OpLoc, diag::ext_sizeof_function_type)
3040 << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00003041 return false;
3042 }
Mike Stump1eb44332009-09-09 15:08:12 +00003043
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003044 // Allow sizeof(void)/alignof(void) as an extension. vec_step(void) is not
3045 // an extension, as void is a built-in scalar type (OpenCL 1.1 6.1.1).
Chris Lattner01072922009-01-24 19:46:37 +00003046 if (exprType->isVoidType()) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003047 if (ExprKind != UETT_VecStep)
3048 Diag(OpLoc, diag::ext_sizeof_void_type)
3049 << ExprKind << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00003050 return false;
3051 }
Mike Stump1eb44332009-09-09 15:08:12 +00003052
Chris Lattner1efaa952009-04-24 00:30:45 +00003053 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00003054 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003055 << ExprKind << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00003056 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003057
Chris Lattner1efaa952009-04-24 00:30:45 +00003058 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCallc12c5bb2010-05-15 11:32:37 +00003059 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003060 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003061 << exprType << (ExprKind == UETT_SizeOf)
3062 << ExprRange;
Chris Lattner5cb10d32009-04-24 22:30:50 +00003063 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00003064 }
Mike Stump1eb44332009-09-09 15:08:12 +00003065
Chris Lattner1efaa952009-04-24 00:30:45 +00003066 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00003067}
3068
John McCall2a984ca2010-10-12 00:20:44 +00003069static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
3070 SourceRange ExprRange) {
Chris Lattner31e21e02009-01-24 20:17:12 +00003071 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00003072
Mike Stump1eb44332009-09-09 15:08:12 +00003073 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00003074 if (isa<DeclRefExpr>(E))
3075 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00003076
3077 // Cannot know anything else if the expression is dependent.
3078 if (E->isTypeDependent())
3079 return false;
3080
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003081 if (E->getBitField()) {
John McCall2a984ca2010-10-12 00:20:44 +00003082 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003083 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00003084 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003085
3086 // Alignment of a field access is always okay, so long as it isn't a
3087 // bit-field.
3088 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00003089 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003090 return false;
3091
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003092 return S.CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
3093 UETT_AlignOf);
3094}
3095
3096bool Sema::CheckVecStepExpr(Expr *E, SourceLocation OpLoc,
3097 SourceRange ExprRange) {
3098 E = E->IgnoreParens();
3099
3100 // Cannot know anything else if the expression is dependent.
3101 if (E->isTypeDependent())
3102 return false;
3103
3104 return CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
3105 UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00003106}
3107
Douglas Gregorba498172009-03-13 21:01:28 +00003108/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003109ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003110Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3111 SourceLocation OpLoc,
3112 UnaryExprOrTypeTrait ExprKind,
3113 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00003114 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00003115 return ExprError();
3116
John McCalla93c9342009-12-07 02:54:59 +00003117 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00003118
Douglas Gregorba498172009-03-13 21:01:28 +00003119 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003120 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00003121 return ExprError();
3122
3123 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003124 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3125 Context.getSizeType(),
3126 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003127}
3128
3129/// \brief Build a sizeof or alignof expression given an expression
3130/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003131ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003132Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3133 UnaryExprOrTypeTrait ExprKind,
3134 SourceRange R) {
Douglas Gregorba498172009-03-13 21:01:28 +00003135 // Verify that the operand is valid.
3136 bool isInvalid = false;
3137 if (E->isTypeDependent()) {
3138 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003139 } else if (ExprKind == UETT_AlignOf) {
John McCall2a984ca2010-10-12 00:20:44 +00003140 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003141 } else if (ExprKind == UETT_VecStep) {
3142 isInvalid = CheckVecStepExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003143 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00003144 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
3145 isInvalid = true;
John McCall2cd11fe2010-10-12 02:09:17 +00003146 } else if (E->getType()->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00003147 ExprResult PE = CheckPlaceholderExpr(E);
John McCall2cd11fe2010-10-12 02:09:17 +00003148 if (PE.isInvalid()) return ExprError();
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003149 return CreateUnaryExprOrTypeTraitExpr(PE.take(), OpLoc, ExprKind, R);
Douglas Gregorba498172009-03-13 21:01:28 +00003150 } else {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003151 isInvalid = CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, R,
3152 UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00003153 }
3154
3155 if (isInvalid)
3156 return ExprError();
3157
3158 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003159 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, E,
3160 Context.getSizeType(),
3161 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003162}
3163
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003164/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3165/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00003166/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00003167ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003168Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3169 UnaryExprOrTypeTrait ExprKind, bool isType,
3170 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003171 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003172 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003173
Sebastian Redl05189992008-11-11 17:56:53 +00003174 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00003175 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00003176 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003177 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00003178 }
Sebastian Redl05189992008-11-11 17:56:53 +00003179
Douglas Gregorba498172009-03-13 21:01:28 +00003180 Expr *ArgEx = (Expr *)TyOrEx;
John McCall60d7b3a2010-08-24 06:29:42 +00003181 ExprResult Result
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003182 = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind,
3183 ArgEx->getSourceRange());
Douglas Gregorba498172009-03-13 21:01:28 +00003184
Douglas Gregorba498172009-03-13 21:01:28 +00003185 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00003186}
3187
John Wiegley429bb272011-04-08 18:41:53 +00003188static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall09431682010-11-18 19:01:18 +00003189 bool isReal) {
John Wiegley429bb272011-04-08 18:41:53 +00003190 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00003191 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003192
John McCallf6a16482010-12-04 03:47:34 +00003193 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00003194 if (V.get()->getObjectKind() != OK_Ordinary) {
3195 V = S.DefaultLvalueConversion(V.take());
3196 if (V.isInvalid())
3197 return QualType();
3198 }
John McCallf6a16482010-12-04 03:47:34 +00003199
Chris Lattnercc26ed72007-08-26 05:39:26 +00003200 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00003201 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00003202 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00003203
Chris Lattnercc26ed72007-08-26 05:39:26 +00003204 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00003205 if (V.get()->getType()->isArithmeticType())
3206 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003207
John McCall2cd11fe2010-10-12 02:09:17 +00003208 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00003209 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00003210 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003211 if (PR.get() != V.get()) {
3212 V = move(PR);
John McCall09431682010-11-18 19:01:18 +00003213 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall2cd11fe2010-10-12 02:09:17 +00003214 }
3215
Chris Lattnercc26ed72007-08-26 05:39:26 +00003216 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003217 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattnerba27e2a2009-02-17 08:12:06 +00003218 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003219 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003220}
3221
3222
Reid Spencer5f016e22007-07-11 17:01:13 +00003223
John McCall60d7b3a2010-08-24 06:29:42 +00003224ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003225Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003226 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003227 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003228 switch (Kind) {
3229 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003230 case tok::plusplus: Opc = UO_PostInc; break;
3231 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003232 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003233
John McCall9ae2f072010-08-23 23:25:46 +00003234 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003235}
3236
John McCall09431682010-11-18 19:01:18 +00003237/// Expressions of certain arbitrary types are forbidden by C from
3238/// having l-value type. These are:
3239/// - 'void', but not qualified void
3240/// - function types
3241///
3242/// The exact rule here is C99 6.3.2.1:
3243/// An lvalue is an expression with an object type or an incomplete
3244/// type other than void.
3245static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
3246 return ((T->isVoidType() && !T.hasQualifiers()) ||
3247 T->isFunctionType());
3248}
3249
John McCall60d7b3a2010-08-24 06:29:42 +00003250ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003251Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3252 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003253 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003254 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003255 if (Result.isInvalid()) return ExprError();
3256 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003257
John McCall9ae2f072010-08-23 23:25:46 +00003258 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00003259
Douglas Gregor337c6b92008-11-19 17:17:41 +00003260 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003261 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003262 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003263 Context.DependentTy,
3264 VK_LValue, OK_Ordinary,
3265 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003266 }
3267
Mike Stump1eb44332009-09-09 15:08:12 +00003268 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003269 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003270 LHSExp->getType()->isEnumeralType() ||
3271 RHSExp->getType()->isRecordType() ||
3272 RHSExp->getType()->isEnumeralType())) {
John McCall9ae2f072010-08-23 23:25:46 +00003273 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003274 }
3275
John McCall9ae2f072010-08-23 23:25:46 +00003276 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003277}
3278
3279
John McCall60d7b3a2010-08-24 06:29:42 +00003280ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003281Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3282 Expr *Idx, SourceLocation RLoc) {
3283 Expr *LHSExp = Base;
3284 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003285
Chris Lattner12d9ff62007-07-16 00:14:47 +00003286 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003287 if (!LHSExp->getType()->getAs<VectorType>()) {
3288 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3289 if (Result.isInvalid())
3290 return ExprError();
3291 LHSExp = Result.take();
3292 }
3293 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3294 if (Result.isInvalid())
3295 return ExprError();
3296 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003297
Chris Lattner12d9ff62007-07-16 00:14:47 +00003298 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003299 ExprValueKind VK = VK_LValue;
3300 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003301
Reid Spencer5f016e22007-07-11 17:01:13 +00003302 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003303 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003304 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003305 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003306 Expr *BaseExpr, *IndexExpr;
3307 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003308 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3309 BaseExpr = LHSExp;
3310 IndexExpr = RHSExp;
3311 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003312 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003313 BaseExpr = LHSExp;
3314 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003315 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003316 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00003317 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00003318 BaseExpr = RHSExp;
3319 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003320 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003321 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003322 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003323 BaseExpr = LHSExp;
3324 IndexExpr = RHSExp;
3325 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003326 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003327 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003328 // Handle the uncommon case of "123[Ptr]".
3329 BaseExpr = RHSExp;
3330 IndexExpr = LHSExp;
3331 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003332 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003333 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003334 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003335 VK = LHSExp->getValueKind();
3336 if (VK != VK_RValue)
3337 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003338
Chris Lattner12d9ff62007-07-16 00:14:47 +00003339 // FIXME: need to deal with const...
3340 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003341 } else if (LHSTy->isArrayType()) {
3342 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003343 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003344 // wasn't promoted because of the C90 rule that doesn't
3345 // allow promoting non-lvalue arrays. Warn, then
3346 // force the promotion here.
3347 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3348 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003349 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3350 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003351 LHSTy = LHSExp->getType();
3352
3353 BaseExpr = LHSExp;
3354 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003355 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003356 } else if (RHSTy->isArrayType()) {
3357 // Same as previous, except for 123[f().a] case
3358 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3359 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003360 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3361 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003362 RHSTy = RHSExp->getType();
3363
3364 BaseExpr = RHSExp;
3365 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003366 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003367 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003368 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3369 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003370 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003371 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003372 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003373 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3374 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003375
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003376 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003377 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3378 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003379 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3380
Douglas Gregore7450f52009-03-24 19:52:54 +00003381 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003382 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3383 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003384 // incomplete types are not object types.
3385 if (ResultType->isFunctionType()) {
3386 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3387 << ResultType << BaseExpr->getSourceRange();
3388 return ExprError();
3389 }
Mike Stump1eb44332009-09-09 15:08:12 +00003390
Abramo Bagnara46358452010-09-13 06:50:07 +00003391 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3392 // GNU extension: subscripting on pointer to void
3393 Diag(LLoc, diag::ext_gnu_void_ptr)
3394 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003395
3396 // C forbids expressions of unqualified void type from being l-values.
3397 // See IsCForbiddenLValueType.
3398 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003399 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003400 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003401 PDiag(diag::err_subscript_incomplete_type)
3402 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00003403 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003404
Chris Lattner1efaa952009-04-24 00:30:45 +00003405 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00003406 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003407 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3408 << ResultType << BaseExpr->getSourceRange();
3409 return ExprError();
3410 }
Mike Stump1eb44332009-09-09 15:08:12 +00003411
John McCall09431682010-11-18 19:01:18 +00003412 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3413 !IsCForbiddenLValueType(Context, ResultType));
3414
Mike Stumpeed9cac2009-02-19 03:04:26 +00003415 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003416 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003417}
3418
John McCall09431682010-11-18 19:01:18 +00003419/// Check an ext-vector component access expression.
3420///
3421/// VK should be set in advance to the value kind of the base
3422/// expression.
3423static QualType
3424CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3425 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00003426 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00003427 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3428 // see FIXME there.
3429 //
3430 // FIXME: This logic can be greatly simplified by splitting it along
3431 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00003432 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00003433
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003434 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00003435 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00003436
Mike Stumpeed9cac2009-02-19 03:04:26 +00003437 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00003438 // special names that indicate a subset of exactly half the elements are
3439 // to be selected.
3440 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003441
Nate Begeman353417a2009-01-18 01:47:54 +00003442 // This flag determines whether or not CompName has an 's' char prefix,
3443 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00003444 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00003445
John McCall09431682010-11-18 19:01:18 +00003446 bool HasRepeated = false;
3447 bool HasIndex[16] = {};
3448
3449 int Idx;
3450
Nate Begeman8a997642008-05-09 06:41:27 +00003451 // Check that we've found one of the special components, or that the component
3452 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003453 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00003454 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3455 HalvingSwizzle = true;
John McCall09431682010-11-18 19:01:18 +00003456 } else if (!HexSwizzle &&
3457 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3458 do {
3459 if (HasIndex[Idx]) HasRepeated = true;
3460 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00003461 compStr++;
John McCall09431682010-11-18 19:01:18 +00003462 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3463 } else {
3464 if (HexSwizzle) compStr++;
3465 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3466 if (HasIndex[Idx]) HasRepeated = true;
3467 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00003468 compStr++;
John McCall09431682010-11-18 19:01:18 +00003469 }
Chris Lattner88dca042007-08-02 22:33:49 +00003470 }
Nate Begeman353417a2009-01-18 01:47:54 +00003471
Mike Stumpeed9cac2009-02-19 03:04:26 +00003472 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003473 // We didn't get to the end of the string. This means the component names
3474 // didn't come from the same set *or* we encountered an illegal name.
John McCall09431682010-11-18 19:01:18 +00003475 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00003476 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003477 return QualType();
3478 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003479
Nate Begeman353417a2009-01-18 01:47:54 +00003480 // Ensure no component accessor exceeds the width of the vector type it
3481 // operates on.
3482 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00003483 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00003484
3485 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003486 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00003487
3488 while (*compStr) {
3489 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall09431682010-11-18 19:01:18 +00003490 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begeman353417a2009-01-18 01:47:54 +00003491 << baseType << SourceRange(CompLoc);
3492 return QualType();
3493 }
3494 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003495 }
Nate Begeman8a997642008-05-09 06:41:27 +00003496
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003497 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003498 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003499 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00003500 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00003501 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman0479a0b2009-12-15 18:13:04 +00003502 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00003503 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00003504 if (HexSwizzle)
3505 CompSize--;
3506
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003507 if (CompSize == 1)
3508 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003509
John McCall09431682010-11-18 19:01:18 +00003510 if (HasRepeated) VK = VK_RValue;
3511
3512 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003513 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00003514 // diagostics look bad. We want extended vector types to appear built-in.
John McCall09431682010-11-18 19:01:18 +00003515 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3516 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3517 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00003518 }
3519 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003520}
3521
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003522static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00003523 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003524 const Selector &Sel,
3525 ASTContext &Context) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003526 if (Member)
3527 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3528 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003529 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003530 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00003531
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003532 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3533 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003534 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3535 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003536 return D;
3537 }
3538 return 0;
3539}
3540
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003541static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3542 IdentifierInfo *Member,
3543 const Selector &Sel,
3544 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003545 // Check protocols on qualified interfaces.
3546 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003547 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003548 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003549 if (Member)
3550 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3551 GDecl = PD;
3552 break;
3553 }
3554 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003555 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003556 GDecl = OMD;
3557 break;
3558 }
3559 }
3560 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003561 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003562 E = QIdTy->qual_end(); I != E; ++I) {
3563 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003564 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3565 Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003566 if (GDecl)
3567 return GDecl;
3568 }
3569 }
3570 return GDecl;
3571}
Chris Lattner76a642f2009-02-15 22:43:40 +00003572
John McCall60d7b3a2010-08-24 06:29:42 +00003573ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003574Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCallaa81e162009-12-01 22:10:20 +00003575 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00003576 const CXXScopeSpec &SS,
3577 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003578 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003579 const TemplateArgumentListInfo *TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00003580 // Even in dependent contexts, try to diagnose base expressions with
3581 // obviously wrong types, e.g.:
3582 //
3583 // T* t;
3584 // t.f;
3585 //
3586 // In Obj-C++, however, the above expression is valid, since it could be
3587 // accessing the 'f' property if T is an Obj-C interface. The extra check
3588 // allows this, while still reporting an error if T is a struct pointer.
3589 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00003590 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00003591 if (PT && (!getLangOptions().ObjC1 ||
3592 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00003593 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnara25777432010-08-11 22:01:17 +00003594 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00003595 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00003596 return ExprError();
3597 }
3598 }
3599
Abramo Bagnara25777432010-08-11 22:01:17 +00003600 assert(BaseType->isDependentType() ||
3601 NameInfo.getName().isDependentName() ||
Douglas Gregor01e56ae2010-04-12 20:54:26 +00003602 isDependentScopeSpecifier(SS));
John McCall129e2df2009-11-30 22:42:35 +00003603
3604 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3605 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00003606 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003607 IsArrow, OpLoc,
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003608 SS.getWithLocInContext(Context),
John McCall129e2df2009-11-30 22:42:35 +00003609 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003610 NameInfo, TemplateArgs));
John McCall129e2df2009-11-30 22:42:35 +00003611}
3612
3613/// We know that the given qualified member reference points only to
3614/// declarations which do not belong to the static type of the base
3615/// expression. Diagnose the problem.
3616static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3617 Expr *BaseExpr,
3618 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003619 const CXXScopeSpec &SS,
John McCall5808ce42011-02-03 08:15:49 +00003620 NamedDecl *rep,
3621 const DeclarationNameInfo &nameInfo) {
John McCall2f841ba2009-12-02 03:53:29 +00003622 // If this is an implicit member access, use a different set of
3623 // diagnostics.
3624 if (!BaseExpr)
John McCall5808ce42011-02-03 08:15:49 +00003625 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall129e2df2009-11-30 22:42:35 +00003626
John McCall5808ce42011-02-03 08:15:49 +00003627 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3628 << SS.getRange() << rep << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00003629}
3630
3631// Check whether the declarations we found through a nested-name
3632// specifier in a member expression are actually members of the base
3633// type. The restriction here is:
3634//
3635// C++ [expr.ref]p2:
3636// ... In these cases, the id-expression shall name a
3637// member of the class or of one of its base classes.
3638//
3639// So it's perfectly legitimate for the nested-name specifier to name
3640// an unrelated class, and for us to find an overload set including
3641// decls from classes which are not superclasses, as long as the decl
3642// we actually pick through overload resolution is from a superclass.
3643bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3644 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003645 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003646 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00003647 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3648 if (!BaseRT) {
3649 // We can't check this yet because the base type is still
3650 // dependent.
3651 assert(BaseType->isDependentType());
3652 return false;
3653 }
3654 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00003655
3656 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00003657 // If this is an implicit member reference and we find a
3658 // non-instance member, it's not an error.
John McCall161755a2010-04-06 21:38:20 +00003659 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCallaa81e162009-12-01 22:10:20 +00003660 return false;
John McCall129e2df2009-11-30 22:42:35 +00003661
John McCallaa81e162009-12-01 22:10:20 +00003662 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman02463762010-07-27 20:51:02 +00003663 DeclContext *DC = (*I)->getDeclContext();
3664 while (DC->isTransparentContext())
3665 DC = DC->getParent();
John McCallaa81e162009-12-01 22:10:20 +00003666
Douglas Gregor9d4bb942010-07-28 22:27:52 +00003667 if (!DC->isRecord())
3668 continue;
3669
John McCallaa81e162009-12-01 22:10:20 +00003670 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman02463762010-07-27 20:51:02 +00003671 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCallaa81e162009-12-01 22:10:20 +00003672
3673 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3674 return false;
3675 }
3676
John McCall5808ce42011-02-03 08:15:49 +00003677 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3678 R.getRepresentativeDecl(),
3679 R.getLookupNameInfo());
John McCallaa81e162009-12-01 22:10:20 +00003680 return true;
3681}
3682
3683static bool
3684LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3685 SourceRange BaseRange, const RecordType *RTy,
John McCallad00b772010-06-16 08:42:20 +00003686 SourceLocation OpLoc, CXXScopeSpec &SS,
3687 bool HasTemplateArgs) {
John McCallaa81e162009-12-01 22:10:20 +00003688 RecordDecl *RDecl = RTy->getDecl();
3689 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003690 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCallaa81e162009-12-01 22:10:20 +00003691 << BaseRange))
3692 return true;
3693
John McCallad00b772010-06-16 08:42:20 +00003694 if (HasTemplateArgs) {
3695 // LookupTemplateName doesn't expect these both to exist simultaneously.
3696 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3697
3698 bool MOUS;
3699 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3700 return false;
3701 }
3702
John McCallaa81e162009-12-01 22:10:20 +00003703 DeclContext *DC = RDecl;
3704 if (SS.isSet()) {
3705 // If the member name was a qualified-id, look into the
3706 // nested-name-specifier.
3707 DC = SemaRef.computeDeclContext(SS, false);
3708
John McCall77bb1aa2010-05-01 00:40:08 +00003709 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCall2f841ba2009-12-02 03:53:29 +00003710 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3711 << SS.getRange() << DC;
3712 return true;
3713 }
3714
John McCallaa81e162009-12-01 22:10:20 +00003715 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003716
John McCallaa81e162009-12-01 22:10:20 +00003717 if (!isa<TypeDecl>(DC)) {
3718 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3719 << DC << SS.getRange();
3720 return true;
John McCall129e2df2009-11-30 22:42:35 +00003721 }
3722 }
3723
John McCallaa81e162009-12-01 22:10:20 +00003724 // The record definition is complete, now look up the member.
3725 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00003726
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003727 if (!R.empty())
3728 return false;
3729
3730 // We didn't find anything with the given name, so try to correct
3731 // for typos.
3732 DeclarationName Name = R.getLookupName();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003733 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00003734 !R.empty() &&
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003735 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3736 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3737 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00003738 << FixItHint::CreateReplacement(R.getNameLoc(),
3739 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00003740 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3741 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3742 << ND->getDeclName();
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003743 return false;
3744 } else {
3745 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003746 R.setLookupName(Name);
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003747 }
3748
John McCall129e2df2009-11-30 22:42:35 +00003749 return false;
3750}
3751
John McCall60d7b3a2010-08-24 06:29:42 +00003752ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003753Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003754 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003755 CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003756 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003757 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003758 const TemplateArgumentListInfo *TemplateArgs) {
John McCall2f841ba2009-12-02 03:53:29 +00003759 if (BaseType->isDependentType() ||
3760 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCall9ae2f072010-08-23 23:25:46 +00003761 return ActOnDependentMemberExpr(Base, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003762 IsArrow, OpLoc,
3763 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003764 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003765
Abramo Bagnara25777432010-08-11 22:01:17 +00003766 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00003767
John McCallaa81e162009-12-01 22:10:20 +00003768 // Implicit member accesses.
3769 if (!Base) {
3770 QualType RecordTy = BaseType;
3771 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3772 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3773 RecordTy->getAs<RecordType>(),
John McCallad00b772010-06-16 08:42:20 +00003774 OpLoc, SS, TemplateArgs != 0))
John McCallaa81e162009-12-01 22:10:20 +00003775 return ExprError();
3776
3777 // Explicit member accesses.
3778 } else {
John Wiegley429bb272011-04-08 18:41:53 +00003779 ExprResult BaseResult = Owned(Base);
John McCall60d7b3a2010-08-24 06:29:42 +00003780 ExprResult Result =
John Wiegley429bb272011-04-08 18:41:53 +00003781 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCalld226f652010-08-21 09:40:31 +00003782 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCallaa81e162009-12-01 22:10:20 +00003783
John Wiegley429bb272011-04-08 18:41:53 +00003784 if (BaseResult.isInvalid())
3785 return ExprError();
3786 Base = BaseResult.take();
3787
John McCallaa81e162009-12-01 22:10:20 +00003788 if (Result.isInvalid()) {
3789 Owned(Base);
3790 return ExprError();
3791 }
3792
3793 if (Result.get())
3794 return move(Result);
Sebastian Redlf3e63372010-05-07 09:25:11 +00003795
3796 // LookupMemberExpr can modify Base, and thus change BaseType
3797 BaseType = Base->getType();
John McCall129e2df2009-11-30 22:42:35 +00003798 }
3799
John McCall9ae2f072010-08-23 23:25:46 +00003800 return BuildMemberReferenceExpr(Base, BaseType,
John McCallc2233c52010-01-15 08:34:02 +00003801 OpLoc, IsArrow, SS, FirstQualifierInScope,
3802 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003803}
3804
John McCall60d7b3a2010-08-24 06:29:42 +00003805ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003806Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCallaa81e162009-12-01 22:10:20 +00003807 SourceLocation OpLoc, bool IsArrow,
3808 const CXXScopeSpec &SS,
John McCallc2233c52010-01-15 08:34:02 +00003809 NamedDecl *FirstQualifierInScope,
John McCall129e2df2009-11-30 22:42:35 +00003810 LookupResult &R,
Douglas Gregor06a9f362010-05-01 20:49:11 +00003811 const TemplateArgumentListInfo *TemplateArgs,
3812 bool SuppressQualifierCheck) {
John McCallaa81e162009-12-01 22:10:20 +00003813 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00003814 if (IsArrow) {
3815 assert(BaseType->isPointerType());
3816 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3817 }
John McCall161755a2010-04-06 21:38:20 +00003818 R.setBaseObjectType(BaseType);
John McCall129e2df2009-11-30 22:42:35 +00003819
Abramo Bagnara25777432010-08-11 22:01:17 +00003820 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3821 DeclarationName MemberName = MemberNameInfo.getName();
3822 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall129e2df2009-11-30 22:42:35 +00003823
3824 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00003825 return ExprError();
3826
John McCall129e2df2009-11-30 22:42:35 +00003827 if (R.empty()) {
3828 // Rederive where we looked up.
3829 DeclContext *DC = (SS.isSet()
3830 ? computeDeclContext(SS, false)
3831 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00003832
John McCall129e2df2009-11-30 22:42:35 +00003833 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00003834 << MemberName << DC
3835 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00003836 return ExprError();
3837 }
3838
John McCallc2233c52010-01-15 08:34:02 +00003839 // Diagnose lookups that find only declarations from a non-base
3840 // type. This is possible for either qualified lookups (which may
3841 // have been qualified with an unrelated type) or implicit member
3842 // expressions (which were found with unqualified lookup and thus
3843 // may have come from an enclosing scope). Note that it's okay for
3844 // lookup to find declarations from a non-base type as long as those
3845 // aren't the ones picked by overload resolution.
3846 if ((SS.isSet() || !BaseExpr ||
3847 (isa<CXXThisExpr>(BaseExpr) &&
3848 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00003849 !SuppressQualifierCheck &&
John McCallc2233c52010-01-15 08:34:02 +00003850 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00003851 return ExprError();
3852
3853 // Construct an unresolved result if we in fact got an unresolved
3854 // result.
3855 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallc373d482010-01-27 01:50:18 +00003856 // Suppress any lookup-related diagnostics; we'll do these when we
3857 // pick a member.
3858 R.suppressDiagnostics();
3859
John McCall129e2df2009-11-30 22:42:35 +00003860 UnresolvedMemberExpr *MemExpr
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003861 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00003862 BaseExpr, BaseExprType,
3863 IsArrow, OpLoc,
Douglas Gregor4c9be892011-02-28 20:01:57 +00003864 SS.getWithLocInContext(Context),
Abramo Bagnara25777432010-08-11 22:01:17 +00003865 MemberNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00003866 TemplateArgs, R.begin(), R.end());
John McCall129e2df2009-11-30 22:42:35 +00003867
3868 return Owned(MemExpr);
3869 }
3870
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003871 assert(R.isSingleResult());
John McCall161755a2010-04-06 21:38:20 +00003872 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall129e2df2009-11-30 22:42:35 +00003873 NamedDecl *MemberDecl = R.getFoundDecl();
3874
3875 // FIXME: diagnose the presence of template arguments now.
3876
3877 // If the decl being referenced had an error, return an error for this
3878 // sub-expr without emitting another error, in order to avoid cascading
3879 // error cases.
3880 if (MemberDecl->isInvalidDecl())
3881 return ExprError();
3882
John McCallaa81e162009-12-01 22:10:20 +00003883 // Handle the implicit-member-access case.
3884 if (!BaseExpr) {
3885 // If this is not an instance member, convert to a non-member access.
John McCall161755a2010-04-06 21:38:20 +00003886 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnara25777432010-08-11 22:01:17 +00003887 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCallaa81e162009-12-01 22:10:20 +00003888
Douglas Gregor828a1972010-01-07 23:12:05 +00003889 SourceLocation Loc = R.getNameLoc();
3890 if (SS.getRange().isValid())
3891 Loc = SS.getRange().getBegin();
3892 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003893 }
3894
John McCall129e2df2009-11-30 22:42:35 +00003895 bool ShouldCheckUse = true;
3896 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3897 // Don't diagnose the use of a virtual member function unless it's
3898 // explicitly qualified.
3899 if (MD->isVirtual() && !SS.isSet())
3900 ShouldCheckUse = false;
3901 }
3902
3903 // Check the use of this member.
3904 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3905 Owned(BaseExpr);
3906 return ExprError();
3907 }
3908
John McCallf6a16482010-12-04 03:47:34 +00003909 // Perform a property load on the base regardless of whether we
3910 // actually need it for the declaration.
John Wiegley429bb272011-04-08 18:41:53 +00003911 if (BaseExpr->getObjectKind() == OK_ObjCProperty) {
3912 ExprResult Result = ConvertPropertyForRValue(BaseExpr);
3913 if (Result.isInvalid())
3914 return ExprError();
3915 BaseExpr = Result.take();
3916 }
John McCallf6a16482010-12-04 03:47:34 +00003917
John McCalldfa1edb2010-11-23 20:48:44 +00003918 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3919 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3920 SS, FD, FoundDecl, MemberNameInfo);
John McCall129e2df2009-11-30 22:42:35 +00003921
Francois Pichet87c2e122010-11-21 06:08:52 +00003922 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3923 // We may have found a field within an anonymous union or struct
3924 // (C++ [class.union]).
John McCall5808ce42011-02-03 08:15:49 +00003925 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCallf6a16482010-12-04 03:47:34 +00003926 BaseExpr, OpLoc);
Francois Pichet87c2e122010-11-21 06:08:52 +00003927
John McCall129e2df2009-11-30 22:42:35 +00003928 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3929 MarkDeclarationReferenced(MemberLoc, Var);
3930 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003931 Var, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003932 Var->getType().getNonReferenceType(),
John McCall09431682010-11-18 19:01:18 +00003933 VK_LValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003934 }
3935
John McCallf89e55a2010-11-18 06:31:45 +00003936 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall864c0412011-04-26 20:42:42 +00003937 ExprValueKind valueKind;
3938 QualType type;
3939 if (MemberFn->isInstance()) {
3940 valueKind = VK_RValue;
3941 type = Context.BoundMemberTy;
3942 } else {
3943 valueKind = VK_LValue;
3944 type = MemberFn->getType();
3945 }
3946
John McCall129e2df2009-11-30 22:42:35 +00003947 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3948 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003949 MemberFn, FoundDecl, MemberNameInfo,
John McCall864c0412011-04-26 20:42:42 +00003950 type, valueKind, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003951 }
John McCallf89e55a2010-11-18 06:31:45 +00003952 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall129e2df2009-11-30 22:42:35 +00003953
3954 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3955 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3956 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003957 Enum, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003958 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003959 }
3960
3961 Owned(BaseExpr);
3962
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003963 // We found something that we didn't expect. Complain.
John McCall129e2df2009-11-30 22:42:35 +00003964 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnara25777432010-08-11 22:01:17 +00003965 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003966 << MemberName << BaseType << int(IsArrow);
3967 else
3968 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3969 << MemberName << BaseType << int(IsArrow);
John McCall129e2df2009-11-30 22:42:35 +00003970
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003971 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3972 << MemberName;
Douglas Gregor2b147f02010-04-25 21:15:30 +00003973 R.suppressDiagnostics();
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003974 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00003975}
3976
John McCall028d3972010-12-15 16:46:44 +00003977/// Given that normal member access failed on the given expression,
3978/// and given that the expression's type involves builtin-id or
3979/// builtin-Class, decide whether substituting in the redefinition
3980/// types would be profitable. The redefinition type is whatever
3981/// this translation unit tried to typedef to id/Class; we store
3982/// it to the side and then re-use it in places like this.
John Wiegley429bb272011-04-08 18:41:53 +00003983static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
John McCall028d3972010-12-15 16:46:44 +00003984 const ObjCObjectPointerType *opty
John Wiegley429bb272011-04-08 18:41:53 +00003985 = base.get()->getType()->getAs<ObjCObjectPointerType>();
John McCall028d3972010-12-15 16:46:44 +00003986 if (!opty) return false;
3987
3988 const ObjCObjectType *ty = opty->getObjectType();
3989
3990 QualType redef;
3991 if (ty->isObjCId()) {
3992 redef = S.Context.ObjCIdRedefinitionType;
3993 } else if (ty->isObjCClass()) {
3994 redef = S.Context.ObjCClassRedefinitionType;
3995 } else {
3996 return false;
3997 }
3998
3999 // Do the substitution as long as the redefinition type isn't just a
4000 // possibly-qualified pointer to builtin-id or builtin-Class again.
4001 opty = redef->getAs<ObjCObjectPointerType>();
4002 if (opty && !opty->getObjectType()->getInterface() != 0)
4003 return false;
4004
John Wiegley429bb272011-04-08 18:41:53 +00004005 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
John McCall028d3972010-12-15 16:46:44 +00004006 return true;
4007}
4008
John McCall129e2df2009-11-30 22:42:35 +00004009/// Look up the given member of the given non-type-dependent
4010/// expression. This can return in one of two ways:
4011/// * If it returns a sentinel null-but-valid result, the caller will
4012/// assume that lookup was performed and the results written into
4013/// the provided structure. It will take over from there.
4014/// * Otherwise, the returned expression will be produced in place of
4015/// an ordinary member expression.
4016///
4017/// The ObjCImpDecl bit is a gross hack that will need to be properly
4018/// fixed for ObjC++.
John McCall60d7b3a2010-08-24 06:29:42 +00004019ExprResult
John Wiegley429bb272011-04-08 18:41:53 +00004020Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
John McCall812c1542009-12-07 22:46:59 +00004021 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004022 CXXScopeSpec &SS,
John McCalld226f652010-08-21 09:40:31 +00004023 Decl *ObjCImpDecl, bool HasTemplateArgs) {
John Wiegley429bb272011-04-08 18:41:53 +00004024 assert(BaseExpr.get() && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00004025
Steve Naroff3cc4af82007-12-16 21:42:28 +00004026 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00004027 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
Sebastian Redl0eb23302009-01-19 00:08:26 +00004028
John Wiegley429bb272011-04-08 18:41:53 +00004029 if (IsArrow) {
4030 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4031 if (BaseExpr.isInvalid())
4032 return ExprError();
4033 }
4034
4035 QualType BaseType = BaseExpr.get()->getType();
John McCall129e2df2009-11-30 22:42:35 +00004036 assert(!BaseType->isDependentType());
4037
4038 DeclarationName MemberName = R.getLookupName();
4039 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00004040
John McCall028d3972010-12-15 16:46:44 +00004041 // For later type-checking purposes, turn arrow accesses into dot
4042 // accesses. The only access type we support that doesn't follow
4043 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
4044 // and those never use arrows, so this is unaffected.
4045 if (IsArrow) {
4046 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4047 BaseType = Ptr->getPointeeType();
4048 else if (const ObjCObjectPointerType *Ptr
4049 = BaseType->getAs<ObjCObjectPointerType>())
4050 BaseType = Ptr->getPointeeType();
4051 else if (BaseType->isRecordType()) {
4052 // Recover from arrow accesses to records, e.g.:
4053 // struct MyRecord foo;
4054 // foo->bar
4055 // This is actually well-formed in C++ if MyRecord has an
4056 // overloaded operator->, but that should have been dealt with
4057 // by now.
4058 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley429bb272011-04-08 18:41:53 +00004059 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
John McCall028d3972010-12-15 16:46:44 +00004060 << FixItHint::CreateReplacement(OpLoc, ".");
4061 IsArrow = false;
John McCall864c0412011-04-26 20:42:42 +00004062 } else if (BaseType == Context.BoundMemberTy) {
4063 goto fail;
John McCall028d3972010-12-15 16:46:44 +00004064 } else {
4065 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
John Wiegley429bb272011-04-08 18:41:53 +00004066 << BaseType << BaseExpr.get()->getSourceRange();
John McCall028d3972010-12-15 16:46:44 +00004067 return ExprError();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00004068 }
4069 }
4070
John McCall028d3972010-12-15 16:46:44 +00004071 // Handle field access to simple records.
4072 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John Wiegley429bb272011-04-08 18:41:53 +00004073 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
John McCall028d3972010-12-15 16:46:44 +00004074 RTy, OpLoc, SS, HasTemplateArgs))
4075 return ExprError();
4076
4077 // Returning valid-but-null is how we indicate to the caller that
4078 // the lookup result was filled in.
4079 return Owned((Expr*) 0);
David Chisnall0f436562009-08-17 16:35:33 +00004080 }
John McCall129e2df2009-11-30 22:42:35 +00004081
John McCall028d3972010-12-15 16:46:44 +00004082 // Handle ivar access to Objective-C objects.
4083 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004084 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall028d3972010-12-15 16:46:44 +00004085
4086 // There are three cases for the base type:
4087 // - builtin id (qualified or unqualified)
4088 // - builtin Class (qualified or unqualified)
4089 // - an interface
4090 ObjCInterfaceDecl *IDecl = OTy->getInterface();
4091 if (!IDecl) {
4092 // There's an implicit 'isa' ivar on all objects.
4093 // But we only actually find it this way on objects of type 'id',
4094 // apparently.
4095 if (OTy->isObjCId() && Member->isStr("isa"))
John Wiegley429bb272011-04-08 18:41:53 +00004096 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
John McCall028d3972010-12-15 16:46:44 +00004097 Context.getObjCClassType()));
4098
4099 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4100 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4101 ObjCImpDecl, HasTemplateArgs);
4102 goto fail;
4103 }
4104
4105 ObjCInterfaceDecl *ClassDeclared;
4106 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
4107
4108 if (!IV) {
4109 // Attempt to correct for typos in ivar names.
4110 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
4111 LookupMemberName);
4112 if (CorrectTypo(Res, 0, 0, IDecl, false,
4113 IsArrow ? CTC_ObjCIvarLookup
4114 : CTC_ObjCPropertyLookup) &&
4115 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
4116 Diag(R.getNameLoc(),
4117 diag::err_typecheck_member_reference_ivar_suggest)
4118 << IDecl->getDeclName() << MemberName << IV->getDeclName()
4119 << FixItHint::CreateReplacement(R.getNameLoc(),
4120 IV->getNameAsString());
4121 Diag(IV->getLocation(), diag::note_previous_decl)
4122 << IV->getDeclName();
4123 } else {
4124 Res.clear();
4125 Res.setLookupName(Member);
4126
4127 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
4128 << IDecl->getDeclName() << MemberName
John Wiegley429bb272011-04-08 18:41:53 +00004129 << BaseExpr.get()->getSourceRange();
John McCall028d3972010-12-15 16:46:44 +00004130 return ExprError();
4131 }
4132 }
4133
4134 // If the decl being referenced had an error, return an error for this
4135 // sub-expr without emitting another error, in order to avoid cascading
4136 // error cases.
4137 if (IV->isInvalidDecl())
4138 return ExprError();
4139
4140 // Check whether we can reference this field.
4141 if (DiagnoseUseOfDecl(IV, MemberLoc))
4142 return ExprError();
4143 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
4144 IV->getAccessControl() != ObjCIvarDecl::Package) {
4145 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
4146 if (ObjCMethodDecl *MD = getCurMethodDecl())
4147 ClassOfMethodDecl = MD->getClassInterface();
4148 else if (ObjCImpDecl && getCurFunctionDecl()) {
4149 // Case of a c-function declared inside an objc implementation.
4150 // FIXME: For a c-style function nested inside an objc implementation
4151 // class, there is no implementation context available, so we pass
4152 // down the context as argument to this routine. Ideally, this context
4153 // need be passed down in the AST node and somehow calculated from the
4154 // AST for a function decl.
4155 if (ObjCImplementationDecl *IMPD =
4156 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
4157 ClassOfMethodDecl = IMPD->getClassInterface();
4158 else if (ObjCCategoryImplDecl* CatImplClass =
4159 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
4160 ClassOfMethodDecl = CatImplClass->getClassInterface();
4161 }
4162
4163 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
4164 if (ClassDeclared != IDecl ||
4165 ClassOfMethodDecl != ClassDeclared)
4166 Diag(MemberLoc, diag::error_private_ivar_access)
4167 << IV->getDeclName();
4168 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
4169 // @protected
4170 Diag(MemberLoc, diag::error_protected_ivar_access)
4171 << IV->getDeclName();
4172 }
4173
4174 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
John Wiegley429bb272011-04-08 18:41:53 +00004175 MemberLoc, BaseExpr.take(),
John McCall028d3972010-12-15 16:46:44 +00004176 IsArrow));
4177 }
4178
4179 // Objective-C property access.
4180 const ObjCObjectPointerType *OPT;
4181 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
4182 // This actually uses the base as an r-value.
John Wiegley429bb272011-04-08 18:41:53 +00004183 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4184 if (BaseExpr.isInvalid())
4185 return ExprError();
4186
4187 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
John McCall028d3972010-12-15 16:46:44 +00004188
4189 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
4190
4191 const ObjCObjectType *OT = OPT->getObjectType();
4192
4193 // id, with and without qualifiers.
4194 if (OT->isObjCId()) {
4195 // Check protocols on qualified interfaces.
4196 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
4197 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
4198 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
4199 // Check the use of this declaration
4200 if (DiagnoseUseOfDecl(PD, MemberLoc))
4201 return ExprError();
4202
4203 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
4204 VK_LValue,
4205 OK_ObjCProperty,
4206 MemberLoc,
John Wiegley429bb272011-04-08 18:41:53 +00004207 BaseExpr.take()));
John McCall028d3972010-12-15 16:46:44 +00004208 }
4209
4210 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
4211 // Check the use of this method.
4212 if (DiagnoseUseOfDecl(OMD, MemberLoc))
4213 return ExprError();
4214 Selector SetterSel =
4215 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4216 PP.getSelectorTable(), Member);
4217 ObjCMethodDecl *SMD = 0;
4218 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
4219 SetterSel, Context))
4220 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
4221 QualType PType = OMD->getSendResultType();
4222
4223 ExprValueKind VK = VK_LValue;
4224 if (!getLangOptions().CPlusPlus &&
4225 IsCForbiddenLValueType(Context, PType))
4226 VK = VK_RValue;
4227 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4228
4229 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
4230 VK, OK,
John Wiegley429bb272011-04-08 18:41:53 +00004231 MemberLoc, BaseExpr.take()));
John McCall028d3972010-12-15 16:46:44 +00004232 }
4233 }
Fariborz Jahanian4eb7f692011-03-15 17:27:48 +00004234 // Use of id.member can only be for a property reference. Do not
4235 // use the 'id' redefinition in this case.
4236 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
John McCall028d3972010-12-15 16:46:44 +00004237 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4238 ObjCImpDecl, HasTemplateArgs);
4239
4240 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
4241 << MemberName << BaseType);
4242 }
4243
4244 // 'Class', unqualified only.
4245 if (OT->isObjCClass()) {
4246 // Only works in a method declaration (??!).
4247 ObjCMethodDecl *MD = getCurMethodDecl();
4248 if (!MD) {
4249 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4250 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4251 ObjCImpDecl, HasTemplateArgs);
4252
4253 goto fail;
4254 }
4255
4256 // Also must look for a getter name which uses property syntax.
4257 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004258 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4259 ObjCMethodDecl *Getter;
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004260 if ((Getter = IFace->lookupClassMethod(Sel))) {
4261 // Check the use of this method.
4262 if (DiagnoseUseOfDecl(Getter, MemberLoc))
4263 return ExprError();
John McCall028d3972010-12-15 16:46:44 +00004264 } else
Fariborz Jahanian74b27562010-12-03 23:37:08 +00004265 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004266 // If we found a getter then this may be a valid dot-reference, we
4267 // will look for the matching setter, in case it is needed.
4268 Selector SetterSel =
John McCall028d3972010-12-15 16:46:44 +00004269 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4270 PP.getSelectorTable(), Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004271 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
4272 if (!Setter) {
4273 // If this reference is in an @implementation, also check for 'private'
4274 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +00004275 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004276 }
4277 // Look through local category implementations associated with the class.
4278 if (!Setter)
4279 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004280
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004281 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
4282 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004283
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004284 if (Getter || Setter) {
4285 QualType PType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004286
John McCall09431682010-11-18 19:01:18 +00004287 ExprValueKind VK = VK_LValue;
4288 if (Getter) {
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004289 PType = Getter->getSendResultType();
John McCall09431682010-11-18 19:01:18 +00004290 if (!getLangOptions().CPlusPlus &&
4291 IsCForbiddenLValueType(Context, PType))
4292 VK = VK_RValue;
4293 } else {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004294 // Get the expression type from Setter's incoming parameter.
4295 PType = (*(Setter->param_end() -1))->getType();
John McCall09431682010-11-18 19:01:18 +00004296 }
4297 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4298
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004299 // FIXME: we must check that the setter has property type.
John McCall12f78a62010-12-02 01:19:52 +00004300 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
4301 PType, VK, OK,
John Wiegley429bb272011-04-08 18:41:53 +00004302 MemberLoc, BaseExpr.take()));
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004303 }
John McCall028d3972010-12-15 16:46:44 +00004304
4305 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4306 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4307 ObjCImpDecl, HasTemplateArgs);
4308
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004309 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall028d3972010-12-15 16:46:44 +00004310 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00004311 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004312
John McCall028d3972010-12-15 16:46:44 +00004313 // Normal property access.
John Wiegley429bb272011-04-08 18:41:53 +00004314 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), MemberName, MemberLoc,
John McCall028d3972010-12-15 16:46:44 +00004315 SourceLocation(), QualType(), false);
Steve Naroff14108da2009-07-10 23:34:53 +00004316 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004317
Chris Lattnerfb173ec2008-07-21 04:28:12 +00004318 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00004319 if (BaseType->isExtVectorType()) {
John McCall5e3c67b2010-12-15 04:42:30 +00004320 // FIXME: this expr should store IsArrow.
Anders Carlsson8f28f992009-08-26 18:25:21 +00004321 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John Wiegley429bb272011-04-08 18:41:53 +00004322 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
John McCall09431682010-11-18 19:01:18 +00004323 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
4324 Member, MemberLoc);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00004325 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004326 return ExprError();
John McCall09431682010-11-18 19:01:18 +00004327
John Wiegley429bb272011-04-08 18:41:53 +00004328 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
John McCall09431682010-11-18 19:01:18 +00004329 *Member, MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00004330 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004331
John McCall028d3972010-12-15 16:46:44 +00004332 // Adjust builtin-sel to the appropriate redefinition type if that's
4333 // not just a pointer to builtin-sel again.
4334 if (IsArrow &&
4335 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
4336 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004337 BaseExpr = ImpCastExprToType(BaseExpr.take(), Context.ObjCSelRedefinitionType,
4338 CK_BitCast);
John McCall028d3972010-12-15 16:46:44 +00004339 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4340 ObjCImpDecl, HasTemplateArgs);
4341 }
4342
4343 // Failure cases.
4344 fail:
4345
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004346 // Recover from dot accesses to pointers, e.g.:
4347 // type *foo;
4348 // foo.bar
4349 // This is actually well-formed in two cases:
4350 // - 'type' is an Objective C type
4351 // - 'bar' is a pseudo-destructor name which happens to refer to
4352 // the appropriate pointer type
John McCall028d3972010-12-15 16:46:44 +00004353 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004354 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
4355 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
John McCall028d3972010-12-15 16:46:44 +00004356 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley429bb272011-04-08 18:41:53 +00004357 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004358 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall028d3972010-12-15 16:46:44 +00004359
4360 // Recurse as an -> access.
4361 IsArrow = true;
4362 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4363 ObjCImpDecl, HasTemplateArgs);
4364 }
John McCall028d3972010-12-15 16:46:44 +00004365 }
4366
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004367 // If the user is trying to apply -> or . to a function name, it's probably
4368 // because they forgot parentheses to call that function.
4369 bool TryCall = false;
4370 bool Overloaded = false;
4371 UnresolvedSet<8> AllOverloads;
John Wiegley429bb272011-04-08 18:41:53 +00004372 if (const OverloadExpr *Overloads = dyn_cast<OverloadExpr>(BaseExpr.get())) {
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004373 AllOverloads.append(Overloads->decls_begin(), Overloads->decls_end());
4374 TryCall = true;
4375 Overloaded = true;
John Wiegley429bb272011-04-08 18:41:53 +00004376 } else if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(BaseExpr.get())) {
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004377 if (FunctionDecl* Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
4378 AllOverloads.addDecl(Fun);
4379 TryCall = true;
4380 }
4381 }
John McCall028d3972010-12-15 16:46:44 +00004382
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004383 if (TryCall) {
4384 // Plunder the overload set for something that would make the member
4385 // expression valid.
4386 UnresolvedSet<4> ViableOverloads;
4387 bool HasViableZeroArgOverload = false;
4388 for (OverloadExpr::decls_iterator it = AllOverloads.begin(),
4389 DeclsEnd = AllOverloads.end(); it != DeclsEnd; ++it) {
Matt Beaumont-Gayfbe59942011-03-05 02:42:30 +00004390 // Our overload set may include TemplateDecls, which we'll ignore for the
4391 // purposes of determining whether we can issue a '()' fixit.
4392 if (const FunctionDecl *OverloadDecl = dyn_cast<FunctionDecl>(*it)) {
4393 QualType ResultTy = OverloadDecl->getResultType();
4394 if ((!IsArrow && ResultTy->isRecordType()) ||
4395 (IsArrow && ResultTy->isPointerType() &&
4396 ResultTy->getPointeeType()->isRecordType())) {
4397 ViableOverloads.addDecl(*it);
4398 if (OverloadDecl->getMinRequiredArguments() == 0) {
4399 HasViableZeroArgOverload = true;
4400 }
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004401 }
John McCall028d3972010-12-15 16:46:44 +00004402 }
4403 }
4404
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004405 if (!HasViableZeroArgOverload || ViableOverloads.size() != 1) {
John Wiegley429bb272011-04-08 18:41:53 +00004406 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gayfbe59942011-03-05 02:42:30 +00004407 << (AllOverloads.size() > 1) << 0
John Wiegley429bb272011-04-08 18:41:53 +00004408 << BaseExpr.get()->getSourceRange();
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004409 int ViableOverloadCount = ViableOverloads.size();
4410 int I;
4411 for (I = 0; I < ViableOverloadCount; ++I) {
4412 // FIXME: Magic number for max shown overloads stolen from
4413 // OverloadCandidateSet::NoteCandidates.
4414 if (I >= 4 && Diags.getShowOverloads() == Diagnostic::Ovl_Best) {
4415 break;
4416 }
4417 Diag(ViableOverloads[I].getDecl()->getSourceRange().getBegin(),
4418 diag::note_member_ref_possible_intended_overload);
4419 }
4420 if (I != ViableOverloadCount) {
John Wiegley429bb272011-04-08 18:41:53 +00004421 Diag(BaseExpr.get()->getExprLoc(), diag::note_ovl_too_many_candidates)
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004422 << int(ViableOverloadCount - I);
4423 }
4424 return ExprError();
4425 }
4426 } else {
4427 // We don't have an expression that's convenient to get a Decl from, but we
4428 // can at least check if the type is "function of 0 arguments which returns
4429 // an acceptable type".
4430 const FunctionType *Fun = NULL;
4431 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4432 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
4433 TryCall = true;
4434 }
4435 } else if ((Fun = BaseType->getAs<FunctionType>())) {
4436 TryCall = true;
John McCall864c0412011-04-26 20:42:42 +00004437 } else if (BaseType == Context.BoundMemberTy) {
4438 // Look for the bound-member type. If it's still overloaded,
4439 // give up, although we probably should have fallen into the
4440 // OverloadExpr case above if we actually have an overloaded
4441 // bound member.
4442 QualType fnType = Expr::findBoundMemberType(BaseExpr.get());
4443 if (!fnType.isNull()) {
4444 TryCall = true;
4445 Fun = fnType->castAs<FunctionType>();
4446 }
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004447 }
John McCall028d3972010-12-15 16:46:44 +00004448
4449 if (TryCall) {
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004450 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
4451 if (FPT->getNumArgs() == 0) {
4452 QualType ResultTy = Fun->getResultType();
4453 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
4454 (IsArrow && ResultTy->isPointerType() &&
4455 ResultTy->getPointeeType()->isRecordType());
4456 }
Matt Beaumont-Gay26ae5dd2011-02-17 02:54:17 +00004457 }
John McCall028d3972010-12-15 16:46:44 +00004458 }
4459 }
4460
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004461 if (TryCall) {
4462 // At this point, we know BaseExpr looks like it's potentially callable with
4463 // 0 arguments, and that it returns something of a reasonable type, so we
4464 // can emit a fixit and carry on pretending that BaseExpr was actually a
4465 // CallExpr.
4466 SourceLocation ParenInsertionLoc =
John Wiegley429bb272011-04-08 18:41:53 +00004467 PP.getLocForEndOfToken(BaseExpr.get()->getLocEnd());
4468 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004469 << int(Overloaded) << 1
John Wiegley429bb272011-04-08 18:41:53 +00004470 << BaseExpr.get()->getSourceRange()
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004471 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
John Wiegley429bb272011-04-08 18:41:53 +00004472 ExprResult NewBase = ActOnCallExpr(0, BaseExpr.take(), ParenInsertionLoc,
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004473 MultiExprArg(*this, 0, 0),
4474 ParenInsertionLoc);
4475 if (NewBase.isInvalid())
4476 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004477 BaseExpr = NewBase;
4478 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004479 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4480 ObjCImpDecl, HasTemplateArgs);
4481 }
4482
Douglas Gregor214f31a2009-03-27 06:00:30 +00004483 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
John Wiegley429bb272011-04-08 18:41:53 +00004484 << BaseType << BaseExpr.get()->getSourceRange();
Douglas Gregor214f31a2009-03-27 06:00:30 +00004485
Douglas Gregor214f31a2009-03-27 06:00:30 +00004486 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00004487}
4488
John McCall129e2df2009-11-30 22:42:35 +00004489/// The main callback when the parser finds something like
4490/// expression . [nested-name-specifier] identifier
4491/// expression -> [nested-name-specifier] identifier
4492/// where 'identifier' encompasses a fairly broad spectrum of
4493/// possibilities, including destructor and operator references.
4494///
4495/// \param OpKind either tok::arrow or tok::period
4496/// \param HasTrailingLParen whether the next token is '(', which
4497/// is used to diagnose mis-uses of special members that can
4498/// only be called
4499/// \param ObjCImpDecl the current ObjC @implementation decl;
4500/// this is an ugly hack around the fact that ObjC @implementations
4501/// aren't properly put in the context chain
John McCall60d7b3a2010-08-24 06:29:42 +00004502ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall5e3c67b2010-12-15 04:42:30 +00004503 SourceLocation OpLoc,
4504 tok::TokenKind OpKind,
4505 CXXScopeSpec &SS,
4506 UnqualifiedId &Id,
4507 Decl *ObjCImpDecl,
4508 bool HasTrailingLParen) {
John McCall129e2df2009-11-30 22:42:35 +00004509 if (SS.isSet() && SS.isInvalid())
4510 return ExprError();
4511
Francois Pichetdbee3412011-01-18 05:04:39 +00004512 // Warn about the explicit constructor calls Microsoft extension.
4513 if (getLangOptions().Microsoft &&
4514 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4515 Diag(Id.getSourceRange().getBegin(),
4516 diag::ext_ms_explicit_constructor_call);
4517
John McCall129e2df2009-11-30 22:42:35 +00004518 TemplateArgumentListInfo TemplateArgsBuffer;
4519
4520 // Decompose the name into its component parts.
Abramo Bagnara25777432010-08-11 22:01:17 +00004521 DeclarationNameInfo NameInfo;
John McCall129e2df2009-11-30 22:42:35 +00004522 const TemplateArgumentListInfo *TemplateArgs;
4523 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnara25777432010-08-11 22:01:17 +00004524 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004525
Abramo Bagnara25777432010-08-11 22:01:17 +00004526 DeclarationName Name = NameInfo.getName();
John McCall129e2df2009-11-30 22:42:35 +00004527 bool IsArrow = (OpKind == tok::arrow);
4528
4529 NamedDecl *FirstQualifierInScope
4530 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4531 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4532
4533 // This is a postfix expression, so get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004534 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004535 if (Result.isInvalid()) return ExprError();
4536 Base = Result.take();
John McCall129e2df2009-11-30 22:42:35 +00004537
Douglas Gregor01e56ae2010-04-12 20:54:26 +00004538 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4539 isDependentScopeSpecifier(SS)) {
John McCall9ae2f072010-08-23 23:25:46 +00004540 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00004541 IsArrow, OpLoc,
4542 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00004543 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004544 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00004545 LookupResult R(*this, NameInfo, LookupMemberName);
John Wiegley429bb272011-04-08 18:41:53 +00004546 ExprResult BaseResult = Owned(Base);
4547 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCallad00b772010-06-16 08:42:20 +00004548 SS, ObjCImpDecl, TemplateArgs != 0);
John Wiegley429bb272011-04-08 18:41:53 +00004549 if (BaseResult.isInvalid())
4550 return ExprError();
4551 Base = BaseResult.take();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004552
John McCallad00b772010-06-16 08:42:20 +00004553 if (Result.isInvalid()) {
4554 Owned(Base);
4555 return ExprError();
4556 }
John McCall129e2df2009-11-30 22:42:35 +00004557
John McCallad00b772010-06-16 08:42:20 +00004558 if (Result.get()) {
4559 // The only way a reference to a destructor can be used is to
4560 // immediately call it, which falls into this case. If the
4561 // next token is not a '(', produce a diagnostic and build the
4562 // call now.
4563 if (!HasTrailingLParen &&
4564 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCall9ae2f072010-08-23 23:25:46 +00004565 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall129e2df2009-11-30 22:42:35 +00004566
John McCallad00b772010-06-16 08:42:20 +00004567 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00004568 }
4569
John McCall9ae2f072010-08-23 23:25:46 +00004570 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCallc2233c52010-01-15 08:34:02 +00004571 OpLoc, IsArrow, SS, FirstQualifierInScope,
4572 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004573 }
4574
4575 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00004576}
4577
John McCall60d7b3a2010-08-24 06:29:42 +00004578ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00004579 FunctionDecl *FD,
4580 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00004581 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004582 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00004583 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00004584 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00004585 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00004586 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004587 return ExprError();
4588 }
4589
4590 if (Param->hasUninstantiatedDefaultArg()) {
4591 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00004592
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004593 // Instantiate the expression.
4594 MultiLevelTemplateArgumentList ArgList
4595 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00004596
Nico Weber08e41a62010-11-29 18:19:25 +00004597 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004598 = ArgList.getInnermost();
4599 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4600 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004601
Nico Weber08e41a62010-11-29 18:19:25 +00004602 ExprResult Result;
4603 {
4604 // C++ [dcl.fct.default]p5:
4605 // The names in the [default argument] expression are bound, and
4606 // the semantic constraints are checked, at the point where the
4607 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00004608 ContextRAII SavedContext(*this, FD);
Nico Weber08e41a62010-11-29 18:19:25 +00004609 Result = SubstExpr(UninstExpr, ArgList);
4610 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004611 if (Result.isInvalid())
4612 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004613
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004614 // Check the expression as an initializer for the parameter.
4615 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004616 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004617 InitializationKind Kind
4618 = InitializationKind::CreateCopy(Param->getLocation(),
4619 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4620 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00004621
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004622 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4623 Result = InitSeq.Perform(*this, Entity, Kind,
4624 MultiExprArg(*this, &ResultE, 1));
4625 if (Result.isInvalid())
4626 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004627
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004628 // Build the default argument expression.
4629 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4630 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004631 }
4632
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004633 // If the default expression creates temporaries, we need to
4634 // push them to the current stack of expression temporaries so they'll
4635 // be properly destroyed.
4636 // FIXME: We should really be rebuilding the default argument with new
4637 // bound temporaries; see the comment in PR5810.
Douglas Gregor5833b0b2010-09-14 22:55:20 +00004638 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4639 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4640 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4641 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4642 ExprTemporaries.push_back(Temporary);
4643 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004644
4645 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00004646 // Just mark all of the declarations in this potentially-evaluated expression
4647 // as being "referenced".
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004648 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor036aed12009-12-23 23:03:06 +00004649 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004650}
4651
Douglas Gregor88a35142008-12-22 05:46:06 +00004652/// ConvertArgumentsForCall - Converts the arguments specified in
4653/// Args/NumArgs to the parameter types of the function FDecl with
4654/// function prototype Proto. Call is the call expression itself, and
4655/// Fn is the function expression. For a C++ member function, this
4656/// routine does not attempt to convert the object argument. Returns
4657/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004658bool
4659Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00004660 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00004661 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00004662 Expr **Args, unsigned NumArgs,
4663 SourceLocation RParenLoc) {
John McCall8e10f3b2011-02-26 05:39:39 +00004664 // Bail out early if calling a builtin with custom typechecking.
4665 // We don't need to do this in the
4666 if (FDecl)
4667 if (unsigned ID = FDecl->getBuiltinID())
4668 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4669 return false;
4670
Mike Stumpeed9cac2009-02-19 03:04:26 +00004671 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00004672 // assignment, to the types of the corresponding parameter, ...
4673 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004674 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004675
Douglas Gregor88a35142008-12-22 05:46:06 +00004676 // If too few arguments are available (and we don't have default
4677 // arguments for the remaining parameters), don't make the call.
4678 if (NumArgs < NumArgsInProto) {
4679 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4680 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004681 << Fn->getType()->isBlockPointerType()
Eric Christopherd77b9a22010-04-16 04:48:22 +00004682 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00004683 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00004684 }
4685
4686 // If too many are passed and not variadic, error on the extras and drop
4687 // them.
4688 if (NumArgs > NumArgsInProto) {
4689 if (!Proto->isVariadic()) {
4690 Diag(Args[NumArgsInProto]->getLocStart(),
4691 diag::err_typecheck_call_too_many_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004692 << Fn->getType()->isBlockPointerType()
Eric Christopherccfa9632010-04-16 04:56:46 +00004693 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00004694 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4695 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00004696
4697 // Emit the location of the prototype.
4698 if (FDecl && !FDecl->getBuiltinID())
4699 Diag(FDecl->getLocStart(),
4700 diag::note_typecheck_call_too_many_args)
4701 << FDecl;
4702
Douglas Gregor88a35142008-12-22 05:46:06 +00004703 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004704 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004705 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004706 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004707 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004708 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004709 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004710 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4711 if (Fn->getType()->isBlockPointerType())
4712 CallType = VariadicBlock; // Block
4713 else if (isa<MemberExpr>(Fn))
4714 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004715 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004716 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004717 if (Invalid)
4718 return true;
4719 unsigned TotalNumArgs = AllArgs.size();
4720 for (unsigned i = 0; i < TotalNumArgs; ++i)
4721 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004722
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004723 return false;
4724}
Mike Stumpeed9cac2009-02-19 03:04:26 +00004725
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004726bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4727 FunctionDecl *FDecl,
4728 const FunctionProtoType *Proto,
4729 unsigned FirstProtoArg,
4730 Expr **Args, unsigned NumArgs,
4731 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004732 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004733 unsigned NumArgsInProto = Proto->getNumArgs();
4734 unsigned NumArgsToCheck = NumArgs;
4735 bool Invalid = false;
4736 if (NumArgs != NumArgsInProto)
4737 // Use default arguments for missing arguments
4738 NumArgsToCheck = NumArgsInProto;
4739 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00004740 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004741 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004742 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004743
Douglas Gregor88a35142008-12-22 05:46:06 +00004744 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004745 if (ArgIx < NumArgs) {
4746 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004747
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004748 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4749 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00004750 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004751 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004752 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004753
Douglas Gregora188ff22009-12-22 16:09:06 +00004754 // Pass the argument
4755 ParmVarDecl *Param = 0;
4756 if (FDecl && i < FDecl->getNumParams())
4757 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00004758
Douglas Gregora188ff22009-12-22 16:09:06 +00004759 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004760 Param? InitializedEntity::InitializeParameter(Context, Param)
4761 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCall60d7b3a2010-08-24 06:29:42 +00004762 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00004763 SourceLocation(),
4764 Owned(Arg));
Douglas Gregora188ff22009-12-22 16:09:06 +00004765 if (ArgE.isInvalid())
4766 return true;
4767
4768 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004769 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00004770 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004771
John McCall60d7b3a2010-08-24 06:29:42 +00004772 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004773 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004774 if (ArgExpr.isInvalid())
4775 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004776
Anders Carlsson56c5e332009-08-25 03:49:14 +00004777 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004778 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004779 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00004780 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004781
Douglas Gregor88a35142008-12-22 05:46:06 +00004782 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004783 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00004784
4785 // Assume that extern "C" functions with variadic arguments that
4786 // return __unknown_anytype aren't *really* variadic.
4787 if (Proto->getResultType() == Context.UnknownAnyTy &&
4788 FDecl && FDecl->isExternC()) {
4789 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4790 ExprResult arg;
4791 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
4792 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
4793 else
4794 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4795 Invalid |= arg.isInvalid();
4796 AllArgs.push_back(arg.take());
4797 }
4798
4799 // Otherwise do argument promotion, (C99 6.5.2.2p7).
4800 } else {
4801 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4802 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4803 Invalid |= Arg.isInvalid();
4804 AllArgs.push_back(Arg.take());
4805 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004806 }
4807 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004808 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00004809}
4810
John McCall755d8492011-04-12 00:42:48 +00004811/// Given a function expression of unknown-any type, try to rebuild it
4812/// to have a function type.
4813static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4814
Steve Narofff69936d2007-09-16 03:34:24 +00004815/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00004816/// This provides the location of the left/right parens and a list of comma
4817/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00004818ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004819Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004820 MultiExprArg args, SourceLocation RParenLoc,
4821 Expr *ExecConfig) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00004822 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00004823
4824 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004825 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00004826 if (Result.isInvalid()) return ExprError();
4827 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00004828
John McCall9ae2f072010-08-23 23:25:46 +00004829 Expr **Args = args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004830
Douglas Gregor88a35142008-12-22 05:46:06 +00004831 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00004832 // If this is a pseudo-destructor expression, build the call immediately.
4833 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4834 if (NumArgs > 0) {
4835 // Pseudo-destructor calls should not have any arguments.
4836 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00004837 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00004838 SourceRange(Args[0]->getLocStart(),
4839 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00004840
Douglas Gregora71d8192009-09-04 17:36:40 +00004841 NumArgs = 0;
4842 }
Mike Stump1eb44332009-09-09 15:08:12 +00004843
Douglas Gregora71d8192009-09-04 17:36:40 +00004844 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00004845 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00004846 }
Mike Stump1eb44332009-09-09 15:08:12 +00004847
Douglas Gregor17330012009-02-04 15:01:18 +00004848 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00004849 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00004850 // FIXME: Will need to cache the results of name lookup (including ADL) in
4851 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00004852 bool Dependent = false;
4853 if (Fn->isTypeDependent())
4854 Dependent = true;
4855 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4856 Dependent = true;
4857
Peter Collingbournee08ce652011-02-09 21:07:24 +00004858 if (Dependent) {
4859 if (ExecConfig) {
4860 return Owned(new (Context) CUDAKernelCallExpr(
4861 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4862 Context.DependentTy, VK_RValue, RParenLoc));
4863 } else {
4864 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4865 Context.DependentTy, VK_RValue,
4866 RParenLoc));
4867 }
4868 }
Douglas Gregor17330012009-02-04 15:01:18 +00004869
4870 // Determine whether this is a call to an object (C++ [over.call.object]).
4871 if (Fn->getType()->isRecordType())
4872 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004873 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00004874
John McCall755d8492011-04-12 00:42:48 +00004875 if (Fn->getType() == Context.UnknownAnyTy) {
4876 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4877 if (result.isInvalid()) return ExprError();
4878 Fn = result.take();
4879 }
4880
John McCall864c0412011-04-26 20:42:42 +00004881 if (Fn->getType() == Context.BoundMemberTy) {
John McCallaa81e162009-12-01 22:10:20 +00004882 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004883 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00004884 }
John McCall864c0412011-04-26 20:42:42 +00004885 }
John McCall129e2df2009-11-30 22:42:35 +00004886
John McCall864c0412011-04-26 20:42:42 +00004887 // Check for overloaded calls. This can happen even in C due to extensions.
4888 if (Fn->getType() == Context.OverloadTy) {
4889 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4890
4891 // We aren't supposed to apply this logic if there's an '&' involved.
4892 if (!find.IsAddressOfOperand) {
4893 OverloadExpr *ovl = find.Expression;
4894 if (isa<UnresolvedLookupExpr>(ovl)) {
4895 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4896 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
4897 RParenLoc, ExecConfig);
4898 } else {
John McCallaa81e162009-12-01 22:10:20 +00004899 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004900 RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004901 }
4902 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004903 }
4904
Douglas Gregorfa047642009-02-04 00:32:51 +00004905 // If we're directly calling a function, get the appropriate declaration.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004906
Eli Friedmanefa42f72009-12-26 03:35:45 +00004907 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00004908
John McCall3b4294e2009-12-16 12:17:52 +00004909 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00004910 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4911 if (UnOp->getOpcode() == UO_AddrOf)
4912 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4913
John McCall3b4294e2009-12-16 12:17:52 +00004914 if (isa<DeclRefExpr>(NakedFn))
4915 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00004916 else if (isa<MemberExpr>(NakedFn))
4917 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00004918
Peter Collingbournee08ce652011-02-09 21:07:24 +00004919 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
4920 ExecConfig);
4921}
4922
4923ExprResult
4924Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4925 MultiExprArg execConfig, SourceLocation GGGLoc) {
4926 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4927 if (!ConfigDecl)
4928 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4929 << "cudaConfigureCall");
4930 QualType ConfigQTy = ConfigDecl->getType();
4931
4932 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4933 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
4934
4935 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCallaa81e162009-12-01 22:10:20 +00004936}
4937
John McCall3b4294e2009-12-16 12:17:52 +00004938/// BuildResolvedCallExpr - Build a call to a resolved expression,
4939/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00004940/// unary-convert to an expression of function-pointer or
4941/// block-pointer type.
4942///
4943/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00004944ExprResult
John McCallaa81e162009-12-01 22:10:20 +00004945Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4946 SourceLocation LParenLoc,
4947 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004948 SourceLocation RParenLoc,
4949 Expr *Config) {
John McCallaa81e162009-12-01 22:10:20 +00004950 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4951
Chris Lattner04421082008-04-08 04:40:51 +00004952 // Promote the function operand.
John Wiegley429bb272011-04-08 18:41:53 +00004953 ExprResult Result = UsualUnaryConversions(Fn);
4954 if (Result.isInvalid())
4955 return ExprError();
4956 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00004957
Chris Lattner925e60d2007-12-28 05:29:59 +00004958 // Make the call expr early, before semantic checks. This guarantees cleanup
4959 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00004960 CallExpr *TheCall;
4961 if (Config) {
4962 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4963 cast<CallExpr>(Config),
4964 Args, NumArgs,
4965 Context.BoolTy,
4966 VK_RValue,
4967 RParenLoc);
4968 } else {
4969 TheCall = new (Context) CallExpr(Context, Fn,
4970 Args, NumArgs,
4971 Context.BoolTy,
4972 VK_RValue,
4973 RParenLoc);
4974 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004975
John McCall8e10f3b2011-02-26 05:39:39 +00004976 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4977
4978 // Bail out early if calling a builtin with custom typechecking.
4979 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4980 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4981
John McCall1de4d4e2011-04-07 08:22:57 +00004982 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00004983 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00004984 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00004985 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4986 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00004987 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00004988 if (FuncT == 0)
4989 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4990 << Fn->getType() << Fn->getSourceRange());
4991 } else if (const BlockPointerType *BPT =
4992 Fn->getType()->getAs<BlockPointerType>()) {
4993 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4994 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00004995 // Handle calls to expressions of unknown-any type.
4996 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00004997 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00004998 if (rewrite.isInvalid()) return ExprError();
4999 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00005000 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00005001 goto retry;
5002 }
5003
Sebastian Redl0eb23302009-01-19 00:08:26 +00005004 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5005 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00005006 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00005007
Peter Collingbourne0423fc62011-02-23 01:53:29 +00005008 if (getLangOptions().CUDA) {
5009 if (Config) {
5010 // CUDA: Kernel calls must be to global functions
5011 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5012 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5013 << FDecl->getName() << Fn->getSourceRange());
5014
5015 // CUDA: Kernel function must have 'void' return type
5016 if (!FuncT->getResultType()->isVoidType())
5017 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5018 << Fn->getType() << Fn->getSourceRange());
5019 }
5020 }
5021
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00005022 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005023 if (CheckCallReturnType(FuncT->getResultType(),
John McCall9ae2f072010-08-23 23:25:46 +00005024 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00005025 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00005026 return ExprError();
5027
Chris Lattner925e60d2007-12-28 05:29:59 +00005028 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00005029 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00005030 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00005031
Douglas Gregor72564e72009-02-26 23:50:07 +00005032 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00005033 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00005034 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00005035 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00005036 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00005037 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00005038
Douglas Gregor74734d52009-04-02 15:37:10 +00005039 if (FDecl) {
5040 // Check if we have too few/too many template arguments, based
5041 // on our knowledge of the function definition.
5042 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00005043 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor46542412010-10-25 20:39:23 +00005044 const FunctionProtoType *Proto
5045 = Def->getType()->getAs<FunctionProtoType>();
5046 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00005047 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5048 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00005049 }
Douglas Gregor46542412010-10-25 20:39:23 +00005050
5051 // If the function we're calling isn't a function prototype, but we have
5052 // a function prototype from a prior declaratiom, use that prototype.
5053 if (!FDecl->hasPrototype())
5054 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00005055 }
5056
Steve Naroffb291ab62007-08-28 23:30:39 +00005057 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00005058 for (unsigned i = 0; i != NumArgs; i++) {
5059 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00005060
5061 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00005062 InitializedEntity Entity
5063 = InitializedEntity::InitializeParameter(Context,
5064 Proto->getArgType(i));
5065 ExprResult ArgE = PerformCopyInitialization(Entity,
5066 SourceLocation(),
5067 Owned(Arg));
5068 if (ArgE.isInvalid())
5069 return true;
5070
5071 Arg = ArgE.takeAs<Expr>();
5072
5073 } else {
John Wiegley429bb272011-04-08 18:41:53 +00005074 ExprResult ArgE = DefaultArgumentPromotion(Arg);
5075
5076 if (ArgE.isInvalid())
5077 return true;
5078
5079 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00005080 }
5081
Douglas Gregor0700bbf2010-10-26 05:45:40 +00005082 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
5083 Arg->getType(),
5084 PDiag(diag::err_call_incomplete_argument)
5085 << Arg->getSourceRange()))
5086 return ExprError();
5087
Chris Lattner925e60d2007-12-28 05:29:59 +00005088 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00005089 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005090 }
Chris Lattner925e60d2007-12-28 05:29:59 +00005091
Douglas Gregor88a35142008-12-22 05:46:06 +00005092 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5093 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00005094 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5095 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00005096
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00005097 // Check for sentinels
5098 if (NDecl)
5099 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00005100
Chris Lattner59907c42007-08-10 20:18:51 +00005101 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00005102 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00005103 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00005104 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00005105
John McCall8e10f3b2011-02-26 05:39:39 +00005106 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00005107 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00005108 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00005109 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00005110 return ExprError();
5111 }
Chris Lattner59907c42007-08-10 20:18:51 +00005112
John McCall9ae2f072010-08-23 23:25:46 +00005113 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00005114}
5115
John McCall60d7b3a2010-08-24 06:29:42 +00005116ExprResult
John McCallb3d87482010-08-24 05:47:05 +00005117Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005118 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00005119 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00005120 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00005121 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00005122
5123 TypeSourceInfo *TInfo;
5124 QualType literalType = GetTypeFromParser(Ty, &TInfo);
5125 if (!TInfo)
5126 TInfo = Context.getTrivialTypeSourceInfo(literalType);
5127
John McCall9ae2f072010-08-23 23:25:46 +00005128 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00005129}
5130
John McCall60d7b3a2010-08-24 06:29:42 +00005131ExprResult
John McCall42f56b52010-01-18 19:35:47 +00005132Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCall9ae2f072010-08-23 23:25:46 +00005133 SourceLocation RParenLoc, Expr *literalExpr) {
John McCall42f56b52010-01-18 19:35:47 +00005134 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00005135
Eli Friedman6223c222008-05-20 05:22:08 +00005136 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00005137 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5138 PDiag(diag::err_illegal_decl_array_incomplete_type)
5139 << SourceRange(LParenLoc,
5140 literalExpr->getSourceRange().getEnd())))
5141 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00005142 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005143 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5144 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00005145 } else if (!literalType->isDependentType() &&
5146 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00005147 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00005148 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00005149 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005150 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00005151
Douglas Gregor99a2e602009-12-16 01:38:02 +00005152 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00005153 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00005154 InitializationKind Kind
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005155 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor99a2e602009-12-16 01:38:02 +00005156 /*IsCStyleCast=*/true);
Eli Friedman08544622009-12-22 02:35:53 +00005157 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00005158 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00005159 MultiExprArg(*this, &literalExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00005160 &literalType);
5161 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005162 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00005163 literalExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00005164
Chris Lattner371f2582008-12-04 23:50:19 +00005165 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00005166 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00005167 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005168 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00005169 }
Eli Friedman08544622009-12-22 02:35:53 +00005170
John McCallf89e55a2010-11-18 06:31:45 +00005171 // In C, compound literals are l-values for some reason.
5172 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
5173
John McCall1d7d8d62010-01-19 22:33:45 +00005174 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCallf89e55a2010-11-18 06:31:45 +00005175 VK, literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00005176}
5177
John McCall60d7b3a2010-08-24 06:29:42 +00005178ExprResult
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005179Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005180 SourceLocation RBraceLoc) {
5181 unsigned NumInit = initlist.size();
John McCall9ae2f072010-08-23 23:25:46 +00005182 Expr **InitList = initlist.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00005183
Steve Naroff08d92e42007-09-15 18:49:24 +00005184 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00005185 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005186
Ted Kremenek709210f2010-04-13 23:39:13 +00005187 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
5188 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00005189 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005190 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00005191}
5192
John McCallf3ea8cf2010-11-14 08:17:51 +00005193/// Prepares for a scalar cast, performing all the necessary stages
5194/// except the final cast and returning the kind required.
John Wiegley429bb272011-04-08 18:41:53 +00005195static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00005196 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5197 // Also, callers should have filtered out the invalid cases with
5198 // pointers. Everything else should be possible.
5199
John Wiegley429bb272011-04-08 18:41:53 +00005200 QualType SrcTy = Src.get()->getType();
John McCallf3ea8cf2010-11-14 08:17:51 +00005201 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00005202 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00005203
John McCalldaa8e4e2010-11-15 09:13:47 +00005204 switch (SrcTy->getScalarTypeKind()) {
5205 case Type::STK_MemberPointer:
5206 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00005207
John McCalldaa8e4e2010-11-15 09:13:47 +00005208 case Type::STK_Pointer:
5209 switch (DestTy->getScalarTypeKind()) {
5210 case Type::STK_Pointer:
5211 return DestTy->isObjCObjectPointerType() ?
John McCallf3ea8cf2010-11-14 08:17:51 +00005212 CK_AnyPointerToObjCPointerCast :
5213 CK_BitCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005214 case Type::STK_Bool:
5215 return CK_PointerToBoolean;
5216 case Type::STK_Integral:
5217 return CK_PointerToIntegral;
5218 case Type::STK_Floating:
5219 case Type::STK_FloatingComplex:
5220 case Type::STK_IntegralComplex:
5221 case Type::STK_MemberPointer:
5222 llvm_unreachable("illegal cast from pointer");
5223 }
5224 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005225
John McCalldaa8e4e2010-11-15 09:13:47 +00005226 case Type::STK_Bool: // casting from bool is like casting from an integer
5227 case Type::STK_Integral:
5228 switch (DestTy->getScalarTypeKind()) {
5229 case Type::STK_Pointer:
John Wiegley429bb272011-04-08 18:41:53 +00005230 if (Src.get()->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00005231 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00005232 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005233 case Type::STK_Bool:
5234 return CK_IntegralToBoolean;
5235 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00005236 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005237 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00005238 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00005239 case Type::STK_IntegralComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005240 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5241 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00005242 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005243 case Type::STK_FloatingComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005244 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5245 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00005246 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005247 case Type::STK_MemberPointer:
5248 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005249 }
5250 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005251
John McCalldaa8e4e2010-11-15 09:13:47 +00005252 case Type::STK_Floating:
5253 switch (DestTy->getScalarTypeKind()) {
5254 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00005255 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005256 case Type::STK_Bool:
5257 return CK_FloatingToBoolean;
5258 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00005259 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00005260 case Type::STK_FloatingComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005261 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5262 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00005263 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005264 case Type::STK_IntegralComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005265 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5266 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00005267 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005268 case Type::STK_Pointer:
5269 llvm_unreachable("valid float->pointer cast?");
5270 case Type::STK_MemberPointer:
5271 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005272 }
5273 break;
5274
John McCalldaa8e4e2010-11-15 09:13:47 +00005275 case Type::STK_FloatingComplex:
5276 switch (DestTy->getScalarTypeKind()) {
5277 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005278 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005279 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005280 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00005281 case Type::STK_Floating: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00005282 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00005283 if (S.Context.hasSameType(ET, DestTy))
5284 return CK_FloatingComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00005285 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00005286 return CK_FloatingCast;
5287 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005288 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00005289 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00005290 case Type::STK_Integral:
John Wiegley429bb272011-04-08 18:41:53 +00005291 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5292 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00005293 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00005294 case Type::STK_Pointer:
5295 llvm_unreachable("valid complex float->pointer cast?");
5296 case Type::STK_MemberPointer:
5297 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005298 }
5299 break;
5300
John McCalldaa8e4e2010-11-15 09:13:47 +00005301 case Type::STK_IntegralComplex:
5302 switch (DestTy->getScalarTypeKind()) {
5303 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005304 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005305 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005306 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00005307 case Type::STK_Integral: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00005308 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00005309 if (S.Context.hasSameType(ET, DestTy))
5310 return CK_IntegralComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00005311 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00005312 return CK_IntegralCast;
5313 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005314 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00005315 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00005316 case Type::STK_Floating:
John Wiegley429bb272011-04-08 18:41:53 +00005317 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5318 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00005319 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00005320 case Type::STK_Pointer:
5321 llvm_unreachable("valid complex int->pointer cast?");
5322 case Type::STK_MemberPointer:
5323 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005324 }
5325 break;
Anders Carlsson82debc72009-10-18 18:12:03 +00005326 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005327
John McCallf3ea8cf2010-11-14 08:17:51 +00005328 llvm_unreachable("Unhandled scalar cast");
5329 return CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00005330}
5331
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005332/// CheckCastTypes - Check type constraints for casting between types.
John Wiegley429bb272011-04-08 18:41:53 +00005333ExprResult Sema::CheckCastTypes(SourceRange TyR, QualType castType,
5334 Expr *castExpr, CastKind& Kind, ExprValueKind &VK,
5335 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall1de4d4e2011-04-07 08:22:57 +00005336 if (castExpr->getType() == Context.UnknownAnyTy)
5337 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
5338
Sebastian Redl9cc11e72009-07-25 15:41:38 +00005339 if (getLangOptions().CPlusPlus)
Douglas Gregor40749ee2010-11-03 00:35:38 +00005340 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
5341 castExpr->getLocEnd()),
John McCallf89e55a2010-11-18 06:31:45 +00005342 castType, VK, castExpr, Kind, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005343 FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00005344
John McCallfb8721c2011-04-10 19:13:55 +00005345 assert(!castExpr->getType()->isPlaceholderType());
5346
John McCallf89e55a2010-11-18 06:31:45 +00005347 // We only support r-value casts in C.
5348 VK = VK_RValue;
5349
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005350 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
5351 // type needs to be scalar.
5352 if (castType->isVoidType()) {
John McCallf6a16482010-12-04 03:47:34 +00005353 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley429bb272011-04-08 18:41:53 +00005354 ExprResult castExprRes = IgnoredValueConversions(castExpr);
5355 if (castExprRes.isInvalid())
5356 return ExprError();
5357 castExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00005358
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005359 // Cast to void allows any expr type.
John McCall2de56d12010-08-25 11:45:40 +00005360 Kind = CK_ToVoid;
John Wiegley429bb272011-04-08 18:41:53 +00005361 return Owned(castExpr);
Anders Carlssonebeaf202009-10-16 02:35:04 +00005362 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005363
John Wiegley429bb272011-04-08 18:41:53 +00005364 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
5365 if (castExprRes.isInvalid())
5366 return ExprError();
5367 castExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00005368
Eli Friedman8d438082010-07-17 20:43:49 +00005369 if (RequireCompleteType(TyR.getBegin(), castType,
5370 diag::err_typecheck_cast_to_incomplete))
John Wiegley429bb272011-04-08 18:41:53 +00005371 return ExprError();
Eli Friedman8d438082010-07-17 20:43:49 +00005372
Anders Carlssonebeaf202009-10-16 02:35:04 +00005373 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00005374 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005375 (castType->isStructureType() || castType->isUnionType())) {
5376 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005377 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005378 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
5379 << castType << castExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005380 Kind = CK_NoOp;
John Wiegley429bb272011-04-08 18:41:53 +00005381 return Owned(castExpr);
Anders Carlssonc3516322009-10-16 02:48:28 +00005382 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005383
Anders Carlssonc3516322009-10-16 02:48:28 +00005384 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005385 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00005386 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005387 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005388 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005389 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005390 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara8c4bfe52010-10-07 21:20:44 +00005391 castExpr->getType()) &&
5392 !Field->isUnnamedBitfield()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005393 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
5394 << castExpr->getSourceRange();
5395 break;
5396 }
5397 }
John Wiegley429bb272011-04-08 18:41:53 +00005398 if (Field == FieldEnd) {
5399 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005400 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005401 return ExprError();
5402 }
John McCall2de56d12010-08-25 11:45:40 +00005403 Kind = CK_ToUnion;
John Wiegley429bb272011-04-08 18:41:53 +00005404 return Owned(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005405 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005406
Anders Carlssonc3516322009-10-16 02:48:28 +00005407 // Reject any other conversions to non-scalar types.
John Wiegley429bb272011-04-08 18:41:53 +00005408 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlssonc3516322009-10-16 02:48:28 +00005409 << castType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005410 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00005411 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005412
John McCallf3ea8cf2010-11-14 08:17:51 +00005413 // The type we're casting to is known to be a scalar or vector.
5414
5415 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005416 if (!castExpr->getType()->isScalarType() &&
Anders Carlssonc3516322009-10-16 02:48:28 +00005417 !castExpr->getType()->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005418 Diag(castExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005419 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00005420 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005421 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00005422 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005423
5424 if (castType->isExtVectorType())
Anders Carlsson16a89042009-10-16 05:23:41 +00005425 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005426
Anton Yartsevd06fea82011-03-27 09:32:40 +00005427 if (castType->isVectorType()) {
5428 if (castType->getAs<VectorType>()->getVectorKind() ==
5429 VectorType::AltiVecVector &&
5430 (castExpr->getType()->isIntegerType() ||
5431 castExpr->getType()->isFloatingType())) {
5432 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00005433 return Owned(castExpr);
5434 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
5435 return ExprError();
Anton Yartsevd06fea82011-03-27 09:32:40 +00005436 } else
John Wiegley429bb272011-04-08 18:41:53 +00005437 return Owned(castExpr);
Anton Yartsevd06fea82011-03-27 09:32:40 +00005438 }
John Wiegley429bb272011-04-08 18:41:53 +00005439 if (castExpr->getType()->isVectorType()) {
5440 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
5441 return ExprError();
5442 else
5443 return Owned(castExpr);
5444 }
Anders Carlssonc3516322009-10-16 02:48:28 +00005445
John McCallf3ea8cf2010-11-14 08:17:51 +00005446 // The source and target types are both scalars, i.e.
5447 // - arithmetic types (fundamental, enum, and complex)
5448 // - all kinds of pointers
5449 // Note that member pointers were filtered out with C++, above.
5450
John Wiegley429bb272011-04-08 18:41:53 +00005451 if (isa<ObjCSelectorExpr>(castExpr)) {
5452 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
5453 return ExprError();
5454 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005455
John McCallf3ea8cf2010-11-14 08:17:51 +00005456 // If either type is a pointer, the other type has to be either an
5457 // integer or a pointer.
Anders Carlssonc3516322009-10-16 02:48:28 +00005458 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00005459 QualType castExprType = castExpr->getType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00005460 if (!castExprType->isIntegralType(Context) &&
John Wiegley429bb272011-04-08 18:41:53 +00005461 castExprType->isArithmeticType()) {
5462 Diag(castExpr->getLocStart(),
5463 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedman41826bb2009-05-01 02:23:58 +00005464 << castExprType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005465 return ExprError();
5466 }
Eli Friedman41826bb2009-05-01 02:23:58 +00005467 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005468 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
5469 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedman41826bb2009-05-01 02:23:58 +00005470 << castType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005471 return ExprError();
5472 }
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005473 }
Anders Carlsson82debc72009-10-18 18:12:03 +00005474
John Wiegley429bb272011-04-08 18:41:53 +00005475 castExprRes = Owned(castExpr);
5476 Kind = PrepareScalarCast(*this, castExprRes, castType);
5477 if (castExprRes.isInvalid())
5478 return ExprError();
5479 castExpr = castExprRes.take();
John McCallb7f4ffe2010-08-12 21:44:57 +00005480
John McCallf3ea8cf2010-11-14 08:17:51 +00005481 if (Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +00005482 CheckCastAlign(castExpr, castType, TyR);
5483
John Wiegley429bb272011-04-08 18:41:53 +00005484 return Owned(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005485}
5486
Anders Carlssonc3516322009-10-16 02:48:28 +00005487bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00005488 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00005489 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005490
Anders Carlssona64db8f2007-11-27 05:51:55 +00005491 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00005492 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00005493 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00005494 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00005495 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005496 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00005497 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00005498 } else
5499 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005500 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00005501 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005502
John McCall2de56d12010-08-25 11:45:40 +00005503 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00005504 return false;
5505}
5506
John Wiegley429bb272011-04-08 18:41:53 +00005507ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5508 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00005509 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005510
Anders Carlsson16a89042009-10-16 05:23:41 +00005511 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005512
Nate Begeman9b10da62009-06-27 22:05:55 +00005513 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5514 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00005515 if (SrcTy->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005516 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
5517 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00005518 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00005519 return ExprError();
5520 }
John McCall2de56d12010-08-25 11:45:40 +00005521 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00005522 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00005523 }
5524
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005525 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00005526 // conversion will take place first from scalar to elt type, and then
5527 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005528 if (SrcTy->isPointerType())
5529 return Diag(R.getBegin(),
5530 diag::err_invalid_conversion_between_vector_and_scalar)
5531 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00005532
5533 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00005534 ExprResult CastExprRes = Owned(CastExpr);
5535 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
5536 if (CastExprRes.isInvalid())
5537 return ExprError();
5538 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005539
John McCall2de56d12010-08-25 11:45:40 +00005540 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00005541 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00005542}
5543
John McCall60d7b3a2010-08-24 06:29:42 +00005544ExprResult
John McCallb3d87482010-08-24 05:47:05 +00005545Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005546 SourceLocation RParenLoc, Expr *castExpr) {
5547 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005548 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00005549
John McCall9d125032010-01-15 18:39:57 +00005550 TypeSourceInfo *castTInfo;
5551 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5552 if (!castTInfo)
John McCall42f56b52010-01-18 19:35:47 +00005553 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump1eb44332009-09-09 15:08:12 +00005554
Nate Begeman2ef13e52009-08-10 23:49:36 +00005555 // If the Expr being casted is a ParenListExpr, handle it specially.
5556 if (isa<ParenListExpr>(castExpr))
John McCall9ae2f072010-08-23 23:25:46 +00005557 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCall42f56b52010-01-18 19:35:47 +00005558 castTInfo);
John McCallb042fdf2010-01-15 18:56:44 +00005559
John McCall9ae2f072010-08-23 23:25:46 +00005560 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallb042fdf2010-01-15 18:56:44 +00005561}
5562
John McCall60d7b3a2010-08-24 06:29:42 +00005563ExprResult
John McCallb042fdf2010-01-15 18:56:44 +00005564Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005565 SourceLocation RParenLoc, Expr *castExpr) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005566 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +00005567 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +00005568 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +00005569 ExprResult CastResult =
5570 CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
5571 Kind, VK, BasePath);
5572 if (CastResult.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005573 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00005574 castExpr = CastResult.take();
Anders Carlsson0aebc812009-09-09 21:33:21 +00005575
John McCallf871d0c2010-08-07 06:22:56 +00005576 return Owned(CStyleCastExpr::Create(Context,
John Wiegley429bb272011-04-08 18:41:53 +00005577 Ty->getType().getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +00005578 VK, Kind, castExpr, &BasePath, Ty,
John McCallf871d0c2010-08-07 06:22:56 +00005579 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00005580}
5581
Nate Begeman2ef13e52009-08-10 23:49:36 +00005582/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5583/// of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00005584ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005585Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005586 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5587 if (!E)
5588 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00005589
John McCall60d7b3a2010-08-24 06:29:42 +00005590 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00005591
Nate Begeman2ef13e52009-08-10 23:49:36 +00005592 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00005593 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5594 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00005595
John McCall9ae2f072010-08-23 23:25:46 +00005596 if (Result.isInvalid()) return ExprError();
5597
5598 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00005599}
5600
John McCall60d7b3a2010-08-24 06:29:42 +00005601ExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00005602Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00005603 SourceLocation RParenLoc, Expr *Op,
John McCall42f56b52010-01-18 19:35:47 +00005604 TypeSourceInfo *TInfo) {
John McCall9ae2f072010-08-23 23:25:46 +00005605 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCall42f56b52010-01-18 19:35:47 +00005606 QualType Ty = TInfo->getType();
Anton Yartsevd06fea82011-03-27 09:32:40 +00005607 bool isVectorLiteral = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005608
Anton Yartsevd06fea82011-03-27 09:32:40 +00005609 // Check for an altivec or OpenCL literal,
John Thompson8bb59a82010-06-30 22:55:51 +00005610 // i.e. all the elements are integer constants.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005611 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5612 if (PE->getNumExprs() == 0) {
5613 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5614 return ExprError();
5615 }
John Thompson8bb59a82010-06-30 22:55:51 +00005616 if (PE->getNumExprs() == 1) {
5617 if (!PE->getExpr(0)->getType()->isVectorType())
Anton Yartsevd06fea82011-03-27 09:32:40 +00005618 isVectorLiteral = true;
John Thompson8bb59a82010-06-30 22:55:51 +00005619 }
5620 else
Anton Yartsevd06fea82011-03-27 09:32:40 +00005621 isVectorLiteral = true;
John Thompson8bb59a82010-06-30 22:55:51 +00005622 }
Nate Begeman2ef13e52009-08-10 23:49:36 +00005623
Anton Yartsevd06fea82011-03-27 09:32:40 +00005624 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
John Thompson8bb59a82010-06-30 22:55:51 +00005625 // then handle it as such.
Anton Yartsevd06fea82011-03-27 09:32:40 +00005626 if (isVectorLiteral) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005627 llvm::SmallVector<Expr *, 8> initExprs;
Anton Yartsevd06fea82011-03-27 09:32:40 +00005628 // '(...)' form of vector initialization in AltiVec: the number of
5629 // initializers must be one or must match the size of the vector.
5630 // If a single value is specified in the initializer then it will be
5631 // replicated to all the components of the vector
5632 if (Ty->getAs<VectorType>()->getVectorKind() ==
5633 VectorType::AltiVecVector) {
5634 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5635 // The number of initializers must be one or must match the size of the
5636 // vector. If a single value is specified in the initializer then it will
5637 // be replicated to all the components of the vector
5638 if (PE->getNumExprs() == 1) {
5639 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00005640 ExprResult Literal = Owned(PE->getExpr(0));
5641 Literal = ImpCastExprToType(Literal.take(), ElemTy,
5642 PrepareScalarCast(*this, Literal, ElemTy));
5643 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
Anton Yartsevd06fea82011-03-27 09:32:40 +00005644 }
5645 else if (PE->getNumExprs() < numElems) {
5646 Diag(PE->getExprLoc(),
5647 diag::err_incorrect_number_of_vector_initializers);
5648 return ExprError();
5649 }
5650 else
5651 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5652 initExprs.push_back(PE->getExpr(i));
5653 }
5654 else
5655 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5656 initExprs.push_back(PE->getExpr(i));
Nate Begeman2ef13e52009-08-10 23:49:36 +00005657
5658 // FIXME: This means that pretty-printing the final AST will produce curly
5659 // braces instead of the original commas.
Ted Kremenek709210f2010-04-13 23:39:13 +00005660 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5661 &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00005662 initExprs.size(), RParenLoc);
5663 E->setType(Ty);
John McCall9ae2f072010-08-23 23:25:46 +00005664 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman2ef13e52009-08-10 23:49:36 +00005665 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00005666 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00005667 // sequence of BinOp comma operators.
John McCall60d7b3a2010-08-24 06:29:42 +00005668 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCall9ae2f072010-08-23 23:25:46 +00005669 if (Result.isInvalid()) return ExprError();
5670 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman2ef13e52009-08-10 23:49:36 +00005671 }
5672}
5673
John McCall60d7b3a2010-08-24 06:29:42 +00005674ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00005675 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00005676 MultiExprArg Val,
John McCallb3d87482010-08-24 05:47:05 +00005677 ParsedType TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005678 unsigned nexprs = Val.size();
5679 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00005680 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5681 Expr *expr;
5682 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5683 expr = new (Context) ParenExpr(L, R, exprs[0]);
5684 else
5685 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00005686 return Owned(expr);
5687}
5688
Chandler Carruth82214a82011-02-18 23:54:50 +00005689/// \brief Emit a specialized diagnostic when one expression is a null pointer
5690/// constant and the other is not a pointer.
5691bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5692 SourceLocation QuestionLoc) {
5693 Expr *NullExpr = LHS;
5694 Expr *NonPointerExpr = RHS;
5695 Expr::NullPointerConstantKind NullKind =
5696 NullExpr->isNullPointerConstant(Context,
5697 Expr::NPC_ValueDependentIsNotNull);
5698
5699 if (NullKind == Expr::NPCK_NotNull) {
5700 NullExpr = RHS;
5701 NonPointerExpr = LHS;
5702 NullKind =
5703 NullExpr->isNullPointerConstant(Context,
5704 Expr::NPC_ValueDependentIsNotNull);
5705 }
5706
5707 if (NullKind == Expr::NPCK_NotNull)
5708 return false;
5709
5710 if (NullKind == Expr::NPCK_ZeroInteger) {
5711 // In this case, check to make sure that we got here from a "NULL"
5712 // string in the source code.
5713 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00005714 SourceLocation loc = NullExpr->getExprLoc();
5715 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00005716 return false;
5717 }
5718
5719 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5720 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5721 << NonPointerExpr->getType() << DiagType
5722 << NonPointerExpr->getSourceRange();
5723 return true;
5724}
5725
Sebastian Redl28507842009-02-26 14:39:58 +00005726/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5727/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00005728/// C99 6.5.15
John Wiegley429bb272011-04-08 18:41:53 +00005729QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005730 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00005731 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00005732
John McCallfb8721c2011-04-10 19:13:55 +00005733 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00005734 if (!lhsResult.isUsable()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00005735 LHS = move(lhsResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00005736
John McCallfb8721c2011-04-10 19:13:55 +00005737 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00005738 if (!rhsResult.isUsable()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00005739 RHS = move(rhsResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00005740
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005741 // C++ is sufficiently different to merit its own checker.
5742 if (getLangOptions().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00005743 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00005744
5745 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005746 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005747
John Wiegley429bb272011-04-08 18:41:53 +00005748 Cond = UsualUnaryConversions(Cond.take());
5749 if (Cond.isInvalid())
5750 return QualType();
5751 LHS = UsualUnaryConversions(LHS.take());
5752 if (LHS.isInvalid())
5753 return QualType();
5754 RHS = UsualUnaryConversions(RHS.take());
5755 if (RHS.isInvalid())
5756 return QualType();
5757
5758 QualType CondTy = Cond.get()->getType();
5759 QualType LHSTy = LHS.get()->getType();
5760 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005761
Reid Spencer5f016e22007-07-11 17:01:13 +00005762 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005763 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begeman6155d732010-09-20 22:41:17 +00005764 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5765 // Throw an error if its not either.
5766 if (getLangOptions().OpenCL) {
5767 if (!CondTy->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005768 Diag(Cond.get()->getLocStart(),
Nate Begeman6155d732010-09-20 22:41:17 +00005769 diag::err_typecheck_cond_expect_scalar_or_vector)
5770 << CondTy;
5771 return QualType();
5772 }
5773 }
5774 else {
John Wiegley429bb272011-04-08 18:41:53 +00005775 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00005776 << CondTy;
5777 return QualType();
5778 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005779 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005780
Chris Lattner70d67a92008-01-06 22:42:25 +00005781 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005782 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5783 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00005784
Nate Begeman6155d732010-09-20 22:41:17 +00005785 // OpenCL: If the condition is a vector, and both operands are scalar,
5786 // attempt to implicity convert them to the vector type to act like the
5787 // built in select.
5788 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5789 // Both operands should be of scalar type.
5790 if (!LHSTy->isScalarType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005791 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00005792 << CondTy;
5793 return QualType();
5794 }
5795 if (!RHSTy->isScalarType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005796 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00005797 << CondTy;
5798 return QualType();
5799 }
5800 // Implicity convert these scalars to the type of the condition.
John Wiegley429bb272011-04-08 18:41:53 +00005801 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5802 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begeman6155d732010-09-20 22:41:17 +00005803 }
5804
Chris Lattner70d67a92008-01-06 22:42:25 +00005805 // If both operands have arithmetic type, do the usual arithmetic conversions
5806 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005807 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5808 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00005809 if (LHS.isInvalid() || RHS.isInvalid())
5810 return QualType();
5811 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00005812 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005813
Chris Lattner70d67a92008-01-06 22:42:25 +00005814 // If both operands are the same structure or union type, the result is that
5815 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005816 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5817 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00005818 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005819 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00005820 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005821 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005822 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00005823 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005824
Chris Lattner70d67a92008-01-06 22:42:25 +00005825 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00005826 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005827 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5828 if (!LHSTy->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +00005829 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5830 << RHS.get()->getSourceRange();
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005831 if (!RHSTy->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +00005832 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5833 << LHS.get()->getSourceRange();
5834 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
5835 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00005836 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00005837 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00005838 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5839 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005840 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
John Wiegley429bb272011-04-08 18:41:53 +00005841 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005842 // promote the null to a pointer.
John Wiegley429bb272011-04-08 18:41:53 +00005843 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005844 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00005845 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005846 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
John Wiegley429bb272011-04-08 18:41:53 +00005847 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5848 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005849 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00005850 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005851
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005852 // All objective-c pointer type analysis is done here.
5853 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5854 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005855 if (LHS.isInvalid() || RHS.isInvalid())
5856 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005857 if (!compositeType.isNull())
5858 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005859
5860
Steve Naroff7154a772009-07-01 14:36:47 +00005861 // Handle block pointer types.
5862 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5863 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5864 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5865 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00005866 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5867 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005868 return destType;
5869 }
5870 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00005871 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00005872 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00005873 }
Steve Naroff7154a772009-07-01 14:36:47 +00005874 // We have 2 block pointer types.
5875 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5876 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005877 return LHSTy;
5878 }
Steve Naroff7154a772009-07-01 14:36:47 +00005879 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00005880 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5881 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005882
Steve Naroff7154a772009-07-01 14:36:47 +00005883 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5884 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00005885 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00005886 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00005887 // In this situation, we assume void* type. No especially good
5888 // reason, but this is what gcc does, and we do have to pick
5889 // to get a consistent AST.
5890 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00005891 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5892 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00005893 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005894 }
Steve Naroff7154a772009-07-01 14:36:47 +00005895 // The block pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00005896 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
5897 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00005898 return LHSTy;
5899 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005900
Steve Naroff7154a772009-07-01 14:36:47 +00005901 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5902 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5903 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00005904 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5905 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00005906
5907 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5908 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5909 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00005910 QualType destPointee
5911 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00005912 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005913 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005914 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005915 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005916 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005917 return destType;
5918 }
5919 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00005920 QualType destPointee
5921 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00005922 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005923 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005924 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005925 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005926 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005927 return destType;
5928 }
5929
5930 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5931 // Two identical pointer types are always compatible.
5932 return LHSTy;
5933 }
5934 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5935 rhptee.getUnqualifiedType())) {
5936 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00005937 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00005938 // In this situation, we assume void* type. No especially good
5939 // reason, but this is what gcc does, and we do have to pick
5940 // to get a consistent AST.
5941 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00005942 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5943 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005944 return incompatTy;
5945 }
5946 // The pointer types are compatible.
5947 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5948 // differently qualified versions of compatible types, the result type is
5949 // a pointer to an appropriately qualified version of the *composite*
5950 // type.
5951 // FIXME: Need to calculate the composite type.
5952 // FIXME: Need to add qualifiers
John Wiegley429bb272011-04-08 18:41:53 +00005953 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
5954 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005955 return LHSTy;
5956 }
Mike Stump1eb44332009-09-09 15:08:12 +00005957
John McCall404cd162010-11-13 01:35:44 +00005958 // GCC compatibility: soften pointer/integer mismatch. Note that
5959 // null pointers have been filtered out by this point.
Steve Naroff7154a772009-07-01 14:36:47 +00005960 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5961 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley429bb272011-04-08 18:41:53 +00005962 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5963 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00005964 return RHSTy;
5965 }
5966 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5967 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley429bb272011-04-08 18:41:53 +00005968 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5969 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00005970 return LHSTy;
5971 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00005972
Chandler Carruth82214a82011-02-18 23:54:50 +00005973 // Emit a better diagnostic if one of the expressions is a null pointer
5974 // constant and the other is not a pointer type. In this case, the user most
5975 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00005976 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00005977 return QualType();
5978
Chris Lattner70d67a92008-01-06 22:42:25 +00005979 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005980 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00005981 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005982 return QualType();
5983}
5984
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005985/// FindCompositeObjCPointerType - Helper method to find composite type of
5986/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00005987QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005988 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00005989 QualType LHSTy = LHS.get()->getType();
5990 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005991
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005992 // Handle things like Class and struct objc_class*. Here we case the result
5993 // to the pseudo-builtin, because that will be implicitly cast back to the
5994 // redefinition type if an attempt is made to access its fields.
5995 if (LHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005996 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00005997 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005998 return LHSTy;
5999 }
6000 if (RHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00006001 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006002 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006003 return RHSTy;
6004 }
6005 // And the same for struct objc_object* / id
6006 if (LHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00006007 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006008 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006009 return LHSTy;
6010 }
6011 if (RHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00006012 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006013 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006014 return RHSTy;
6015 }
6016 // And the same for struct objc_selector* / SEL
6017 if (Context.isObjCSelType(LHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00006018 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006019 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006020 return LHSTy;
6021 }
6022 if (Context.isObjCSelType(RHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00006023 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006024 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006025 return RHSTy;
6026 }
6027 // Check constraints for Objective-C object pointers types.
6028 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006029
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006030 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6031 // Two identical object pointer types are always compatible.
6032 return LHSTy;
6033 }
6034 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
6035 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
6036 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006037
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006038 // If both operands are interfaces and either operand can be
6039 // assigned to the other, use that type as the composite
6040 // type. This allows
6041 // xxx ? (A*) a : (B*) b
6042 // where B is a subclass of A.
6043 //
6044 // Additionally, as for assignment, if either type is 'id'
6045 // allow silent coercion. Finally, if the types are
6046 // incompatible then make sure to use 'id' as the composite
6047 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006048
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006049 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6050 // It could return the composite type.
6051 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6052 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6053 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6054 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6055 } else if ((LHSTy->isObjCQualifiedIdType() ||
6056 RHSTy->isObjCQualifiedIdType()) &&
6057 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6058 // Need to handle "id<xx>" explicitly.
6059 // GCC allows qualified id and any Objective-C type to devolve to
6060 // id. Currently localizing to here until clear this should be
6061 // part of ObjCQualifiedIdTypesAreCompatible.
6062 compositeType = Context.getObjCIdType();
6063 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6064 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006065 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006066 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
6067 ;
6068 else {
6069 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6070 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00006071 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006072 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00006073 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
6074 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006075 return incompatTy;
6076 }
6077 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00006078 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
6079 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006080 return compositeType;
6081 }
6082 // Check Objective-C object pointer types and 'void *'
6083 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6084 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6085 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6086 QualType destPointee
6087 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6088 QualType destType = Context.getPointerType(destPointee);
6089 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00006090 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006091 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00006092 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006093 return destType;
6094 }
6095 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6096 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6097 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6098 QualType destPointee
6099 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6100 QualType destType = Context.getPointerType(destPointee);
6101 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00006102 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006103 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00006104 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006105 return destType;
6106 }
6107 return QualType();
6108}
6109
Steve Narofff69936d2007-09-16 03:34:24 +00006110/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00006111/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00006112ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00006113 SourceLocation ColonLoc,
6114 Expr *CondExpr, Expr *LHSExpr,
6115 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00006116 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6117 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00006118 OpaqueValueExpr *opaqueValue = 0;
6119 Expr *commonExpr = 0;
6120 if (LHSExpr == 0) {
6121 commonExpr = CondExpr;
6122
6123 // We usually want to apply unary conversions *before* saving, except
6124 // in the special case of a C++ l-value conditional.
6125 if (!(getLangOptions().CPlusPlus
6126 && !commonExpr->isTypeDependent()
6127 && commonExpr->getValueKind() == RHSExpr->getValueKind()
6128 && commonExpr->isGLValue()
6129 && commonExpr->isOrdinaryOrBitFieldObject()
6130 && RHSExpr->isOrdinaryOrBitFieldObject()
6131 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00006132 ExprResult commonRes = UsualUnaryConversions(commonExpr);
6133 if (commonRes.isInvalid())
6134 return ExprError();
6135 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00006136 }
6137
6138 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6139 commonExpr->getType(),
6140 commonExpr->getValueKind(),
6141 commonExpr->getObjectKind());
6142 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00006143 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006144
John McCallf89e55a2010-11-18 06:31:45 +00006145 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00006146 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00006147 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
6148 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00006149 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00006150 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6151 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006152 return ExprError();
6153
John McCall56ca35d2011-02-17 10:25:35 +00006154 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00006155 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
6156 LHS.take(), ColonLoc,
6157 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00006158
6159 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00006160 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
6161 RHS.take(), QuestionLoc, ColonLoc, result, VK, OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00006162}
6163
John McCalle4be87e2011-01-31 23:13:11 +00006164// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00006165// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00006166// routine is it effectively iqnores the qualifiers on the top level pointee.
6167// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6168// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00006169static Sema::AssignConvertType
6170checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6171 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6172 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006173
Reid Spencer5f016e22007-07-11 17:01:13 +00006174 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00006175 const Type *lhptee, *rhptee;
6176 Qualifiers lhq, rhq;
6177 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
6178 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006179
John McCalle4be87e2011-01-31 23:13:11 +00006180 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006181
6182 // C99 6.5.16.1p1: This following citation is common to constraints
6183 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6184 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00006185 Qualifiers lq;
6186
6187 if (!lhq.compatiblyIncludes(rhq)) {
6188 // Treat address-space mismatches as fatal. TODO: address subspaces
6189 if (lhq.getAddressSpace() != rhq.getAddressSpace())
6190 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6191
John McCall22348732011-03-26 02:56:45 +00006192 // It's okay to add or remove GC qualifiers when converting to
6193 // and from void*.
6194 else if (lhq.withoutObjCGCAttr().compatiblyIncludes(rhq.withoutObjCGCAttr())
6195 && (lhptee->isVoidType() || rhptee->isVoidType()))
6196 ; // keep old
6197
John McCall86c05f32011-02-01 00:10:29 +00006198 // For GCC compatibility, other qualifier mismatches are treated
6199 // as still compatible in C.
6200 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6201 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006202
Mike Stumpeed9cac2009-02-19 03:04:26 +00006203 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6204 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00006205 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006206 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00006207 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00006208 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006209
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006210 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00006211 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00006212 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006213 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006214
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006215 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00006216 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00006217 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006218
6219 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00006220 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00006221 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006222 }
John McCall86c05f32011-02-01 00:10:29 +00006223
Mike Stumpeed9cac2009-02-19 03:04:26 +00006224 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00006225 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00006226 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6227 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006228 // Check if the pointee types are compatible ignoring the sign.
6229 // We explicitly check for char so that we catch "char" vs
6230 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00006231 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00006232 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00006233 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00006234 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006235
Chris Lattner6a2b9262009-10-17 20:33:28 +00006236 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00006237 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00006238 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00006239 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00006240
John McCall86c05f32011-02-01 00:10:29 +00006241 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006242 // Types are compatible ignoring the sign. Qualifier incompatibility
6243 // takes priority over sign incompatibility because the sign
6244 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00006245 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006246 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00006247
John McCalle4be87e2011-01-31 23:13:11 +00006248 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006249 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006250
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006251 // If we are a multi-level pointer, it's possible that our issue is simply
6252 // one of qualification - e.g. char ** -> const char ** is not allowed. If
6253 // the eventual target type is the same and the pointers have the same
6254 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00006255 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006256 do {
John McCall86c05f32011-02-01 00:10:29 +00006257 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6258 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00006259 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006260
John McCall86c05f32011-02-01 00:10:29 +00006261 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00006262 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006263 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006264
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006265 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00006266 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006267 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00006268 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006269}
6270
John McCalle4be87e2011-01-31 23:13:11 +00006271/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00006272/// block pointer types are compatible or whether a block and normal pointer
6273/// are compatible. It is more restrict than comparing two function pointer
6274// types.
John McCalle4be87e2011-01-31 23:13:11 +00006275static Sema::AssignConvertType
6276checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
6277 QualType rhsType) {
6278 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6279 assert(rhsType.isCanonical() && "RHS not canonicalized!");
6280
Steve Naroff1c7d0672008-09-04 15:10:53 +00006281 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006282
Steve Naroff1c7d0672008-09-04 15:10:53 +00006283 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCalle4be87e2011-01-31 23:13:11 +00006284 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
6285 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006286
John McCalle4be87e2011-01-31 23:13:11 +00006287 // In C++, the types have to match exactly.
6288 if (S.getLangOptions().CPlusPlus)
6289 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006290
John McCalle4be87e2011-01-31 23:13:11 +00006291 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006292
Steve Naroff1c7d0672008-09-04 15:10:53 +00006293 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00006294 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6295 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006296
John McCalle4be87e2011-01-31 23:13:11 +00006297 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
6298 return Sema::IncompatibleBlockPointer;
6299
Steve Naroff1c7d0672008-09-04 15:10:53 +00006300 return ConvTy;
6301}
6302
John McCalle4be87e2011-01-31 23:13:11 +00006303/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006304/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00006305static Sema::AssignConvertType
6306checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6307 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
6308 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
6309
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00006310 if (lhsType->isObjCBuiltinType()) {
6311 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00006312 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
6313 !rhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00006314 return Sema::IncompatiblePointer;
6315 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00006316 }
6317 if (rhsType->isObjCBuiltinType()) {
6318 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00006319 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
6320 !lhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00006321 return Sema::IncompatiblePointer;
6322 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00006323 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006324 QualType lhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006325 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006326 QualType rhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006327 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006328
John McCalle4be87e2011-01-31 23:13:11 +00006329 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
6330 return Sema::CompatiblePointerDiscardsQualifiers;
6331
6332 if (S.Context.typesAreCompatible(lhsType, rhsType))
6333 return Sema::Compatible;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006334 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00006335 return Sema::IncompatibleObjCQualifiedId;
6336 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006337}
6338
John McCall1c23e912010-11-16 02:32:08 +00006339Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00006340Sema::CheckAssignmentConstraints(SourceLocation Loc,
6341 QualType lhsType, QualType rhsType) {
John McCall1c23e912010-11-16 02:32:08 +00006342 // Fake up an opaque expression. We don't actually care about what
6343 // cast operations are required, so if CheckAssignmentConstraints
6344 // adds casts to this they'll be wasted, but fortunately that doesn't
6345 // usually happen on valid code.
Douglas Gregorb608b982011-01-28 02:26:04 +00006346 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00006347 ExprResult rhsPtr = &rhs;
John McCall1c23e912010-11-16 02:32:08 +00006348 CastKind K = CK_Invalid;
6349
6350 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
6351}
6352
Mike Stumpeed9cac2009-02-19 03:04:26 +00006353/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6354/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00006355/// pointers. Here are some objectionable examples that GCC considers warnings:
6356///
6357/// int a, *pint;
6358/// short *pshort;
6359/// struct foo *pfoo;
6360///
6361/// pint = pshort; // warning: assignment from incompatible pointer type
6362/// a = pint; // warning: assignment makes integer from pointer without a cast
6363/// pint = a; // warning: assignment makes pointer from integer without a cast
6364/// pint = pfoo; // warning: assignment from incompatible pointer type
6365///
6366/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00006367/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00006368///
John McCalldaa8e4e2010-11-15 09:13:47 +00006369/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00006370Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00006371Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCalldaa8e4e2010-11-15 09:13:47 +00006372 CastKind &Kind) {
John Wiegley429bb272011-04-08 18:41:53 +00006373 QualType rhsType = rhs.get()->getType();
John McCall1c23e912010-11-16 02:32:08 +00006374
Chris Lattnerfc144e22008-01-04 23:18:45 +00006375 // Get canonical types. We're not formatting these types, just comparing
6376 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00006377 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
6378 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006379
John McCallb6cfa242011-01-31 22:28:28 +00006380 // Common case: no conversion required.
John McCalldaa8e4e2010-11-15 09:13:47 +00006381 if (lhsType == rhsType) {
6382 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00006383 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00006384 }
6385
Douglas Gregor9d293df2008-10-28 00:22:11 +00006386 // If the left-hand side is a reference type, then we are in a
6387 // (rare!) case where we've allowed the use of references in C,
6388 // e.g., as a parameter type in a built-in function. In this case,
6389 // just make sure that the type referenced is compatible with the
6390 // right-hand side type. The caller is responsible for adjusting
6391 // lhsType so that the resulting expression does not have reference
6392 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00006393 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006394 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
6395 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00006396 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006397 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00006398 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00006399 }
John McCallb6cfa242011-01-31 22:28:28 +00006400
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006401 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6402 // to the same ExtVector type.
6403 if (lhsType->isExtVectorType()) {
6404 if (rhsType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00006405 return Incompatible;
6406 if (rhsType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00006407 // CK_VectorSplat does T -> vector T, so first cast to the
6408 // element type.
6409 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
6410 if (elType != rhsType) {
6411 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley429bb272011-04-08 18:41:53 +00006412 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00006413 }
6414 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006415 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006416 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006417 }
Mike Stump1eb44332009-09-09 15:08:12 +00006418
John McCallb6cfa242011-01-31 22:28:28 +00006419 // Conversions to or from vector type.
Nate Begemanbe2341d2008-07-14 18:02:46 +00006420 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor255210e2010-08-06 10:14:59 +00006421 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00006422 // Allow assignments of an AltiVec vector type to an equivalent GCC
6423 // vector type and vice versa
6424 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
6425 Kind = CK_BitCast;
6426 return Compatible;
6427 }
6428
Douglas Gregor255210e2010-08-06 10:14:59 +00006429 // If we are allowing lax vector conversions, and LHS and RHS are both
6430 // vectors, the total size only needs to be the same. This is a bitcast;
6431 // no bits are changed but the result type is different.
6432 if (getLangOptions().LaxVectorConversions &&
John McCalldaa8e4e2010-11-15 09:13:47 +00006433 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00006434 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006435 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00006436 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00006437 }
6438 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006439 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006440
John McCallb6cfa242011-01-31 22:28:28 +00006441 // Arithmetic conversions.
Douglas Gregor88623ad2010-05-23 21:53:47 +00006442 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00006443 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall1c23e912010-11-16 02:32:08 +00006444 Kind = PrepareScalarCast(*this, rhs, lhsType);
Reid Spencer5f016e22007-07-11 17:01:13 +00006445 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006446 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006447
John McCallb6cfa242011-01-31 22:28:28 +00006448 // Conversions to normal pointers.
6449 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
6450 // U* -> T*
John McCalldaa8e4e2010-11-15 09:13:47 +00006451 if (isa<PointerType>(rhsType)) {
6452 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00006453 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006454 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006455
John McCallb6cfa242011-01-31 22:28:28 +00006456 // int -> T*
6457 if (rhsType->isIntegerType()) {
6458 Kind = CK_IntegralToPointer; // FIXME: null?
6459 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00006460 }
John McCallb6cfa242011-01-31 22:28:28 +00006461
6462 // C pointers are not compatible with ObjC object pointers,
6463 // with two exceptions:
6464 if (isa<ObjCObjectPointerType>(rhsType)) {
6465 // - conversions to void*
6466 if (lhsPointer->getPointeeType()->isVoidType()) {
6467 Kind = CK_AnyPointerToObjCPointerCast;
6468 return Compatible;
6469 }
6470
6471 // - conversions from 'Class' to the redefinition type
6472 if (rhsType->isObjCClassType() &&
6473 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006474 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00006475 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006476 }
Steve Naroffb4406862008-09-29 18:10:17 +00006477
John McCallb6cfa242011-01-31 22:28:28 +00006478 Kind = CK_BitCast;
6479 return IncompatiblePointer;
6480 }
6481
6482 // U^ -> void*
6483 if (rhsType->getAs<BlockPointerType>()) {
6484 if (lhsPointer->getPointeeType()->isVoidType()) {
6485 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00006486 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006487 }
Steve Naroffb4406862008-09-29 18:10:17 +00006488 }
John McCallb6cfa242011-01-31 22:28:28 +00006489
Steve Naroff1c7d0672008-09-04 15:10:53 +00006490 return Incompatible;
6491 }
6492
John McCallb6cfa242011-01-31 22:28:28 +00006493 // Conversions to block pointers.
Steve Naroff1c7d0672008-09-04 15:10:53 +00006494 if (isa<BlockPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006495 // U^ -> T^
6496 if (rhsType->isBlockPointerType()) {
6497 Kind = CK_AnyPointerToBlockPointerCast;
John McCalle4be87e2011-01-31 23:13:11 +00006498 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00006499 }
6500
6501 // int or null -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00006502 if (rhsType->isIntegerType()) {
6503 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00006504 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00006505 }
6506
John McCallb6cfa242011-01-31 22:28:28 +00006507 // id -> T^
6508 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6509 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00006510 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006511 }
Steve Naroffb4406862008-09-29 18:10:17 +00006512
John McCallb6cfa242011-01-31 22:28:28 +00006513 // void* -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00006514 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00006515 if (RHSPT->getPointeeType()->isVoidType()) {
6516 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00006517 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006518 }
John McCalldaa8e4e2010-11-15 09:13:47 +00006519
Chris Lattnerfc144e22008-01-04 23:18:45 +00006520 return Incompatible;
6521 }
6522
John McCallb6cfa242011-01-31 22:28:28 +00006523 // Conversions to Objective-C pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00006524 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006525 // A* -> B*
6526 if (rhsType->isObjCObjectPointerType()) {
6527 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00006528 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00006529 }
6530
6531 // int or null -> A*
John McCalldaa8e4e2010-11-15 09:13:47 +00006532 if (rhsType->isIntegerType()) {
6533 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00006534 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00006535 }
6536
John McCallb6cfa242011-01-31 22:28:28 +00006537 // In general, C pointers are not compatible with ObjC object pointers,
6538 // with two exceptions:
Steve Naroff14108da2009-07-10 23:34:53 +00006539 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006540 // - conversions from 'void*'
6541 if (rhsType->isVoidPointerType()) {
6542 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00006543 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006544 }
6545
6546 // - conversions to 'Class' from its redefinition type
6547 if (lhsType->isObjCClassType() &&
6548 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6549 Kind = CK_BitCast;
6550 return Compatible;
6551 }
6552
6553 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00006554 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00006555 }
John McCallb6cfa242011-01-31 22:28:28 +00006556
6557 // T^ -> A*
6558 if (rhsType->isBlockPointerType()) {
6559 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00006560 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006561 }
6562
Steve Naroff14108da2009-07-10 23:34:53 +00006563 return Incompatible;
6564 }
John McCallb6cfa242011-01-31 22:28:28 +00006565
6566 // Conversions from pointers that are not covered by the above.
Chris Lattner78eca282008-04-07 06:49:41 +00006567 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006568 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00006569 if (lhsType == Context.BoolTy) {
6570 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006571 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006572 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006573
John McCallb6cfa242011-01-31 22:28:28 +00006574 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00006575 if (lhsType->isIntegerType()) {
6576 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006577 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00006578 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006579
Chris Lattnerfc144e22008-01-04 23:18:45 +00006580 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00006581 }
John McCallb6cfa242011-01-31 22:28:28 +00006582
6583 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff14108da2009-07-10 23:34:53 +00006584 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006585 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00006586 if (lhsType == Context.BoolTy) {
6587 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00006588 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006589 }
Steve Naroff14108da2009-07-10 23:34:53 +00006590
John McCallb6cfa242011-01-31 22:28:28 +00006591 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00006592 if (lhsType->isIntegerType()) {
6593 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00006594 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00006595 }
6596
Steve Naroff14108da2009-07-10 23:34:53 +00006597 return Incompatible;
6598 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006599
John McCallb6cfa242011-01-31 22:28:28 +00006600 // struct A -> struct B
Chris Lattnerfc144e22008-01-04 23:18:45 +00006601 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006602 if (Context.typesAreCompatible(lhsType, rhsType)) {
6603 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00006604 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006605 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006606 }
John McCallb6cfa242011-01-31 22:28:28 +00006607
Reid Spencer5f016e22007-07-11 17:01:13 +00006608 return Incompatible;
6609}
6610
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006611/// \brief Constructs a transparent union from an expression that is
6612/// used to initialize the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00006613static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006614 QualType UnionType, FieldDecl *Field) {
6615 // Build an initializer list that designates the appropriate member
6616 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00006617 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00006618 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00006619 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006620 SourceLocation());
6621 Initializer->setType(UnionType);
6622 Initializer->setInitializedFieldInUnion(Field);
6623
6624 // Build a compound literal constructing a value of the transparent
6625 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00006626 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00006627 EResult = S.Owned(
6628 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6629 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006630}
6631
6632Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00006633Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &rExpr) {
6634 QualType FromType = rExpr.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006635
Mike Stump1eb44332009-09-09 15:08:12 +00006636 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006637 // transparent_union GCC extension.
6638 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006639 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006640 return Incompatible;
6641
6642 // The field to initialize within the transparent union.
6643 RecordDecl *UD = UT->getDecl();
6644 FieldDecl *InitField = 0;
6645 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006646 for (RecordDecl::field_iterator it = UD->field_begin(),
6647 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006648 it != itend; ++it) {
6649 if (it->getType()->isPointerType()) {
6650 // If the transparent union contains a pointer type, we allow:
6651 // 1) void pointer
6652 // 2) null pointer constant
6653 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00006654 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006655 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006656 InitField = *it;
6657 break;
6658 }
Mike Stump1eb44332009-09-09 15:08:12 +00006659
John Wiegley429bb272011-04-08 18:41:53 +00006660 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006661 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00006662 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_NullToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006663 InitField = *it;
6664 break;
6665 }
6666 }
6667
John McCalldaa8e4e2010-11-15 09:13:47 +00006668 CastKind Kind = CK_Invalid;
John Wiegley429bb272011-04-08 18:41:53 +00006669 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006670 == Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +00006671 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006672 InitField = *it;
6673 break;
6674 }
6675 }
6676
6677 if (!InitField)
6678 return Incompatible;
6679
John Wiegley429bb272011-04-08 18:41:53 +00006680 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006681 return Compatible;
6682}
6683
Chris Lattner5cf216b2008-01-04 18:04:52 +00006684Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00006685Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00006686 if (getLangOptions().CPlusPlus) {
6687 if (!lhsType->isRecordType()) {
6688 // C++ 5.17p3: If the left operand is not of class type, the
6689 // expression is implicitly converted (C++ 4) to the
6690 // cv-unqualified type of the left operand.
John Wiegley429bb272011-04-08 18:41:53 +00006691 ExprResult Res = PerformImplicitConversion(rExpr.get(),
6692 lhsType.getUnqualifiedType(),
6693 AA_Assigning);
6694 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00006695 return Incompatible;
John Wiegley429bb272011-04-08 18:41:53 +00006696 rExpr = move(Res);
Chris Lattner2c4463f2009-04-12 09:02:39 +00006697 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00006698 }
6699
6700 // FIXME: Currently, we fall through and treat C++ classes like C
6701 // structures.
John McCallf6a16482010-12-04 03:47:34 +00006702 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00006703
Steve Naroff529a4ad2007-11-27 17:58:44 +00006704 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6705 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00006706 if ((lhsType->isPointerType() ||
6707 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00006708 lhsType->isBlockPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00006709 && rExpr.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006710 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00006711 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00006712 return Compatible;
6713 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006714
Chris Lattner943140e2007-10-16 02:55:40 +00006715 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00006716 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00006717 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00006718 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00006719 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00006720 // Suppress this for references: C++ 8.5.3p5.
John Wiegley429bb272011-04-08 18:41:53 +00006721 if (!lhsType->isReferenceType()) {
6722 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
6723 if (rExpr.isInvalid())
6724 return Incompatible;
6725 }
Steve Narofff1120de2007-08-24 22:33:52 +00006726
John McCalldaa8e4e2010-11-15 09:13:47 +00006727 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006728 Sema::AssignConvertType result =
John McCall1c23e912010-11-16 02:32:08 +00006729 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006730
Steve Narofff1120de2007-08-24 22:33:52 +00006731 // C99 6.5.16.1p2: The value of the right operand is converted to the
6732 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00006733 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6734 // so that we can use references in built-in functions even in C.
6735 // The getNonReferenceType() call makes sure that the resulting expression
6736 // does not have reference type.
John Wiegley429bb272011-04-08 18:41:53 +00006737 if (result != Incompatible && rExpr.get()->getType() != lhsType)
6738 rExpr = ImpCastExprToType(rExpr.take(), lhsType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00006739 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00006740}
6741
John Wiegley429bb272011-04-08 18:41:53 +00006742QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006743 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley429bb272011-04-08 18:41:53 +00006744 << lex.get()->getType() << rex.get()->getType()
6745 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00006746 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006747}
6748
John Wiegley429bb272011-04-08 18:41:53 +00006749QualType Sema::CheckVectorOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00006750 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006751 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00006752 QualType lhsType =
John Wiegley429bb272011-04-08 18:41:53 +00006753 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattnerb77792e2008-07-26 22:17:49 +00006754 QualType rhsType =
John Wiegley429bb272011-04-08 18:41:53 +00006755 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006756
Nate Begemanbe2341d2008-07-14 18:02:46 +00006757 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006758 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00006759 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00006760
Nate Begemanbe2341d2008-07-14 18:02:46 +00006761 // Handle the case of a vector & extvector type of the same size and element
6762 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006763 if (getLangOptions().LaxVectorConversions) {
John McCall183700f2009-09-21 23:43:11 +00006764 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth629f9e42010-08-30 07:36:24 +00006765 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00006766 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006767 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregor26bcf672010-05-19 03:21:00 +00006768 if (lhsType->isExtVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006769 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006770 return lhsType;
6771 }
6772
John Wiegley429bb272011-04-08 18:41:53 +00006773 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006774 return rhsType;
Eric Christophere84f9eb2010-08-26 00:42:16 +00006775 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6776 // If we are allowing lax vector conversions, and LHS and RHS are both
6777 // vectors, the total size only needs to be the same. This is a
6778 // bitcast; no bits are changed but the result type is different.
John Wiegley429bb272011-04-08 18:41:53 +00006779 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Eric Christophere84f9eb2010-08-26 00:42:16 +00006780 return lhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006781 }
Eric Christophere84f9eb2010-08-26 00:42:16 +00006782 }
Chandler Carruth629f9e42010-08-30 07:36:24 +00006783 }
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006784 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006785
Douglas Gregor255210e2010-08-06 10:14:59 +00006786 // Handle the case of equivalent AltiVec and GCC vector types
6787 if (lhsType->isVectorType() && rhsType->isVectorType() &&
6788 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John Wiegley429bb272011-04-08 18:41:53 +00006789 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor255210e2010-08-06 10:14:59 +00006790 return rhsType;
6791 }
6792
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006793 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6794 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6795 bool swapped = false;
6796 if (rhsType->isExtVectorType()) {
6797 swapped = true;
6798 std::swap(rex, lex);
6799 std::swap(rhsType, lhsType);
6800 }
Mike Stump1eb44332009-09-09 15:08:12 +00006801
Nate Begemandde25982009-06-28 19:12:57 +00006802 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00006803 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006804 QualType EltTy = LV->getElementType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00006805 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006806 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6807 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +00006808 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006809 if (order >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +00006810 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006811 if (swapped) std::swap(rex, lex);
6812 return lhsType;
6813 }
6814 }
6815 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6816 rhsType->isRealFloatingType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006817 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6818 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +00006819 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006820 if (order >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +00006821 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006822 if (swapped) std::swap(rex, lex);
6823 return lhsType;
6824 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00006825 }
6826 }
Mike Stump1eb44332009-09-09 15:08:12 +00006827
Nate Begemandde25982009-06-28 19:12:57 +00006828 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006829 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley429bb272011-04-08 18:41:53 +00006830 << lex.get()->getType() << rex.get()->getType()
6831 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006832 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00006833}
6834
Chris Lattner7ef655a2010-01-12 21:23:57 +00006835QualType Sema::CheckMultiplyDivideOperands(
John Wiegley429bb272011-04-08 18:41:53 +00006836 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
6837 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006838 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006839
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006840 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00006841 if (lex.isInvalid() || rex.isInvalid())
6842 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006843
John Wiegley429bb272011-04-08 18:41:53 +00006844 if (!lex.get()->getType()->isArithmeticType() ||
6845 !rex.get()->getType()->isArithmeticType())
Chris Lattner7ef655a2010-01-12 21:23:57 +00006846 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006847
Chris Lattner7ef655a2010-01-12 21:23:57 +00006848 // Check for division by zero.
6849 if (isDiv &&
John Wiegley429bb272011-04-08 18:41:53 +00006850 rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6851 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
6852 << rex.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006853
Chris Lattner7ef655a2010-01-12 21:23:57 +00006854 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006855}
6856
Chris Lattner7ef655a2010-01-12 21:23:57 +00006857QualType Sema::CheckRemainderOperands(
John Wiegley429bb272011-04-08 18:41:53 +00006858 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
6859 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
6860 if (lex.get()->getType()->hasIntegerRepresentation() &&
6861 rex.get()->getType()->hasIntegerRepresentation())
Daniel Dunbar523aa602009-01-05 22:55:36 +00006862 return CheckVectorOperands(Loc, lex, rex);
6863 return InvalidOperands(Loc, lex, rex);
6864 }
Steve Naroff90045e82007-07-13 23:32:42 +00006865
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006866 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00006867 if (lex.isInvalid() || rex.isInvalid())
6868 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006869
John Wiegley429bb272011-04-08 18:41:53 +00006870 if (!lex.get()->getType()->isIntegerType() || !rex.get()->getType()->isIntegerType())
Chris Lattner7ef655a2010-01-12 21:23:57 +00006871 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006872
Chris Lattner7ef655a2010-01-12 21:23:57 +00006873 // Check for remainder by zero.
John Wiegley429bb272011-04-08 18:41:53 +00006874 if (rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6875 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
6876 << rex.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006877
Chris Lattner7ef655a2010-01-12 21:23:57 +00006878 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006879}
6880
Chris Lattner7ef655a2010-01-12 21:23:57 +00006881QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley429bb272011-04-08 18:41:53 +00006882 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
6883 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006884 QualType compType = CheckVectorOperands(Loc, lex, rex);
6885 if (CompLHSTy) *CompLHSTy = compType;
6886 return compType;
6887 }
Steve Naroff49b45262007-07-13 16:58:59 +00006888
Eli Friedmanab3a8522009-03-28 01:22:36 +00006889 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00006890 if (lex.isInvalid() || rex.isInvalid())
6891 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006892
Reid Spencer5f016e22007-07-11 17:01:13 +00006893 // handle the common case first (both operands are arithmetic).
John Wiegley429bb272011-04-08 18:41:53 +00006894 if (lex.get()->getType()->isArithmeticType() &&
6895 rex.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006896 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006897 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006898 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006899
Eli Friedmand72d16e2008-05-18 18:08:51 +00006900 // Put any potential pointer into PExp
John Wiegley429bb272011-04-08 18:41:53 +00006901 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006902 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00006903 std::swap(PExp, IExp);
6904
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006905 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006906
Eli Friedmand72d16e2008-05-18 18:08:51 +00006907 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00006908 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00006909
Chris Lattnerb5f15622009-04-24 23:50:08 +00006910 // Check for arithmetic on pointers to incomplete types.
6911 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006912 if (getLangOptions().CPlusPlus) {
6913 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley429bb272011-04-08 18:41:53 +00006914 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006915 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006916 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006917
6918 // GNU extension: arithmetic on pointer to void
6919 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley429bb272011-04-08 18:41:53 +00006920 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00006921 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006922 if (getLangOptions().CPlusPlus) {
6923 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley429bb272011-04-08 18:41:53 +00006924 << lex.get()->getType() << lex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00006925 return QualType();
6926 }
6927
6928 // GNU extension: arithmetic on pointer to function
6929 Diag(Loc, diag::ext_gnu_ptr_func_arith)
John Wiegley429bb272011-04-08 18:41:53 +00006930 << lex.get()->getType() << lex.get()->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00006931 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00006932 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00006933 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00006934 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00006935 PExp->getType()->isObjCObjectPointerType()) &&
6936 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00006937 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6938 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00006939 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00006940 return QualType();
6941 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00006942 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00006943 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00006944 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6945 << PointeeTy << PExp->getSourceRange();
6946 return QualType();
6947 }
Mike Stump1eb44332009-09-09 15:08:12 +00006948
Eli Friedmanab3a8522009-03-28 01:22:36 +00006949 if (CompLHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00006950 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman04e83572009-08-20 04:21:42 +00006951 if (LHSTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +00006952 LHSTy = lex.get()->getType();
Eli Friedman04e83572009-08-20 04:21:42 +00006953 if (LHSTy->isPromotableIntegerType())
6954 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00006955 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00006956 *CompLHSTy = LHSTy;
6957 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00006958 return PExp->getType();
6959 }
6960 }
6961
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006962 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006963}
6964
Chris Lattnereca7be62008-04-07 05:30:13 +00006965// C99 6.5.6
John Wiegley429bb272011-04-08 18:41:53 +00006966QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00006967 SourceLocation Loc, QualType* CompLHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00006968 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006969 QualType compType = CheckVectorOperands(Loc, lex, rex);
6970 if (CompLHSTy) *CompLHSTy = compType;
6971 return compType;
6972 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006973
Eli Friedmanab3a8522009-03-28 01:22:36 +00006974 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00006975 if (lex.isInvalid() || rex.isInvalid())
6976 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006977
Chris Lattner6e4ab612007-12-09 21:53:25 +00006978 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006979
Chris Lattner6e4ab612007-12-09 21:53:25 +00006980 // Handle the common case first (both operands are arithmetic).
John Wiegley429bb272011-04-08 18:41:53 +00006981 if (lex.get()->getType()->isArithmeticType() &&
6982 rex.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006983 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006984 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006985 }
Mike Stump1eb44332009-09-09 15:08:12 +00006986
Chris Lattner6e4ab612007-12-09 21:53:25 +00006987 // Either ptr - int or ptr - ptr.
John Wiegley429bb272011-04-08 18:41:53 +00006988 if (lex.get()->getType()->isAnyPointerType()) {
6989 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006990
Douglas Gregore7450f52009-03-24 19:52:54 +00006991 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00006992
Douglas Gregore7450f52009-03-24 19:52:54 +00006993 bool ComplainAboutVoid = false;
6994 Expr *ComplainAboutFunc = 0;
6995 if (lpointee->isVoidType()) {
6996 if (getLangOptions().CPlusPlus) {
6997 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley429bb272011-04-08 18:41:53 +00006998 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00006999 return QualType();
7000 }
7001
7002 // GNU C extension: arithmetic on pointer to void
7003 ComplainAboutVoid = true;
7004 } else if (lpointee->isFunctionType()) {
7005 if (getLangOptions().CPlusPlus) {
7006 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley429bb272011-04-08 18:41:53 +00007007 << lex.get()->getType() << lex.get()->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00007008 return QualType();
7009 }
Douglas Gregore7450f52009-03-24 19:52:54 +00007010
7011 // GNU C extension: arithmetic on pointer to function
John Wiegley429bb272011-04-08 18:41:53 +00007012 ComplainAboutFunc = lex.get();
Douglas Gregore7450f52009-03-24 19:52:54 +00007013 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00007014 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00007015 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley429bb272011-04-08 18:41:53 +00007016 << lex.get()->getSourceRange()
7017 << lex.get()->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00007018 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00007019
Chris Lattnerb5f15622009-04-24 23:50:08 +00007020 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00007021 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00007022 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley429bb272011-04-08 18:41:53 +00007023 << lpointee << lex.get()->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00007024 return QualType();
7025 }
Mike Stump1eb44332009-09-09 15:08:12 +00007026
Chris Lattner6e4ab612007-12-09 21:53:25 +00007027 // The result type of a pointer-int computation is the pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00007028 if (rex.get()->getType()->isIntegerType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00007029 if (ComplainAboutVoid)
7030 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley429bb272011-04-08 18:41:53 +00007031 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00007032 if (ComplainAboutFunc)
7033 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00007034 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00007035 << ComplainAboutFunc->getSourceRange();
7036
John Wiegley429bb272011-04-08 18:41:53 +00007037 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
7038 return lex.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00007039 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007040
Chris Lattner6e4ab612007-12-09 21:53:25 +00007041 // Handle pointer-pointer subtractions.
John Wiegley429bb272011-04-08 18:41:53 +00007042 if (const PointerType *RHSPTy = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00007043 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007044
Douglas Gregore7450f52009-03-24 19:52:54 +00007045 // RHS must be a completely-type object type.
7046 // Handle the GNU void* extension.
7047 if (rpointee->isVoidType()) {
7048 if (getLangOptions().CPlusPlus) {
7049 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley429bb272011-04-08 18:41:53 +00007050 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00007051 return QualType();
7052 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007053
Douglas Gregore7450f52009-03-24 19:52:54 +00007054 ComplainAboutVoid = true;
7055 } else if (rpointee->isFunctionType()) {
7056 if (getLangOptions().CPlusPlus) {
7057 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley429bb272011-04-08 18:41:53 +00007058 << rex.get()->getType() << rex.get()->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00007059 return QualType();
7060 }
Douglas Gregore7450f52009-03-24 19:52:54 +00007061
7062 // GNU extension: arithmetic on pointer to function
7063 if (!ComplainAboutFunc)
John Wiegley429bb272011-04-08 18:41:53 +00007064 ComplainAboutFunc = rex.get();
Douglas Gregore7450f52009-03-24 19:52:54 +00007065 } else if (!rpointee->isDependentType() &&
7066 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00007067 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley429bb272011-04-08 18:41:53 +00007068 << rex.get()->getSourceRange()
7069 << rex.get()->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00007070 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007071
Eli Friedman88d936b2009-05-16 13:54:38 +00007072 if (getLangOptions().CPlusPlus) {
7073 // Pointee types must be the same: C++ [expr.add]
7074 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7075 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley429bb272011-04-08 18:41:53 +00007076 << lex.get()->getType() << rex.get()->getType()
7077 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman88d936b2009-05-16 13:54:38 +00007078 return QualType();
7079 }
7080 } else {
7081 // Pointee types must be compatible C99 6.5.6p3
7082 if (!Context.typesAreCompatible(
7083 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7084 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7085 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley429bb272011-04-08 18:41:53 +00007086 << lex.get()->getType() << rex.get()->getType()
7087 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman88d936b2009-05-16 13:54:38 +00007088 return QualType();
7089 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00007090 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007091
Douglas Gregore7450f52009-03-24 19:52:54 +00007092 if (ComplainAboutVoid)
7093 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley429bb272011-04-08 18:41:53 +00007094 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00007095 if (ComplainAboutFunc)
7096 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00007097 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00007098 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00007099
John Wiegley429bb272011-04-08 18:41:53 +00007100 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00007101 return Context.getPointerDiffType();
7102 }
7103 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007104
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007105 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007106}
7107
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007108static bool isScopedEnumerationType(QualType T) {
7109 if (const EnumType *ET = dyn_cast<EnumType>(T))
7110 return ET->getDecl()->isScoped();
7111 return false;
7112}
7113
John Wiegley429bb272011-04-08 18:41:53 +00007114static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth21206d52011-02-23 23:34:11 +00007115 SourceLocation Loc, unsigned Opc,
7116 QualType LHSTy) {
7117 llvm::APSInt Right;
7118 // Check right/shifter operand
John Wiegley429bb272011-04-08 18:41:53 +00007119 if (rex.get()->isValueDependent() || !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00007120 return;
7121
7122 if (Right.isNegative()) {
John Wiegley429bb272011-04-08 18:41:53 +00007123 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00007124 S.PDiag(diag::warn_shift_negative)
John Wiegley429bb272011-04-08 18:41:53 +00007125 << rex.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00007126 return;
7127 }
7128 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley429bb272011-04-08 18:41:53 +00007129 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00007130 if (Right.uge(LeftBits)) {
John Wiegley429bb272011-04-08 18:41:53 +00007131 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00007132 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley429bb272011-04-08 18:41:53 +00007133 << rex.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00007134 return;
7135 }
7136 if (Opc != BO_Shl)
7137 return;
7138
7139 // When left shifting an ICE which is signed, we can check for overflow which
7140 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7141 // integers have defined behavior modulo one more than the maximum value
7142 // representable in the result type, so never warn for those.
7143 llvm::APSInt Left;
John Wiegley429bb272011-04-08 18:41:53 +00007144 if (lex.get()->isValueDependent() || !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth21206d52011-02-23 23:34:11 +00007145 LHSTy->hasUnsignedIntegerRepresentation())
7146 return;
7147 llvm::APInt ResultBits =
7148 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7149 if (LeftBits.uge(ResultBits))
7150 return;
7151 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7152 Result = Result.shl(Right);
7153
7154 // If we are only missing a sign bit, this is less likely to result in actual
7155 // bugs -- if the result is cast back to an unsigned type, it will have the
7156 // expected value. Thus we place this behind a different warning that can be
7157 // turned off separately if needed.
7158 if (LeftBits == ResultBits - 1) {
7159 S.Diag(Loc, diag::warn_shift_result_overrides_sign_bit)
7160 << Result.toString(10) << LHSTy
John Wiegley429bb272011-04-08 18:41:53 +00007161 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00007162 return;
7163 }
7164
7165 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7166 << Result.toString(10) << Result.getMinSignedBits() << LHSTy
John Wiegley429bb272011-04-08 18:41:53 +00007167 << Left.getBitWidth() << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00007168}
7169
Chris Lattnereca7be62008-04-07 05:30:13 +00007170// C99 6.5.7
John Wiegley429bb272011-04-08 18:41:53 +00007171QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Chandler Carruth21206d52011-02-23 23:34:11 +00007172 unsigned Opc, bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00007173 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley429bb272011-04-08 18:41:53 +00007174 if (!lex.get()->getType()->hasIntegerRepresentation() ||
7175 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007176 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007177
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007178 // C++0x: Don't allow scoped enums. FIXME: Use something better than
7179 // hasIntegerRepresentation() above instead of this.
John Wiegley429bb272011-04-08 18:41:53 +00007180 if (isScopedEnumerationType(lex.get()->getType()) ||
7181 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007182 return InvalidOperands(Loc, lex, rex);
7183 }
7184
Nate Begeman2207d792009-10-25 02:26:48 +00007185 // Vector shifts promote their scalar inputs to vector type.
John Wiegley429bb272011-04-08 18:41:53 +00007186 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Nate Begeman2207d792009-10-25 02:26:48 +00007187 return CheckVectorOperands(Loc, lex, rex);
7188
Chris Lattnerca5eede2007-12-12 05:47:28 +00007189 // Shifts don't perform usual arithmetic conversions, they just do integer
7190 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00007191
John McCall1bc80af2010-12-16 19:28:59 +00007192 // For the LHS, do usual unary conversions, but then reset them away
7193 // if this is a compound assignment.
John Wiegley429bb272011-04-08 18:41:53 +00007194 ExprResult old_lex = lex;
7195 lex = UsualUnaryConversions(lex.take());
7196 if (lex.isInvalid())
7197 return QualType();
7198 QualType LHSTy = lex.get()->getType();
John McCall1bc80af2010-12-16 19:28:59 +00007199 if (isCompAssign) lex = old_lex;
7200
7201 // The RHS is simpler.
John Wiegley429bb272011-04-08 18:41:53 +00007202 rex = UsualUnaryConversions(rex.take());
7203 if (rex.isInvalid())
7204 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007205
Ryan Flynnd0439682009-08-07 16:20:20 +00007206 // Sanity-check shift operands
Chandler Carruth21206d52011-02-23 23:34:11 +00007207 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnd0439682009-08-07 16:20:20 +00007208
Chris Lattnerca5eede2007-12-12 05:47:28 +00007209 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00007210 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007211}
7212
Chandler Carruth99919472010-07-10 12:30:03 +00007213static bool IsWithinTemplateSpecialization(Decl *D) {
7214 if (DeclContext *DC = D->getDeclContext()) {
7215 if (isa<ClassTemplateSpecializationDecl>(DC))
7216 return true;
7217 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7218 return FD->isFunctionTemplateSpecialization();
7219 }
7220 return false;
7221}
7222
Douglas Gregor0c6db942009-05-04 06:07:12 +00007223// C99 6.5.8, C++ [expr.rel]
John Wiegley429bb272011-04-08 18:41:53 +00007224QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00007225 unsigned OpaqueOpc, bool isRelational) {
John McCall2de56d12010-08-25 11:45:40 +00007226 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00007227
Chris Lattner02dd4b12009-12-05 05:40:13 +00007228 // Handle vector comparisons separately.
John Wiegley429bb272011-04-08 18:41:53 +00007229 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007230 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007231
John Wiegley429bb272011-04-08 18:41:53 +00007232 QualType lType = lex.get()->getType();
7233 QualType rType = rex.get()->getType();
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007234
John Wiegley429bb272011-04-08 18:41:53 +00007235 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
7236 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00007237 QualType LHSStrippedType = LHSStripped->getType();
7238 QualType RHSStrippedType = RHSStripped->getType();
7239
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007240
7241
Chandler Carruth543cb652011-02-17 08:37:06 +00007242 // Two different enums will raise a warning when compared.
7243 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
7244 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
7245 if (LHSEnumType->getDecl()->getIdentifier() &&
7246 RHSEnumType->getDecl()->getIdentifier() &&
7247 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
7248 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7249 << LHSStrippedType << RHSStrippedType
John Wiegley429bb272011-04-08 18:41:53 +00007250 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth543cb652011-02-17 08:37:06 +00007251 }
7252 }
7253 }
7254
Douglas Gregor8eee1192010-06-22 22:12:46 +00007255 if (!lType->hasFloatingRepresentation() &&
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00007256 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley429bb272011-04-08 18:41:53 +00007257 !lex.get()->getLocStart().isMacroID() &&
7258 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00007259 // For non-floating point types, check for self-comparisons of the form
7260 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7261 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00007262 //
7263 // NOTE: Don't warn about comparison expressions resulting from macro
7264 // expansion. Also don't warn about comparisons which are only self
7265 // comparisons within a template specialization. The warnings should catch
7266 // obvious cases in the definition of the template anyways. The idea is to
7267 // warn when the typed comparison operator will always evaluate to the same
7268 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00007269 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00007270 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00007271 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00007272 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00007273 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00007274 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00007275 << (Opc == BO_EQ
7276 || Opc == BO_LE
7277 || Opc == BO_GE));
Douglas Gregord64fdd02010-06-08 19:50:34 +00007278 } else if (lType->isArrayType() && rType->isArrayType() &&
7279 !DRL->getDecl()->getType()->isReferenceType() &&
7280 !DRR->getDecl()->getType()->isReferenceType()) {
7281 // what is it always going to eval to?
7282 char always_evals_to;
7283 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007284 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00007285 always_evals_to = 0; // false
7286 break;
John McCall2de56d12010-08-25 11:45:40 +00007287 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00007288 always_evals_to = 1; // true
7289 break;
7290 default:
7291 // best we can say is 'a constant'
7292 always_evals_to = 2; // e.g. array1 <= array2
7293 break;
7294 }
Ted Kremenek351ba912011-02-23 01:52:04 +00007295 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00007296 << 1 // array
7297 << always_evals_to);
7298 }
7299 }
Chandler Carruth99919472010-07-10 12:30:03 +00007300 }
Mike Stump1eb44332009-09-09 15:08:12 +00007301
Chris Lattner55660a72009-03-08 19:39:53 +00007302 if (isa<CastExpr>(LHSStripped))
7303 LHSStripped = LHSStripped->IgnoreParenCasts();
7304 if (isa<CastExpr>(RHSStripped))
7305 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00007306
Chris Lattner55660a72009-03-08 19:39:53 +00007307 // Warn about comparisons against a string constant (unless the other
7308 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00007309 Expr *literalString = 0;
7310 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00007311 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007312 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007313 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00007314 literalString = lex.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007315 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00007316 } else if ((isa<StringLiteral>(RHSStripped) ||
7317 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007318 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007319 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00007320 literalString = rex.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007321 literalStringStripped = RHSStripped;
7322 }
7323
7324 if (literalString) {
7325 std::string resultComparison;
7326 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007327 case BO_LT: resultComparison = ") < 0"; break;
7328 case BO_GT: resultComparison = ") > 0"; break;
7329 case BO_LE: resultComparison = ") <= 0"; break;
7330 case BO_GE: resultComparison = ") >= 0"; break;
7331 case BO_EQ: resultComparison = ") == 0"; break;
7332 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregora86b8322009-04-06 18:45:53 +00007333 default: assert(false && "Invalid comparison operator");
7334 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007335
Ted Kremenek351ba912011-02-23 01:52:04 +00007336 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00007337 PDiag(diag::warn_stringcompare)
7338 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00007339 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00007340 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00007341 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007342
Douglas Gregord64fdd02010-06-08 19:50:34 +00007343 // C99 6.5.8p3 / C99 6.5.9p4
John Wiegley429bb272011-04-08 18:41:53 +00007344 if (lex.get()->getType()->isArithmeticType() && rex.get()->getType()->isArithmeticType()) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00007345 UsualArithmeticConversions(lex, rex);
John Wiegley429bb272011-04-08 18:41:53 +00007346 if (lex.isInvalid() || rex.isInvalid())
7347 return QualType();
7348 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00007349 else {
John Wiegley429bb272011-04-08 18:41:53 +00007350 lex = UsualUnaryConversions(lex.take());
7351 if (lex.isInvalid())
7352 return QualType();
7353
7354 rex = UsualUnaryConversions(rex.take());
7355 if (rex.isInvalid())
7356 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007357 }
7358
John Wiegley429bb272011-04-08 18:41:53 +00007359 lType = lex.get()->getType();
7360 rType = rex.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007361
Douglas Gregor447b69e2008-11-19 03:25:36 +00007362 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00007363 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00007364
Chris Lattnera5937dd2007-08-26 01:18:55 +00007365 if (isRelational) {
7366 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007367 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007368 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00007369 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007370 if (lType->hasFloatingRepresentation())
John Wiegley429bb272011-04-08 18:41:53 +00007371 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007372
Chris Lattnera5937dd2007-08-26 01:18:55 +00007373 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007374 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007375 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007376
John Wiegley429bb272011-04-08 18:41:53 +00007377 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007378 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00007379 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007380 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007381
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007382 // All of the following pointer-related warnings are GCC extensions, except
7383 // when handling null pointer constants.
Steve Naroff77878cc2007-08-27 04:08:11 +00007384 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00007385 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00007386 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00007387 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00007388 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007389
Douglas Gregor0c6db942009-05-04 06:07:12 +00007390 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00007391 if (LCanPointeeTy == RCanPointeeTy)
7392 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007393 if (!isRelational &&
7394 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7395 // Valid unless comparison between non-null pointer and function pointer
7396 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007397 // In a SFINAE context, we treat this as a hard error to maintain
7398 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007399 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7400 && !LHSIsNull && !RHSIsNull) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007401 Diag(Loc,
7402 isSFINAEContext()?
7403 diag::err_typecheck_comparison_of_fptr_to_void
7404 : diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley429bb272011-04-08 18:41:53 +00007405 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007406
7407 if (isSFINAEContext())
7408 return QualType();
7409
John Wiegley429bb272011-04-08 18:41:53 +00007410 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007411 return ResultTy;
7412 }
7413 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007414
Douglas Gregor0c6db942009-05-04 06:07:12 +00007415 // C++ [expr.rel]p2:
7416 // [...] Pointer conversions (4.10) and qualification
7417 // conversions (4.4) are performed on pointer operands (or on
7418 // a pointer operand and a null pointer constant) to bring
7419 // them to their composite pointer type. [...]
7420 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00007421 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00007422 // comparisons of pointers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007423 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00007424 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007425 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor0c6db942009-05-04 06:07:12 +00007426 if (T.isNull()) {
7427 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007428 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00007429 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007430 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007431 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007432 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007433 << lType << rType << T
John Wiegley429bb272011-04-08 18:41:53 +00007434 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00007435 }
7436
John Wiegley429bb272011-04-08 18:41:53 +00007437 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7438 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00007439 return ResultTy;
7440 }
Eli Friedman3075e762009-08-23 00:27:47 +00007441 // C99 6.5.9p2 and C99 6.5.8p2
7442 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7443 RCanPointeeTy.getUnqualifiedType())) {
7444 // Valid unless a relational comparison of function pointers
7445 if (isRelational && LCanPointeeTy->isFunctionType()) {
7446 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007447 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007448 }
7449 } else if (!isRelational &&
7450 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7451 // Valid unless comparison between non-null pointer and function pointer
7452 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7453 && !LHSIsNull && !RHSIsNull) {
7454 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley429bb272011-04-08 18:41:53 +00007455 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007456 }
7457 } else {
7458 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007459 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007460 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007461 }
John McCall34d6f932011-03-11 04:25:25 +00007462 if (LCanPointeeTy != RCanPointeeTy) {
7463 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007464 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007465 else
John Wiegley429bb272011-04-08 18:41:53 +00007466 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007467 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00007468 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00007469 }
Mike Stump1eb44332009-09-09 15:08:12 +00007470
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007471 if (getLangOptions().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007472 // Comparison of nullptr_t with itself.
7473 if (lType->isNullPtrType() && rType->isNullPtrType())
7474 return ResultTy;
7475
Mike Stump1eb44332009-09-09 15:08:12 +00007476 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00007477 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00007478 if (RHSIsNull &&
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007479 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregor20b3e992009-08-24 17:42:35 +00007480 (!isRelational && lType->isMemberPointerType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00007481 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregor443c2122010-08-07 13:36:37 +00007482 lType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007483 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007484 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007485 return ResultTy;
7486 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007487 if (LHSIsNull &&
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007488 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregor20b3e992009-08-24 17:42:35 +00007489 (!isRelational && rType->isMemberPointerType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00007490 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregor443c2122010-08-07 13:36:37 +00007491 rType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007492 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007493 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007494 return ResultTy;
7495 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007496
7497 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00007498 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00007499 lType->isMemberPointerType() && rType->isMemberPointerType()) {
7500 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00007501 // In addition, pointers to members can be compared, or a pointer to
7502 // member and a null pointer constant. Pointer to member conversions
7503 // (4.11) and qualification conversions (4.4) are performed to bring
7504 // them to a common type. If one operand is a null pointer constant,
7505 // the common type is the type of the other operand. Otherwise, the
7506 // common type is a pointer to member type similar (4.4) to the type
7507 // of one of the operands, with a cv-qualification signature (4.4)
7508 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00007509 // types.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007510 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00007511 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007512 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor20b3e992009-08-24 17:42:35 +00007513 if (T.isNull()) {
7514 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007515 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00007516 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007517 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007518 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007519 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007520 << lType << rType << T
John Wiegley429bb272011-04-08 18:41:53 +00007521 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00007522 }
Mike Stump1eb44332009-09-09 15:08:12 +00007523
John Wiegley429bb272011-04-08 18:41:53 +00007524 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7525 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00007526 return ResultTy;
7527 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007528
7529 // Handle scoped enumeration types specifically, since they don't promote
7530 // to integers.
John Wiegley429bb272011-04-08 18:41:53 +00007531 if (lex.get()->getType()->isEnumeralType() &&
7532 Context.hasSameUnqualifiedType(lex.get()->getType(), rex.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00007533 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007534 }
Mike Stump1eb44332009-09-09 15:08:12 +00007535
Steve Naroff1c7d0672008-09-04 15:10:53 +00007536 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00007537 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00007538 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
7539 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007540
Steve Naroff1c7d0672008-09-04 15:10:53 +00007541 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00007542 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007543 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley429bb272011-04-08 18:41:53 +00007544 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00007545 }
John Wiegley429bb272011-04-08 18:41:53 +00007546 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007547 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007548 }
John Wiegley429bb272011-04-08 18:41:53 +00007549
Steve Naroff59f53942008-09-28 01:11:11 +00007550 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00007551 if (!isRelational
7552 && ((lType->isBlockPointerType() && rType->isPointerType())
7553 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00007554 if (!LHSIsNull && !RHSIsNull) {
John McCall34d6f932011-03-11 04:25:25 +00007555 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007556 ->getPointeeType()->isVoidType())
John McCall34d6f932011-03-11 04:25:25 +00007557 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007558 ->getPointeeType()->isVoidType())))
7559 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley429bb272011-04-08 18:41:53 +00007560 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00007561 }
John McCall34d6f932011-03-11 04:25:25 +00007562 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007563 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007564 else
John Wiegley429bb272011-04-08 18:41:53 +00007565 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007566 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00007567 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00007568
John McCall34d6f932011-03-11 04:25:25 +00007569 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
7570 const PointerType *LPT = lType->getAs<PointerType>();
7571 const PointerType *RPT = rType->getAs<PointerType>();
7572 if (LPT || RPT) {
7573 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7574 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007575
Steve Naroffa8069f12008-11-17 19:49:16 +00007576 if (!LPtrToVoid && !RPtrToVoid &&
7577 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007578 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007579 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00007580 }
John McCall34d6f932011-03-11 04:25:25 +00007581 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007582 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007583 else
John Wiegley429bb272011-04-08 18:41:53 +00007584 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007585 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00007586 }
Steve Naroff14108da2009-07-10 23:34:53 +00007587 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007588 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00007589 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007590 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
John McCall34d6f932011-03-11 04:25:25 +00007591 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007592 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007593 else
John Wiegley429bb272011-04-08 18:41:53 +00007594 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007595 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00007596 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00007597 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007598 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7599 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007600 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007601 bool isError = false;
7602 if ((LHSIsNull && lType->isIntegerType()) ||
7603 (RHSIsNull && rType->isIntegerType())) {
7604 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007605 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007606 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007607 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007608 else if (getLangOptions().CPlusPlus) {
7609 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7610 isError = true;
7611 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007612 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00007613
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007614 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007615 Diag(Loc, DiagID)
John Wiegley429bb272011-04-08 18:41:53 +00007616 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007617 if (isError)
7618 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00007619 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007620
7621 if (lType->isIntegerType())
John Wiegley429bb272011-04-08 18:41:53 +00007622 lex = ImpCastExprToType(lex.take(), rType,
John McCall404cd162010-11-13 01:35:44 +00007623 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007624 else
John Wiegley429bb272011-04-08 18:41:53 +00007625 rex = ImpCastExprToType(rex.take(), lType,
John McCall404cd162010-11-13 01:35:44 +00007626 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007627 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007628 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007629
Steve Naroff39218df2008-09-04 16:56:14 +00007630 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00007631 if (!isRelational && RHSIsNull
7632 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley429bb272011-04-08 18:41:53 +00007633 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007634 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007635 }
Mike Stumpaf199f32009-05-07 18:43:07 +00007636 if (!isRelational && LHSIsNull
7637 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley429bb272011-04-08 18:41:53 +00007638 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007639 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007640 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007641
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007642 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007643}
7644
Nate Begemanbe2341d2008-07-14 18:02:46 +00007645/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00007646/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007647/// like a scalar comparison, a vector comparison produces a vector of integer
7648/// types.
John Wiegley429bb272011-04-08 18:41:53 +00007649QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007650 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007651 bool isRelational) {
7652 // Check to make sure we're operating on vectors of the same type and width,
7653 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007654 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007655 if (vType.isNull())
7656 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007657
John Wiegley429bb272011-04-08 18:41:53 +00007658 QualType lType = lex.get()->getType();
7659 QualType rType = rex.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007660
Anton Yartsev7870b132011-03-27 15:36:07 +00007661 // If AltiVec, the comparison results in a numeric type, i.e.
7662 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00007663 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00007664 return Context.getLogicalOperationType();
7665
Nate Begemanbe2341d2008-07-14 18:02:46 +00007666 // For non-floating point types, check for self-comparisons of the form
7667 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7668 // often indicate logic errors in the program.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007669 if (!lType->hasFloatingRepresentation()) {
John Wiegley429bb272011-04-08 18:41:53 +00007670 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
7671 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007672 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00007673 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00007674 PDiag(diag::warn_comparison_always)
7675 << 0 // self-
7676 << 2 // "a constant"
7677 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00007678 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007679
Nate Begemanbe2341d2008-07-14 18:02:46 +00007680 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007681 if (!isRelational && lType->hasFloatingRepresentation()) {
7682 assert (rType->hasFloatingRepresentation());
John Wiegley429bb272011-04-08 18:41:53 +00007683 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007684 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007685
Nate Begemanbe2341d2008-07-14 18:02:46 +00007686 // Return the type for the comparison, which is the same as vector type for
7687 // integer vectors, or an integer type of identical size and number of
7688 // elements for floating point vectors.
Douglas Gregorf6094622010-07-23 15:58:24 +00007689 if (lType->hasIntegerRepresentation())
Nate Begemanbe2341d2008-07-14 18:02:46 +00007690 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007691
John McCall183700f2009-09-21 23:43:11 +00007692 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00007693 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00007694 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007695 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00007696 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00007697 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7698
Mike Stumpeed9cac2009-02-19 03:04:26 +00007699 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00007700 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00007701 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7702}
7703
Reid Spencer5f016e22007-07-11 17:01:13 +00007704inline QualType Sema::CheckBitwiseOperands(
John Wiegley429bb272011-04-08 18:41:53 +00007705 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
7706 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
7707 if (lex.get()->getType()->hasIntegerRepresentation() &&
7708 rex.get()->getType()->hasIntegerRepresentation())
Douglas Gregorf6094622010-07-23 15:58:24 +00007709 return CheckVectorOperands(Loc, lex, rex);
7710
7711 return InvalidOperands(Loc, lex, rex);
7712 }
Steve Naroff90045e82007-07-13 23:32:42 +00007713
John Wiegley429bb272011-04-08 18:41:53 +00007714 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
7715 QualType compType = UsualArithmeticConversions(lexResult, rexResult, isCompAssign);
7716 if (lexResult.isInvalid() || rexResult.isInvalid())
7717 return QualType();
7718 lex = lexResult.take();
7719 rex = rexResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007720
John Wiegley429bb272011-04-08 18:41:53 +00007721 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
7722 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007723 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007724 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007725}
7726
7727inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley429bb272011-04-08 18:41:53 +00007728 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00007729
7730 // Diagnose cases where the user write a logical and/or but probably meant a
7731 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7732 // is a constant.
John Wiegley429bb272011-04-08 18:41:53 +00007733 if (lex.get()->getType()->isIntegerType() && !lex.get()->getType()->isBooleanType() &&
7734 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Chris Lattner23ef3e42010-07-15 00:26:43 +00007735 // Don't warn in macros.
Chris Lattnerb7690b42010-07-24 01:10:11 +00007736 !Loc.isMacroID()) {
7737 // If the RHS can be constant folded, and if it constant folds to something
7738 // that isn't 0 or 1 (which indicate a potential logical operation that
7739 // happened to fold to true/false) then warn.
7740 Expr::EvalResult Result;
John Wiegley429bb272011-04-08 18:41:53 +00007741 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects &&
Chris Lattnerb7690b42010-07-24 01:10:11 +00007742 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
7743 Diag(Loc, diag::warn_logical_instead_of_bitwise)
John Wiegley429bb272011-04-08 18:41:53 +00007744 << rex.get()->getSourceRange()
John McCall2de56d12010-08-25 11:45:40 +00007745 << (Opc == BO_LAnd ? "&&" : "||")
7746 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattnerb7690b42010-07-24 01:10:11 +00007747 }
7748 }
Chris Lattner90a8f272010-07-13 19:41:32 +00007749
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007750 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007751 lex = UsualUnaryConversions(lex.take());
7752 if (lex.isInvalid())
7753 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007754
John Wiegley429bb272011-04-08 18:41:53 +00007755 rex = UsualUnaryConversions(rex.take());
7756 if (rex.isInvalid())
7757 return QualType();
7758
7759 if (!lex.get()->getType()->isScalarType() || !rex.get()->getType()->isScalarType())
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007760 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007761
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007762 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00007763 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007764
John McCall75f7c0f2010-06-04 00:29:51 +00007765 // The following is safe because we only use this method for
7766 // non-overloadable operands.
7767
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007768 // C++ [expr.log.and]p1
7769 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007770 // The operands are both contextually converted to type bool.
John Wiegley429bb272011-04-08 18:41:53 +00007771 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
7772 if (lexRes.isInvalid())
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007773 return InvalidOperands(Loc, lex, rex);
John Wiegley429bb272011-04-08 18:41:53 +00007774 lex = move(lexRes);
7775
7776 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
7777 if (rexRes.isInvalid())
7778 return InvalidOperands(Loc, lex, rex);
7779 rex = move(rexRes);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007780
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007781 // C++ [expr.log.and]p2
7782 // C++ [expr.log.or]p2
7783 // The result is a bool.
7784 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007785}
7786
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007787/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7788/// is a read-only property; return true if so. A readonly property expression
7789/// depends on various declarations and thus must be treated specially.
7790///
Mike Stump1eb44332009-09-09 15:08:12 +00007791static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007792 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7793 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCall12f78a62010-12-02 01:19:52 +00007794 if (PropExpr->isImplicitProperty()) return false;
7795
7796 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7797 QualType BaseType = PropExpr->isSuperReceiver() ?
7798 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007799 PropExpr->getBase()->getType();
7800
John McCall12f78a62010-12-02 01:19:52 +00007801 if (const ObjCObjectPointerType *OPT =
7802 BaseType->getAsObjCInterfacePointerType())
7803 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7804 if (S.isPropertyReadonly(PDecl, IFace))
7805 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007806 }
7807 return false;
7808}
7809
Fariborz Jahanian14086762011-03-28 23:47:18 +00007810static bool IsConstProperty(Expr *E, Sema &S) {
7811 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7812 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
7813 if (PropExpr->isImplicitProperty()) return false;
7814
7815 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7816 QualType T = PDecl->getType();
7817 if (T->isReferenceType())
Fariborz Jahanian61750f22011-03-30 16:59:30 +00007818 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanian14086762011-03-28 23:47:18 +00007819 CanQualType CT = S.Context.getCanonicalType(T);
7820 return CT.isConstQualified();
7821 }
7822 return false;
7823}
7824
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007825static bool IsReadonlyMessage(Expr *E, Sema &S) {
7826 if (E->getStmtClass() != Expr::MemberExprClass)
7827 return false;
7828 const MemberExpr *ME = cast<MemberExpr>(E);
7829 NamedDecl *Member = ME->getMemberDecl();
7830 if (isa<FieldDecl>(Member)) {
7831 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
7832 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
7833 return false;
7834 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
7835 }
7836 return false;
7837}
7838
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007839/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7840/// emit an error and return true. If so, return false.
7841static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007842 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007843 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007844 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007845 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7846 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian14086762011-03-28 23:47:18 +00007847 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7848 IsLV = Expr::MLV_Valid;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007849 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7850 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007851 if (IsLV == Expr::MLV_Valid)
7852 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007853
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007854 unsigned Diag = 0;
7855 bool NeedType = false;
7856 switch (IsLV) { // C99 6.5.16p2
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007857 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007858 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007859 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7860 NeedType = true;
7861 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007862 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007863 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7864 NeedType = true;
7865 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007866 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007867 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7868 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007869 case Expr::MLV_Valid:
7870 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007871 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007872 case Expr::MLV_MemberFunction:
7873 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007874 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7875 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007876 case Expr::MLV_IncompleteType:
7877 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007878 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007879 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00007880 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00007881 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007882 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7883 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00007884 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007885 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7886 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007887 case Expr::MLV_ReadonlyProperty:
7888 Diag = diag::error_readonly_property_assignment;
7889 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007890 case Expr::MLV_NoSetterProperty:
7891 Diag = diag::error_nosetter_property_assignment;
7892 break;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007893 case Expr::MLV_InvalidMessageExpression:
7894 Diag = diag::error_readonly_message_assignment;
7895 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007896 case Expr::MLV_SubObjCPropertySetting:
7897 Diag = diag::error_no_subobject_property_setting;
7898 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007899 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007900
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007901 SourceRange Assign;
7902 if (Loc != OrigLoc)
7903 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007904 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007905 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007906 else
Mike Stump1eb44332009-09-09 15:08:12 +00007907 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007908 return true;
7909}
7910
7911
7912
7913// C99 6.5.16.1
John Wiegley429bb272011-04-08 18:41:53 +00007914QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007915 SourceLocation Loc,
7916 QualType CompoundType) {
7917 // Verify that LHS is a modifiable lvalue, and emit error if not.
7918 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007919 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007920
7921 QualType LHSType = LHS->getType();
John Wiegley429bb272011-04-08 18:41:53 +00007922 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007923 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007924 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007925 QualType LHSTy(LHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007926 // Simple assignment "x = y".
John Wiegley429bb272011-04-08 18:41:53 +00007927 if (LHS->getObjectKind() == OK_ObjCProperty) {
7928 ExprResult LHSResult = Owned(LHS);
7929 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7930 if (LHSResult.isInvalid())
7931 return QualType();
7932 LHS = LHSResult.take();
7933 }
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007934 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007935 if (RHS.isInvalid())
7936 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007937 // Special case of NSObject attributes on c-style pointer types.
7938 if (ConvTy == IncompatiblePointer &&
7939 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007940 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007941 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007942 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007943 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007944
John McCallf89e55a2010-11-18 06:31:45 +00007945 if (ConvTy == Compatible &&
7946 getLangOptions().ObjCNonFragileABI &&
7947 LHSType->isObjCObjectType())
7948 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7949 << LHSType;
7950
Chris Lattner2c156472008-08-21 18:04:13 +00007951 // If the RHS is a unary plus or minus, check to see if they = and + are
7952 // right next to each other. If so, the user may have typo'd "x =+ 4"
7953 // instead of "x += 4".
John Wiegley429bb272011-04-08 18:41:53 +00007954 Expr *RHSCheck = RHS.get();
Chris Lattner2c156472008-08-21 18:04:13 +00007955 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7956 RHSCheck = ICE->getSubExpr();
7957 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007958 if ((UO->getOpcode() == UO_Plus ||
7959 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007960 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007961 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00007962 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7963 // And there is a space or other character before the subexpr of the
7964 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00007965 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7966 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007967 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007968 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007969 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007970 }
Chris Lattner2c156472008-08-21 18:04:13 +00007971 }
7972 } else {
7973 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007974 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007975 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007976
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007977 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007978 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007979 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007980
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +00007981 CheckForNullPointerDereference(*this, LHS);
Ted Kremeneka0125d82011-02-16 01:57:07 +00007982 // Check for trivial buffer overflows.
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007983 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremeneka0125d82011-02-16 01:57:07 +00007984
Reid Spencer5f016e22007-07-11 17:01:13 +00007985 // C99 6.5.16p3: The type of an assignment expression is the type of the
7986 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007987 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007988 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7989 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007990 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007991 // operand.
John McCall2bf6f492010-10-12 02:19:57 +00007992 return (getLangOptions().CPlusPlus
7993 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007994}
7995
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007996// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00007997static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00007998 SourceLocation Loc) {
John Wiegley429bb272011-04-08 18:41:53 +00007999 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00008000
John McCallfb8721c2011-04-10 19:13:55 +00008001 LHS = S.CheckPlaceholderExpr(LHS.take());
8002 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00008003 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00008004 return QualType();
8005
John McCallcf2e5062010-10-12 07:14:40 +00008006 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8007 // operands, but not unary promotions.
8008 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008009
John McCallf6a16482010-12-04 03:47:34 +00008010 // So we treat the LHS as a ignored value, and in C++ we allow the
8011 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00008012 LHS = S.IgnoredValueConversions(LHS.take());
8013 if (LHS.isInvalid())
8014 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00008015
8016 if (!S.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00008017 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
8018 if (RHS.isInvalid())
8019 return QualType();
8020 if (!RHS.get()->getType()->isVoidType())
8021 S.RequireCompleteType(Loc, RHS.get()->getType(), diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00008022 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008023
John Wiegley429bb272011-04-08 18:41:53 +00008024 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008025}
8026
Steve Naroff49b45262007-07-13 16:58:59 +00008027/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8028/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00008029static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8030 ExprValueKind &VK,
8031 SourceLocation OpLoc,
8032 bool isInc, bool isPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00008033 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008034 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008035
Chris Lattner3528d352008-11-21 07:05:48 +00008036 QualType ResType = Op->getType();
8037 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008038
John McCall09431682010-11-18 19:01:18 +00008039 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00008040 // Decrement of bool is not allowed.
8041 if (!isInc) {
John McCall09431682010-11-18 19:01:18 +00008042 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00008043 return QualType();
8044 }
8045 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00008046 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00008047 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00008048 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00008049 } else if (ResType->isAnyPointerType()) {
8050 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00008051
Chris Lattner3528d352008-11-21 07:05:48 +00008052 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00008053 if (PointeeTy->isVoidType()) {
John McCall09431682010-11-18 19:01:18 +00008054 if (S.getLangOptions().CPlusPlus) {
8055 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00008056 << Op->getSourceRange();
8057 return QualType();
8058 }
8059
8060 // Pointer to void is a GNU extension in C.
John McCall09431682010-11-18 19:01:18 +00008061 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00008062 } else if (PointeeTy->isFunctionType()) {
John McCall09431682010-11-18 19:01:18 +00008063 if (S.getLangOptions().CPlusPlus) {
8064 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00008065 << Op->getType() << Op->getSourceRange();
8066 return QualType();
8067 }
8068
John McCall09431682010-11-18 19:01:18 +00008069 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00008070 << ResType << Op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00008071 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
8072 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00008073 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00008074 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00008075 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00008076 // Diagnose bad cases where we step over interface counts.
John McCall09431682010-11-18 19:01:18 +00008077 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
8078 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00008079 << PointeeTy << Op->getSourceRange();
8080 return QualType();
8081 }
Eli Friedman5b088a12010-01-03 00:20:48 +00008082 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00008083 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00008084 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00008085 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008086 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008087 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008088 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008089 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
8090 isInc, isPrefix);
Anton Yartsev683564a2011-02-07 02:17:30 +00008091 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
8092 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00008093 } else {
John McCall09431682010-11-18 19:01:18 +00008094 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00008095 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00008096 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008097 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008098 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00008099 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00008100 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00008101 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008102 // In C++, a prefix increment is the same type as the operand. Otherwise
8103 // (in C or with postfix), the increment is the unqualified type of the
8104 // operand.
John McCall09431682010-11-18 19:01:18 +00008105 if (isPrefix && S.getLangOptions().CPlusPlus) {
8106 VK = VK_LValue;
8107 return ResType;
8108 } else {
8109 VK = VK_RValue;
8110 return ResType.getUnqualifiedType();
8111 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008112}
8113
John Wiegley429bb272011-04-08 18:41:53 +00008114ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCallf6a16482010-12-04 03:47:34 +00008115 assert(E->getValueKind() == VK_LValue &&
8116 E->getObjectKind() == OK_ObjCProperty);
8117 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
8118
8119 ExprValueKind VK = VK_RValue;
8120 if (PRE->isImplicitProperty()) {
Fariborz Jahanian99130e52010-12-22 19:46:35 +00008121 if (const ObjCMethodDecl *GetterMethod =
8122 PRE->getImplicitPropertyGetter()) {
8123 QualType Result = GetterMethod->getResultType();
8124 VK = Expr::getValueKindForType(Result);
8125 }
8126 else {
8127 Diag(PRE->getLocation(), diag::err_getter_not_found)
8128 << PRE->getBase()->getType();
8129 }
John McCallf6a16482010-12-04 03:47:34 +00008130 }
8131
8132 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
8133 E, 0, VK);
John McCalldb67e2f2010-12-10 01:49:45 +00008134
8135 ExprResult Result = MaybeBindToTemporary(E);
8136 if (!Result.isInvalid())
8137 E = Result.take();
John Wiegley429bb272011-04-08 18:41:53 +00008138
8139 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00008140}
8141
John Wiegley429bb272011-04-08 18:41:53 +00008142void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType &LHSTy) {
8143 assert(LHS.get()->getValueKind() == VK_LValue &&
8144 LHS.get()->getObjectKind() == OK_ObjCProperty);
8145 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCallf6a16482010-12-04 03:47:34 +00008146
John Wiegley429bb272011-04-08 18:41:53 +00008147 if (PropRef->isImplicitProperty()) {
John McCallf6a16482010-12-04 03:47:34 +00008148 // If using property-dot syntax notation for assignment, and there is a
8149 // setter, RHS expression is being passed to the setter argument. So,
8150 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley429bb272011-04-08 18:41:53 +00008151 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCallf6a16482010-12-04 03:47:34 +00008152 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
8153 LHSTy = (*P)->getType();
8154
8155 // Otherwise, if the getter returns an l-value, just call that.
8156 } else {
John Wiegley429bb272011-04-08 18:41:53 +00008157 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCallf6a16482010-12-04 03:47:34 +00008158 ExprValueKind VK = Expr::getValueKindForType(Result);
8159 if (VK == VK_LValue) {
John Wiegley429bb272011-04-08 18:41:53 +00008160 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
8161 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCallf6a16482010-12-04 03:47:34 +00008162 return;
John McCall12f78a62010-12-02 01:19:52 +00008163 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008164 }
John McCallf6a16482010-12-04 03:47:34 +00008165 }
8166
8167 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008168 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00008169 InitializedEntity::InitializeParameter(Context, LHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00008170 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008171 if (!ArgE.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00008172 RHS = ArgE;
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008173 }
8174}
8175
8176
Anders Carlsson369dee42008-02-01 07:15:58 +00008177/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00008178/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008179/// where the declaration is needed for type checking. We only need to
8180/// handle cases when the expression references a function designator
8181/// or is an lvalue. Here are some examples:
8182/// - &(x) => x
8183/// - &*****f => f for f a function designator.
8184/// - &s.xx => s
8185/// - &s.zz[1].yy -> s, if zz is an array
8186/// - *(x + 1) -> x, if x is an array
8187/// - &"123"[2] -> 0
8188/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00008189static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00008190 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00008191 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00008192 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00008193 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00008194 // If this is an arrow operator, the address is an offset from
8195 // the base's value, so the object the base refers to is
8196 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00008197 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00008198 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00008199 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00008200 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00008201 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00008202 // FIXME: This code shouldn't be necessary! We should catch the implicit
8203 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00008204 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8205 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8206 if (ICE->getSubExpr()->getType()->isArrayType())
8207 return getPrimaryDecl(ICE->getSubExpr());
8208 }
8209 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00008210 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008211 case Stmt::UnaryOperatorClass: {
8212 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008213
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008214 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00008215 case UO_Real:
8216 case UO_Imag:
8217 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008218 return getPrimaryDecl(UO->getSubExpr());
8219 default:
8220 return 0;
8221 }
8222 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008223 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00008224 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00008225 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00008226 // If the result of an implicit cast is an l-value, we care about
8227 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00008228 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00008229 default:
8230 return 0;
8231 }
8232}
8233
8234/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00008235/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00008236/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008237/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00008238/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008239/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00008240/// we allow the '&' but retain the overloaded-function type.
John McCall09431682010-11-18 19:01:18 +00008241static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
8242 SourceLocation OpLoc) {
John McCall9c72c602010-08-27 09:08:28 +00008243 if (OrigOp->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008244 return S.Context.DependentTy;
8245 if (OrigOp->getType() == S.Context.OverloadTy)
8246 return S.Context.OverloadTy;
John McCall755d8492011-04-12 00:42:48 +00008247 if (OrigOp->getType() == S.Context.UnknownAnyTy)
8248 return S.Context.UnknownAnyTy;
John McCall864c0412011-04-26 20:42:42 +00008249 if (OrigOp->getType() == S.Context.BoundMemberTy) {
8250 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8251 << OrigOp->getSourceRange();
8252 return QualType();
8253 }
John McCall9c72c602010-08-27 09:08:28 +00008254
John McCall755d8492011-04-12 00:42:48 +00008255 assert(!OrigOp->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00008256
John McCall9c72c602010-08-27 09:08:28 +00008257 // Make sure to ignore parentheses in subsequent checks
8258 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00008259
John McCall09431682010-11-18 19:01:18 +00008260 if (S.getLangOptions().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00008261 // Implement C99-only parts of addressof rules.
8262 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00008263 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00008264 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8265 // (assuming the deref expression is valid).
8266 return uOp->getSubExpr()->getType();
8267 }
8268 // Technically, there should be a check for array subscript
8269 // expressions here, but the result of one is always an lvalue anyway.
8270 }
John McCall5808ce42011-02-03 08:15:49 +00008271 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00008272 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00008273
Fariborz Jahanian077f4902011-03-26 19:48:30 +00008274 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00008275 bool sfinae = S.isSFINAEContext();
8276 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8277 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00008278 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00008279 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00008280 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00008281 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008282 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00008283 } else if (lval == Expr::LV_MemberFunction) {
8284 // If it's an instance method, make a member pointer.
8285 // The expression must have exactly the form &A::foo.
8286
8287 // If the underlying expression isn't a decl ref, give up.
8288 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008289 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00008290 << OrigOp->getSourceRange();
8291 return QualType();
8292 }
8293 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8294 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8295
8296 // The id-expression was parenthesized.
8297 if (OrigOp != DRE) {
John McCall09431682010-11-18 19:01:18 +00008298 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00008299 << OrigOp->getSourceRange();
8300
8301 // The method was named without a qualifier.
8302 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00008303 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00008304 << op->getSourceRange();
8305 }
8306
John McCall09431682010-11-18 19:01:18 +00008307 return S.Context.getMemberPointerType(op->getType(),
8308 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00008309 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00008310 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008311 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00008312 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00008313 // FIXME: emit more specific diag...
John McCall09431682010-11-18 19:01:18 +00008314 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008315 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00008316 return QualType();
8317 }
John McCall7eb0a9e2010-11-24 05:12:34 +00008318 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008319 // The operand cannot be a bit-field
John McCall09431682010-11-18 19:01:18 +00008320 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman23d58ce2009-04-20 08:23:18 +00008321 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00008322 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00008323 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00008324 // The operand cannot be an element of a vector
John McCall09431682010-11-18 19:01:18 +00008325 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00008326 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00008327 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00008328 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian0337f212009-07-07 18:50:52 +00008329 // cannot take address of a property expression.
John McCall09431682010-11-18 19:01:18 +00008330 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian0337f212009-07-07 18:50:52 +00008331 << "property expression" << op->getSourceRange();
8332 return QualType();
Steve Naroffbcb2b612008-02-29 23:30:25 +00008333 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00008334 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00008335 // with the register storage-class specifier.
8336 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00008337 // in C++ it is not error to take address of a register
8338 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00008339 if (vd->getStorageClass() == SC_Register &&
John McCall09431682010-11-18 19:01:18 +00008340 !S.getLangOptions().CPlusPlus) {
8341 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008342 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00008343 return QualType();
8344 }
John McCallba135432009-11-21 08:51:07 +00008345 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00008346 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00008347 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00008348 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00008349 // Could be a pointer to member, though, if there is an explicit
8350 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00008351 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00008352 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008353 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00008354 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00008355 S.Diag(OpLoc,
8356 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00008357 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008358 return QualType();
8359 }
Mike Stump1eb44332009-09-09 15:08:12 +00008360
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00008361 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8362 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00008363 return S.Context.getMemberPointerType(op->getType(),
8364 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008365 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00008366 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00008367 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00008368 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00008369 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00008370
Eli Friedman441cf102009-05-16 23:27:50 +00008371 if (lval == Expr::LV_IncompleteVoidType) {
8372 // Taking the address of a void variable is technically illegal, but we
8373 // allow it in cases which are otherwise valid.
8374 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00008375 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00008376 }
8377
Reid Spencer5f016e22007-07-11 17:01:13 +00008378 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00008379 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00008380 return S.Context.getObjCObjectPointerType(op->getType());
8381 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00008382}
8383
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008384/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00008385static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8386 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00008387 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008388 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008389
John Wiegley429bb272011-04-08 18:41:53 +00008390 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8391 if (ConvResult.isInvalid())
8392 return QualType();
8393 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008394 QualType OpTy = Op->getType();
8395 QualType Result;
8396
8397 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8398 // is an incomplete type or void. It would be possible to warn about
8399 // dereferencing a void pointer, but it's completely well-defined, and such a
8400 // warning is unlikely to catch any mistakes.
8401 if (const PointerType *PT = OpTy->getAs<PointerType>())
8402 Result = PT->getPointeeType();
8403 else if (const ObjCObjectPointerType *OPT =
8404 OpTy->getAs<ObjCObjectPointerType>())
8405 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00008406 else {
John McCallfb8721c2011-04-10 19:13:55 +00008407 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008408 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008409 if (PR.take() != Op)
8410 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00008411 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008412
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008413 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00008414 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008415 << OpTy << Op->getSourceRange();
8416 return QualType();
8417 }
John McCall09431682010-11-18 19:01:18 +00008418
8419 // Dereferences are usually l-values...
8420 VK = VK_LValue;
8421
8422 // ...except that certain expressions are never l-values in C.
8423 if (!S.getLangOptions().CPlusPlus &&
8424 IsCForbiddenLValueType(S.Context, Result))
8425 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008426
8427 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00008428}
8429
John McCall2de56d12010-08-25 11:45:40 +00008430static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008431 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008432 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008433 switch (Kind) {
8434 default: assert(0 && "Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00008435 case tok::periodstar: Opc = BO_PtrMemD; break;
8436 case tok::arrowstar: Opc = BO_PtrMemI; break;
8437 case tok::star: Opc = BO_Mul; break;
8438 case tok::slash: Opc = BO_Div; break;
8439 case tok::percent: Opc = BO_Rem; break;
8440 case tok::plus: Opc = BO_Add; break;
8441 case tok::minus: Opc = BO_Sub; break;
8442 case tok::lessless: Opc = BO_Shl; break;
8443 case tok::greatergreater: Opc = BO_Shr; break;
8444 case tok::lessequal: Opc = BO_LE; break;
8445 case tok::less: Opc = BO_LT; break;
8446 case tok::greaterequal: Opc = BO_GE; break;
8447 case tok::greater: Opc = BO_GT; break;
8448 case tok::exclaimequal: Opc = BO_NE; break;
8449 case tok::equalequal: Opc = BO_EQ; break;
8450 case tok::amp: Opc = BO_And; break;
8451 case tok::caret: Opc = BO_Xor; break;
8452 case tok::pipe: Opc = BO_Or; break;
8453 case tok::ampamp: Opc = BO_LAnd; break;
8454 case tok::pipepipe: Opc = BO_LOr; break;
8455 case tok::equal: Opc = BO_Assign; break;
8456 case tok::starequal: Opc = BO_MulAssign; break;
8457 case tok::slashequal: Opc = BO_DivAssign; break;
8458 case tok::percentequal: Opc = BO_RemAssign; break;
8459 case tok::plusequal: Opc = BO_AddAssign; break;
8460 case tok::minusequal: Opc = BO_SubAssign; break;
8461 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8462 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8463 case tok::ampequal: Opc = BO_AndAssign; break;
8464 case tok::caretequal: Opc = BO_XorAssign; break;
8465 case tok::pipeequal: Opc = BO_OrAssign; break;
8466 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008467 }
8468 return Opc;
8469}
8470
John McCall2de56d12010-08-25 11:45:40 +00008471static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008472 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008473 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008474 switch (Kind) {
8475 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00008476 case tok::plusplus: Opc = UO_PreInc; break;
8477 case tok::minusminus: Opc = UO_PreDec; break;
8478 case tok::amp: Opc = UO_AddrOf; break;
8479 case tok::star: Opc = UO_Deref; break;
8480 case tok::plus: Opc = UO_Plus; break;
8481 case tok::minus: Opc = UO_Minus; break;
8482 case tok::tilde: Opc = UO_Not; break;
8483 case tok::exclaim: Opc = UO_LNot; break;
8484 case tok::kw___real: Opc = UO_Real; break;
8485 case tok::kw___imag: Opc = UO_Imag; break;
8486 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008487 }
8488 return Opc;
8489}
8490
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008491/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8492/// This warning is only emitted for builtin assignment operations. It is also
8493/// suppressed in the event of macro expansions.
8494static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
8495 SourceLocation OpLoc) {
8496 if (!S.ActiveTemplateInstantiations.empty())
8497 return;
8498 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8499 return;
8500 lhs = lhs->IgnoreParenImpCasts();
8501 rhs = rhs->IgnoreParenImpCasts();
8502 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
8503 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
8504 if (!LeftDeclRef || !RightDeclRef ||
8505 LeftDeclRef->getLocation().isMacroID() ||
8506 RightDeclRef->getLocation().isMacroID())
8507 return;
8508 const ValueDecl *LeftDecl =
8509 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
8510 const ValueDecl *RightDecl =
8511 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
8512 if (LeftDecl != RightDecl)
8513 return;
8514 if (LeftDecl->getType().isVolatileQualified())
8515 return;
8516 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
8517 if (RefTy->getPointeeType().isVolatileQualified())
8518 return;
8519
8520 S.Diag(OpLoc, diag::warn_self_assignment)
8521 << LeftDeclRef->getType()
8522 << lhs->getSourceRange() << rhs->getSourceRange();
8523}
8524
Douglas Gregoreaebc752008-11-06 23:29:22 +00008525/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8526/// operator @p Opc at location @c TokLoc. This routine only supports
8527/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00008528ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008529 BinaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008530 Expr *lhsExpr, Expr *rhsExpr) {
8531 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008532 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00008533 // The following two variables are used for compound assignment operators
8534 QualType CompLHSTy; // Type of LHS after promotions for computation
8535 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00008536 ExprValueKind VK = VK_RValue;
8537 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00008538
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008539 // Check if a 'foo<int>' involved in a binary op, identifies a single
8540 // function unambiguously (i.e. an lvalue ala 13.4)
8541 // But since an assignment can trigger target based overload, exclude it in
8542 // our blind search. i.e:
8543 // template<class T> void f(); template<class T, class U> void f(U);
8544 // f<int> == 0; // resolve f<int> blindly
8545 // void (*p)(int); p = f<int>; // resolve f<int> using target
8546 if (Opc != BO_Assign) {
John McCallfb8721c2011-04-10 19:13:55 +00008547 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall1de4d4e2011-04-07 08:22:57 +00008548 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008549 lhs = move(resolvedLHS);
John McCall1de4d4e2011-04-07 08:22:57 +00008550
John McCallfb8721c2011-04-10 19:13:55 +00008551 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall1de4d4e2011-04-07 08:22:57 +00008552 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008553 rhs = move(resolvedRHS);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008554 }
8555
Douglas Gregoreaebc752008-11-06 23:29:22 +00008556 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008557 case BO_Assign:
John Wiegley429bb272011-04-08 18:41:53 +00008558 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCallf6a16482010-12-04 03:47:34 +00008559 if (getLangOptions().CPlusPlus &&
John Wiegley429bb272011-04-08 18:41:53 +00008560 lhs.get()->getObjectKind() != OK_ObjCProperty) {
8561 VK = lhs.get()->getValueKind();
8562 OK = lhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008563 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008564 if (!ResultTy.isNull())
John Wiegley429bb272011-04-08 18:41:53 +00008565 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008566 break;
John McCall2de56d12010-08-25 11:45:40 +00008567 case BO_PtrMemD:
8568 case BO_PtrMemI:
John McCallf89e55a2010-11-18 06:31:45 +00008569 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008570 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00008571 break;
John McCall2de56d12010-08-25 11:45:40 +00008572 case BO_Mul:
8573 case BO_Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00008574 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00008575 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008576 break;
John McCall2de56d12010-08-25 11:45:40 +00008577 case BO_Rem:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008578 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
8579 break;
John McCall2de56d12010-08-25 11:45:40 +00008580 case BO_Add:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008581 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
8582 break;
John McCall2de56d12010-08-25 11:45:40 +00008583 case BO_Sub:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008584 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
8585 break;
John McCall2de56d12010-08-25 11:45:40 +00008586 case BO_Shl:
8587 case BO_Shr:
Chandler Carruth21206d52011-02-23 23:34:11 +00008588 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008589 break;
John McCall2de56d12010-08-25 11:45:40 +00008590 case BO_LE:
8591 case BO_LT:
8592 case BO_GE:
8593 case BO_GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00008594 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008595 break;
John McCall2de56d12010-08-25 11:45:40 +00008596 case BO_EQ:
8597 case BO_NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00008598 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008599 break;
John McCall2de56d12010-08-25 11:45:40 +00008600 case BO_And:
8601 case BO_Xor:
8602 case BO_Or:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008603 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
8604 break;
John McCall2de56d12010-08-25 11:45:40 +00008605 case BO_LAnd:
8606 case BO_LOr:
Chris Lattner90a8f272010-07-13 19:41:32 +00008607 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008608 break;
John McCall2de56d12010-08-25 11:45:40 +00008609 case BO_MulAssign:
8610 case BO_DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00008611 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00008612 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008613 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00008614 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8615 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008616 break;
John McCall2de56d12010-08-25 11:45:40 +00008617 case BO_RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008618 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
8619 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00008620 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8621 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008622 break;
John McCall2de56d12010-08-25 11:45:40 +00008623 case BO_AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008624 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00008625 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8626 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008627 break;
John McCall2de56d12010-08-25 11:45:40 +00008628 case BO_SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008629 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00008630 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8631 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008632 break;
John McCall2de56d12010-08-25 11:45:40 +00008633 case BO_ShlAssign:
8634 case BO_ShrAssign:
Chandler Carruth21206d52011-02-23 23:34:11 +00008635 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008636 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00008637 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8638 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008639 break;
John McCall2de56d12010-08-25 11:45:40 +00008640 case BO_AndAssign:
8641 case BO_XorAssign:
8642 case BO_OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008643 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
8644 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00008645 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8646 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008647 break;
John McCall2de56d12010-08-25 11:45:40 +00008648 case BO_Comma:
John McCall09431682010-11-18 19:01:18 +00008649 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00008650 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
8651 VK = rhs.get()->getValueKind();
8652 OK = rhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008653 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00008654 break;
8655 }
John Wiegley429bb272011-04-08 18:41:53 +00008656 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008657 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00008658 if (CompResultTy.isNull())
John Wiegley429bb272011-04-08 18:41:53 +00008659 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
8660 ResultTy, VK, OK, OpLoc));
8661 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00008662 VK = VK_LValue;
John Wiegley429bb272011-04-08 18:41:53 +00008663 OK = lhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008664 }
John Wiegley429bb272011-04-08 18:41:53 +00008665 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
8666 ResultTy, VK, OK, CompLHSTy,
John McCallf89e55a2010-11-18 06:31:45 +00008667 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00008668}
8669
Sebastian Redlaee3c932009-10-27 12:10:02 +00008670/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
8671/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008672static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8673 const PartialDiagnostic &PD,
Douglas Gregor55b38842010-04-14 16:09:52 +00008674 const PartialDiagnostic &FirstNote,
8675 SourceRange FirstParenRange,
8676 const PartialDiagnostic &SecondNote,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008677 SourceRange SecondParenRange) {
Douglas Gregor55b38842010-04-14 16:09:52 +00008678 Self.Diag(Loc, PD);
8679
8680 if (!FirstNote.getDiagID())
8681 return;
8682
8683 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
8684 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8685 // We can't display the parentheses, so just return.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008686 return;
8687 }
8688
Douglas Gregor55b38842010-04-14 16:09:52 +00008689 Self.Diag(Loc, FirstNote)
8690 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregor849b2432010-03-31 17:46:05 +00008691 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008692
Douglas Gregor55b38842010-04-14 16:09:52 +00008693 if (!SecondNote.getDiagID())
Douglas Gregor827feec2010-01-08 00:20:23 +00008694 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008695
Douglas Gregor827feec2010-01-08 00:20:23 +00008696 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
8697 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8698 // We can't display the parentheses, so just dig the
8699 // warning/error and return.
Douglas Gregor55b38842010-04-14 16:09:52 +00008700 Self.Diag(Loc, SecondNote);
Douglas Gregor827feec2010-01-08 00:20:23 +00008701 return;
8702 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008703
Douglas Gregor55b38842010-04-14 16:09:52 +00008704 Self.Diag(Loc, SecondNote)
Douglas Gregor849b2432010-03-31 17:46:05 +00008705 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
8706 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008707}
8708
Sebastian Redlaee3c932009-10-27 12:10:02 +00008709/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8710/// operators are mixed in a way that suggests that the programmer forgot that
8711/// comparison operators have higher precedence. The most typical example of
8712/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00008713static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008714 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00008715 typedef BinaryOperator BinOp;
8716 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
8717 rhsopc = static_cast<BinOp::Opcode>(-1);
8718 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008719 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00008720 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008721 rhsopc = BO->getOpcode();
8722
8723 // Subs are not binary operators.
8724 if (lhsopc == -1 && rhsopc == -1)
8725 return;
8726
8727 // Bitwise operations are sometimes used as eager logical ops.
8728 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00008729 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
8730 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008731 return;
8732
Sebastian Redlaee3c932009-10-27 12:10:02 +00008733 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008734 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008735 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00008736 << SourceRange(lhs->getLocStart(), OpLoc)
8737 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor55b38842010-04-14 16:09:52 +00008738 Self.PDiag(diag::note_precedence_bitwise_silence)
8739 << BinOp::getOpcodeStr(lhsopc),
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00008740 lhs->getSourceRange(),
8741 Self.PDiag(diag::note_precedence_bitwise_first)
8742 << BinOp::getOpcodeStr(Opc),
8743 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
Sebastian Redlaee3c932009-10-27 12:10:02 +00008744 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008745 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008746 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00008747 << SourceRange(OpLoc, rhs->getLocEnd())
8748 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00008749 Self.PDiag(diag::note_precedence_bitwise_silence)
8750 << BinOp::getOpcodeStr(rhsopc),
8751 rhs->getSourceRange(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008752 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00008753 << BinOp::getOpcodeStr(Opc),
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00008754 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008755}
8756
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008757/// \brief It accepts a '&&' expr that is inside a '||' one.
8758/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8759/// in parentheses.
8760static void
8761EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008762 BinaryOperator *Bop) {
8763 assert(Bop->getOpcode() == BO_LAnd);
8764 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008765 Self.PDiag(diag::warn_logical_and_in_logical_or)
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008766 << Bop->getSourceRange() << OpLoc,
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008767 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008768 Bop->getSourceRange(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008769 Self.PDiag(0), SourceRange());
8770}
8771
8772/// \brief Returns true if the given expression can be evaluated as a constant
8773/// 'true'.
8774static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8775 bool Res;
8776 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8777}
8778
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008779/// \brief Returns true if the given expression can be evaluated as a constant
8780/// 'false'.
8781static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8782 bool Res;
8783 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8784}
8785
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008786/// \brief Look for '&&' in the left hand of a '||' expr.
8787static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008788 Expr *OrLHS, Expr *OrRHS) {
8789 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008790 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008791 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8792 if (EvaluatesAsFalse(S, OrRHS))
8793 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008794 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8795 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8796 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8797 } else if (Bop->getOpcode() == BO_LOr) {
8798 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8799 // If it's "a || b && 1 || c" we didn't warn earlier for
8800 // "a || b && 1", but warn now.
8801 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8802 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8803 }
8804 }
8805 }
8806}
8807
8808/// \brief Look for '&&' in the right hand of a '||' expr.
8809static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008810 Expr *OrLHS, Expr *OrRHS) {
8811 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008812 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008813 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8814 if (EvaluatesAsFalse(S, OrLHS))
8815 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008816 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8817 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8818 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008819 }
8820 }
8821}
8822
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008823/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008824/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008825static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008826 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008827 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008828 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008829 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
8830
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008831 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8832 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008833 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008834 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
8835 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008836 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008837}
8838
Reid Spencer5f016e22007-07-11 17:01:13 +00008839// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008840ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008841 tok::TokenKind Kind,
8842 Expr *lhs, Expr *rhs) {
8843 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Narofff69936d2007-09-16 03:34:24 +00008844 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8845 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008846
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008847 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8848 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8849
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008850 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8851}
8852
John McCall60d7b3a2010-08-24 06:29:42 +00008853ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008854 BinaryOperatorKind Opc,
8855 Expr *lhs, Expr *rhs) {
John McCall01b2e4e2010-12-06 05:26:58 +00008856 if (getLangOptions().CPlusPlus) {
8857 bool UseBuiltinOperator;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008858
John McCall01b2e4e2010-12-06 05:26:58 +00008859 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8860 UseBuiltinOperator = false;
8861 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8862 UseBuiltinOperator = true;
8863 } else {
8864 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8865 !rhs->getType()->isOverloadableType();
8866 }
8867
8868 if (!UseBuiltinOperator) {
8869 // Find all of the overloaded operators visible from this
8870 // point. We perform both an operator-name lookup from the local
8871 // scope and an argument-dependent lookup based on the types of
8872 // the arguments.
8873 UnresolvedSet<16> Functions;
8874 OverloadedOperatorKind OverOp
8875 = BinaryOperator::getOverloadedOperator(Opc);
8876 if (S && OverOp != OO_None)
8877 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8878 Functions);
8879
8880 // Build the (potentially-overloaded, potentially-dependent)
8881 // binary operation.
8882 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8883 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008884 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008885
Douglas Gregoreaebc752008-11-06 23:29:22 +00008886 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008887 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00008888}
8889
John McCall60d7b3a2010-08-24 06:29:42 +00008890ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008891 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008892 Expr *InputExpr) {
8893 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008894 ExprValueKind VK = VK_RValue;
8895 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008896 QualType resultType;
8897 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008898 case UO_PreInc:
8899 case UO_PreDec:
8900 case UO_PostInc:
8901 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008902 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008903 Opc == UO_PreInc ||
8904 Opc == UO_PostInc,
8905 Opc == UO_PreInc ||
8906 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008907 break;
John McCall2de56d12010-08-25 11:45:40 +00008908 case UO_AddrOf:
John Wiegley429bb272011-04-08 18:41:53 +00008909 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008910 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008911 case UO_Deref: {
John McCallfb8721c2011-04-10 19:13:55 +00008912 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall1de4d4e2011-04-07 08:22:57 +00008913 if (!resolved.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008914 Input = move(resolved);
8915 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8916 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008917 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008918 }
John McCall2de56d12010-08-25 11:45:40 +00008919 case UO_Plus:
8920 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008921 Input = UsualUnaryConversions(Input.take());
8922 if (Input.isInvalid()) return ExprError();
8923 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008924 if (resultType->isDependentType())
8925 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008926 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8927 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008928 break;
8929 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8930 resultType->isEnumeralType())
8931 break;
8932 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008933 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008934 resultType->isPointerType())
8935 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008936 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008937 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008938 if (Input.isInvalid()) return ExprError();
8939 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008940 }
Douglas Gregor74253732008-11-19 15:42:04 +00008941
Sebastian Redl0eb23302009-01-19 00:08:26 +00008942 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008943 << resultType << Input.get()->getSourceRange());
8944
John McCall2de56d12010-08-25 11:45:40 +00008945 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008946 Input = UsualUnaryConversions(Input.take());
8947 if (Input.isInvalid()) return ExprError();
8948 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008949 if (resultType->isDependentType())
8950 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008951 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8952 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8953 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008954 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008955 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008956 else if (resultType->hasIntegerRepresentation())
8957 break;
8958 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008959 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008960 if (Input.isInvalid()) return ExprError();
8961 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008962 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008963 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008964 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008965 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008966 break;
John Wiegley429bb272011-04-08 18:41:53 +00008967
John McCall2de56d12010-08-25 11:45:40 +00008968 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008969 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008970 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8971 if (Input.isInvalid()) return ExprError();
8972 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008973 if (resultType->isDependentType())
8974 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008975 if (resultType->isScalarType()) {
8976 // C99 6.5.3.3p1: ok, fallthrough;
8977 if (Context.getLangOptions().CPlusPlus) {
8978 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8979 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008980 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8981 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008982 }
John McCall2cd11fe2010-10-12 02:09:17 +00008983 } else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008984 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008985 if (Input.isInvalid()) return ExprError();
8986 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008987 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008988 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008989 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008990 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008991
Reid Spencer5f016e22007-07-11 17:01:13 +00008992 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008993 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008994 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008995 break;
John McCall2de56d12010-08-25 11:45:40 +00008996 case UO_Real:
8997 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008998 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCallf89e55a2010-11-18 06:31:45 +00008999 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley429bb272011-04-08 18:41:53 +00009000 if (Input.isInvalid()) return ExprError();
9001 if (Input.get()->getValueKind() != VK_RValue &&
9002 Input.get()->getObjectKind() == OK_Ordinary)
9003 VK = Input.get()->getValueKind();
Chris Lattnerdbb36972007-08-24 21:16:53 +00009004 break;
John McCall2de56d12010-08-25 11:45:40 +00009005 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00009006 resultType = Input.get()->getType();
9007 VK = Input.get()->getValueKind();
9008 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00009009 break;
9010 }
John Wiegley429bb272011-04-08 18:41:53 +00009011 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00009012 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009013
John Wiegley429bb272011-04-08 18:41:53 +00009014 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00009015 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00009016}
9017
John McCall60d7b3a2010-08-24 06:29:42 +00009018ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00009019 UnaryOperatorKind Opc,
9020 Expr *Input) {
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00009021 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman957c0942010-09-05 23:15:52 +00009022 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009023 // Find all of the overloaded operators visible from this
9024 // point. We perform both an operator-name lookup from the local
9025 // scope and an argument-dependent lookup based on the types of
9026 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00009027 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009028 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00009029 if (S && OverOp != OO_None)
9030 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9031 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009032
John McCall9ae2f072010-08-23 23:25:46 +00009033 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009034 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009035
John McCall9ae2f072010-08-23 23:25:46 +00009036 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009037}
9038
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009039// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00009040ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00009041 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00009042 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009043}
9044
Steve Naroff1b273c42007-09-16 14:56:35 +00009045/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00009046ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00009047 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00009048 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00009049 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00009050 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009051 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00009052}
9053
John McCall60d7b3a2010-08-24 06:29:42 +00009054ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00009055Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009056 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009057 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9058 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9059
Douglas Gregordd8f5692010-03-10 04:54:39 +00009060 bool isFileScope
9061 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00009062 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00009063 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00009064
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009065 // FIXME: there are a variety of strange constraints to enforce here, for
9066 // example, it is not possible to goto into a stmt expression apparently.
9067 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00009068
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009069 // If there are sub stmts in the compound stmt, take the type of the last one
9070 // as the type of the stmtexpr.
9071 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009072 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009073 if (!Compound->body_empty()) {
9074 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009075 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009076 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009077 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9078 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009079 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009080 }
John Wiegley429bb272011-04-08 18:41:53 +00009081 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00009082 // Do function/array conversion on the last expression, but not
9083 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00009084 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9085 if (LastExpr.isInvalid())
9086 return ExprError();
9087 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00009088
John Wiegley429bb272011-04-08 18:41:53 +00009089 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
9090 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009091 InitializedEntity::InitializeResult(LPLoc,
9092 Ty,
9093 false),
9094 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00009095 LastExpr);
9096 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009097 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009098 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009099 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00009100 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009101 else
John Wiegley429bb272011-04-08 18:41:53 +00009102 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009103 StmtExprMayBindToTemp = true;
9104 }
9105 }
9106 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00009107 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009108
Eli Friedmanb1d796d2009-03-23 00:24:07 +00009109 // FIXME: Check that expression type is complete/non-abstract; statement
9110 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009111 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9112 if (StmtExprMayBindToTemp)
9113 return MaybeBindToTemporary(ResStmtExpr);
9114 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009115}
Steve Naroffd34e9152007-08-01 22:05:33 +00009116
John McCall60d7b3a2010-08-24 06:29:42 +00009117ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009118 TypeSourceInfo *TInfo,
9119 OffsetOfComponent *CompPtr,
9120 unsigned NumComponents,
9121 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009122 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00009123 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009124 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009125
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009126 // We must have at least one component that refers to the type, and the first
9127 // one is known to be a field designator. Verify that the ArgTy represents
9128 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00009129 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009130 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9131 << ArgTy << TypeRange);
9132
9133 // Type must be complete per C99 7.17p3 because a declaring a variable
9134 // with an incomplete type would be ill-formed.
9135 if (!Dependent
9136 && RequireCompleteType(BuiltinLoc, ArgTy,
9137 PDiag(diag::err_offsetof_incomplete_type)
9138 << TypeRange))
9139 return ExprError();
9140
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009141 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9142 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00009143 // FIXME: This diagnostic isn't actually visible because the location is in
9144 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009145 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00009146 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9147 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009148
9149 bool DidWarnAboutNonPOD = false;
9150 QualType CurrentType = ArgTy;
9151 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9152 llvm::SmallVector<OffsetOfNode, 4> Comps;
9153 llvm::SmallVector<Expr*, 4> Exprs;
9154 for (unsigned i = 0; i != NumComponents; ++i) {
9155 const OffsetOfComponent &OC = CompPtr[i];
9156 if (OC.isBrackets) {
9157 // Offset of an array sub-field. TODO: Should we allow vector elements?
9158 if (!CurrentType->isDependentType()) {
9159 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9160 if(!AT)
9161 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9162 << CurrentType);
9163 CurrentType = AT->getElementType();
9164 } else
9165 CurrentType = Context.DependentTy;
9166
9167 // The expression must be an integral expression.
9168 // FIXME: An integral constant expression?
9169 Expr *Idx = static_cast<Expr*>(OC.U.E);
9170 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9171 !Idx->getType()->isIntegerType())
9172 return ExprError(Diag(Idx->getLocStart(),
9173 diag::err_typecheck_subscript_not_integer)
9174 << Idx->getSourceRange());
9175
9176 // Record this array index.
9177 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9178 Exprs.push_back(Idx);
9179 continue;
9180 }
9181
9182 // Offset of a field.
9183 if (CurrentType->isDependentType()) {
9184 // We have the offset of a field, but we can't look into the dependent
9185 // type. Just record the identifier of the field.
9186 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9187 CurrentType = Context.DependentTy;
9188 continue;
9189 }
9190
9191 // We need to have a complete type to look into.
9192 if (RequireCompleteType(OC.LocStart, CurrentType,
9193 diag::err_offsetof_incomplete_type))
9194 return ExprError();
9195
9196 // Look for the designated field.
9197 const RecordType *RC = CurrentType->getAs<RecordType>();
9198 if (!RC)
9199 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9200 << CurrentType);
9201 RecordDecl *RD = RC->getDecl();
9202
9203 // C++ [lib.support.types]p5:
9204 // The macro offsetof accepts a restricted set of type arguments in this
9205 // International Standard. type shall be a POD structure or a POD union
9206 // (clause 9).
9207 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9208 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00009209 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009210 PDiag(diag::warn_offsetof_non_pod_type)
9211 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9212 << CurrentType))
9213 DidWarnAboutNonPOD = true;
9214 }
9215
9216 // Look for the field.
9217 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9218 LookupQualifiedName(R, RD);
9219 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00009220 IndirectFieldDecl *IndirectMemberDecl = 0;
9221 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00009222 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00009223 MemberDecl = IndirectMemberDecl->getAnonField();
9224 }
9225
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009226 if (!MemberDecl)
9227 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9228 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9229 OC.LocEnd));
9230
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009231 // C99 7.17p3:
9232 // (If the specified member is a bit-field, the behavior is undefined.)
9233 //
9234 // We diagnose this as an error.
9235 if (MemberDecl->getBitWidth()) {
9236 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9237 << MemberDecl->getDeclName()
9238 << SourceRange(BuiltinLoc, RParenLoc);
9239 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9240 return ExprError();
9241 }
Eli Friedman19410a72010-08-05 10:11:36 +00009242
9243 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00009244 if (IndirectMemberDecl)
9245 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00009246
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009247 // If the member was found in a base class, introduce OffsetOfNodes for
9248 // the base class indirections.
9249 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9250 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00009251 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009252 CXXBasePath &Path = Paths.front();
9253 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9254 B != BEnd; ++B)
9255 Comps.push_back(OffsetOfNode(B->Base));
9256 }
Eli Friedman19410a72010-08-05 10:11:36 +00009257
Francois Pichet87c2e122010-11-21 06:08:52 +00009258 if (IndirectMemberDecl) {
9259 for (IndirectFieldDecl::chain_iterator FI =
9260 IndirectMemberDecl->chain_begin(),
9261 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9262 assert(isa<FieldDecl>(*FI));
9263 Comps.push_back(OffsetOfNode(OC.LocStart,
9264 cast<FieldDecl>(*FI), OC.LocEnd));
9265 }
9266 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009267 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00009268
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009269 CurrentType = MemberDecl->getType().getNonReferenceType();
9270 }
9271
9272 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9273 TInfo, Comps.data(), Comps.size(),
9274 Exprs.data(), Exprs.size(), RParenLoc));
9275}
Mike Stumpeed9cac2009-02-19 03:04:26 +00009276
John McCall60d7b3a2010-08-24 06:29:42 +00009277ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00009278 SourceLocation BuiltinLoc,
9279 SourceLocation TypeLoc,
9280 ParsedType argty,
9281 OffsetOfComponent *CompPtr,
9282 unsigned NumComponents,
9283 SourceLocation RPLoc) {
9284
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009285 TypeSourceInfo *ArgTInfo;
9286 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
9287 if (ArgTy.isNull())
9288 return ExprError();
9289
Eli Friedman5a15dc12010-08-05 10:15:45 +00009290 if (!ArgTInfo)
9291 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9292
9293 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9294 RPLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009295}
9296
9297
John McCall60d7b3a2010-08-24 06:29:42 +00009298ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009299 Expr *CondExpr,
9300 Expr *LHSExpr, Expr *RHSExpr,
9301 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00009302 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9303
John McCallf89e55a2010-11-18 06:31:45 +00009304 ExprValueKind VK = VK_RValue;
9305 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00009306 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00009307 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00009308 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00009309 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00009310 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00009311 } else {
9312 // The conditional expression is required to be a constant expression.
9313 llvm::APSInt condEval(32);
9314 SourceLocation ExpLoc;
9315 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00009316 return ExprError(Diag(ExpLoc,
9317 diag::err_typecheck_choose_expr_requires_constant)
9318 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00009319
Sebastian Redl28507842009-02-26 14:39:58 +00009320 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00009321 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9322
9323 resType = ActiveExpr->getType();
9324 ValueDependent = ActiveExpr->isValueDependent();
9325 VK = ActiveExpr->getValueKind();
9326 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00009327 }
9328
Sebastian Redlf53597f2009-03-15 17:47:39 +00009329 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00009330 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00009331 resType->isDependentType(),
9332 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00009333}
9334
Steve Naroff4eb206b2008-09-03 18:15:37 +00009335//===----------------------------------------------------------------------===//
9336// Clang Extensions.
9337//===----------------------------------------------------------------------===//
9338
9339/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00009340void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009341 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9342 PushBlockScope(BlockScope, Block);
9343 CurContext->addDecl(Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009344 if (BlockScope)
9345 PushDeclContext(BlockScope, Block);
9346 else
9347 CurContext = Block;
Steve Naroff090276f2008-10-10 01:28:17 +00009348}
9349
Mike Stump98eb8a72009-02-04 22:31:32 +00009350void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00009351 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00009352 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009353 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009354
John McCallbf1a0282010-06-04 23:28:52 +00009355 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00009356 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00009357
John McCall711c52b2011-01-05 12:14:39 +00009358 // GetTypeForDeclarator always produces a function type for a block
9359 // literal signature. Furthermore, it is always a FunctionProtoType
9360 // unless the function was written with a typedef.
9361 assert(T->isFunctionType() &&
9362 "GetTypeForDeclarator made a non-function block signature");
9363
9364 // Look for an explicit signature in that function type.
9365 FunctionProtoTypeLoc ExplicitSignature;
9366
9367 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9368 if (isa<FunctionProtoTypeLoc>(tmp)) {
9369 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9370
9371 // Check whether that explicit signature was synthesized by
9372 // GetTypeForDeclarator. If so, don't save that as part of the
9373 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00009374 if (ExplicitSignature.getLocalRangeBegin() ==
9375 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00009376 // This would be much cheaper if we stored TypeLocs instead of
9377 // TypeSourceInfos.
9378 TypeLoc Result = ExplicitSignature.getResultLoc();
9379 unsigned Size = Result.getFullDataSize();
9380 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9381 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9382
9383 ExplicitSignature = FunctionProtoTypeLoc();
9384 }
John McCall82dc0092010-06-04 11:21:44 +00009385 }
Mike Stump1eb44332009-09-09 15:08:12 +00009386
John McCall711c52b2011-01-05 12:14:39 +00009387 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9388 CurBlock->FunctionType = T;
9389
9390 const FunctionType *Fn = T->getAs<FunctionType>();
9391 QualType RetTy = Fn->getResultType();
9392 bool isVariadic =
9393 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9394
John McCallc71a4912010-06-04 19:02:56 +00009395 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00009396
John McCall82dc0092010-06-04 11:21:44 +00009397 // Don't allow returning a objc interface by value.
9398 if (RetTy->isObjCObjectType()) {
9399 Diag(ParamInfo.getSourceRange().getBegin(),
9400 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9401 return;
9402 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009403
John McCall82dc0092010-06-04 11:21:44 +00009404 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00009405 // return type. TODO: what should we do with declarators like:
9406 // ^ * { ... }
9407 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00009408 if (RetTy != Context.DependentTy)
9409 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009410
John McCall82dc0092010-06-04 11:21:44 +00009411 // Push block parameters from the declarator if we had them.
John McCallc71a4912010-06-04 19:02:56 +00009412 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00009413 if (ExplicitSignature) {
9414 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9415 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009416 if (Param->getIdentifier() == 0 &&
9417 !Param->isImplicit() &&
9418 !Param->isInvalidDecl() &&
9419 !getLangOptions().CPlusPlus)
9420 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00009421 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009422 }
John McCall82dc0092010-06-04 11:21:44 +00009423
9424 // Fake up parameter variables if we have a typedef, like
9425 // ^ fntype { ... }
9426 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9427 for (FunctionProtoType::arg_type_iterator
9428 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9429 ParmVarDecl *Param =
9430 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9431 ParamInfo.getSourceRange().getBegin(),
9432 *I);
John McCallc71a4912010-06-04 19:02:56 +00009433 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00009434 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009435 }
John McCall82dc0092010-06-04 11:21:44 +00009436
John McCallc71a4912010-06-04 19:02:56 +00009437 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00009438 if (!Params.empty()) {
John McCallc71a4912010-06-04 19:02:56 +00009439 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregor82aa7132010-11-01 18:37:59 +00009440 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9441 CurBlock->TheDecl->param_end(),
9442 /*CheckParameterNames=*/false);
9443 }
9444
John McCall82dc0092010-06-04 11:21:44 +00009445 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009446 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00009447
John McCallc71a4912010-06-04 19:02:56 +00009448 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00009449 Diag(ParamInfo.getAttributes()->getLoc(),
9450 diag::warn_attribute_sentinel_not_variadic) << 1;
9451 // FIXME: remove the attribute.
9452 }
9453
9454 // Put the parameter variables in scope. We can bail out immediately
9455 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00009456 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00009457 return;
9458
Steve Naroff090276f2008-10-10 01:28:17 +00009459 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00009460 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9461 (*AI)->setOwningFunction(CurBlock->TheDecl);
9462
Steve Naroff090276f2008-10-10 01:28:17 +00009463 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009464 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009465 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00009466
Steve Naroff090276f2008-10-10 01:28:17 +00009467 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00009468 }
John McCall7a9813c2010-01-22 00:28:27 +00009469 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009470}
9471
9472/// ActOnBlockError - If there is an error parsing a block, this callback
9473/// is invoked to pop the information about the block from the action impl.
9474void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00009475 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00009476 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009477 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009478}
9479
9480/// ActOnBlockStmtExpr - This is called when the body of a block statement
9481/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00009482ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00009483 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00009484 // If blocks are disabled, emit an error.
9485 if (!LangOpts.Blocks)
9486 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00009487
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009488 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009489
Steve Naroff090276f2008-10-10 01:28:17 +00009490 PopDeclContext();
9491
Steve Naroff4eb206b2008-09-03 18:15:37 +00009492 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00009493 if (!BSI->ReturnType.isNull())
9494 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009495
Mike Stump56925862009-07-28 22:04:01 +00009496 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009497 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00009498
John McCall469a1eb2011-02-02 13:00:07 +00009499 // Set the captured variables on the block.
John McCall6b5a61b2011-02-07 10:33:21 +00009500 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
9501 BSI->CapturesCXXThis);
John McCall469a1eb2011-02-02 13:00:07 +00009502
John McCallc71a4912010-06-04 19:02:56 +00009503 // If the user wrote a function type in some form, try to use that.
9504 if (!BSI->FunctionType.isNull()) {
9505 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9506
9507 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9508 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9509
9510 // Turn protoless block types into nullary block types.
9511 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00009512 FunctionProtoType::ExtProtoInfo EPI;
9513 EPI.ExtInfo = Ext;
9514 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009515
9516 // Otherwise, if we don't need to change anything about the function type,
9517 // preserve its sugar structure.
9518 } else if (FTy->getResultType() == RetTy &&
9519 (!NoReturn || FTy->getNoReturnAttr())) {
9520 BlockTy = BSI->FunctionType;
9521
9522 // Otherwise, make the minimal modifications to the function type.
9523 } else {
9524 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00009525 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9526 EPI.TypeQuals = 0; // FIXME: silently?
9527 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00009528 BlockTy = Context.getFunctionType(RetTy,
9529 FPT->arg_type_begin(),
9530 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00009531 EPI);
John McCallc71a4912010-06-04 19:02:56 +00009532 }
9533
9534 // If we don't have a function type, just build one from nothing.
9535 } else {
John McCalle23cf432010-12-14 08:05:40 +00009536 FunctionProtoType::ExtProtoInfo EPI;
Eli Friedmana49218e2011-04-09 08:18:08 +00009537 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, false, 0, CC_Default);
John McCalle23cf432010-12-14 08:05:40 +00009538 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009539 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009540
John McCallc71a4912010-06-04 19:02:56 +00009541 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9542 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00009543 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009544
Chris Lattner17a78302009-04-19 05:28:12 +00009545 // If needed, diagnose invalid gotos and switches in the block.
John McCall781472f2010-08-25 08:40:02 +00009546 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00009547 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00009548
Chris Lattnere476bdc2011-02-17 23:58:47 +00009549 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009550
John McCall469a1eb2011-02-02 13:00:07 +00009551 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCalle0054f62010-08-25 05:56:39 +00009552
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00009553 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9554 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009555 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00009556}
9557
John McCall60d7b3a2010-08-24 06:29:42 +00009558ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallb3d87482010-08-24 05:47:05 +00009559 Expr *expr, ParsedType type,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009560 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009561 TypeSourceInfo *TInfo;
Jeffrey Yasskindec09842011-01-18 02:00:16 +00009562 GetTypeFromParser(type, &TInfo);
John McCall9ae2f072010-08-23 23:25:46 +00009563 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009564}
9565
John McCall60d7b3a2010-08-24 06:29:42 +00009566ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00009567 Expr *E, TypeSourceInfo *TInfo,
9568 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009569 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00009570
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009571 // Get the va_list type
9572 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009573 if (VaListType->isArrayType()) {
9574 // Deal with implicit array decay; for example, on x86-64,
9575 // va_list is an array, but it's supposed to decay to
9576 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009577 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00009578 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00009579 ExprResult Result = UsualUnaryConversions(E);
9580 if (Result.isInvalid())
9581 return ExprError();
9582 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009583 } else {
9584 // Otherwise, the va_list argument must be an l-value because
9585 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00009586 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00009587 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00009588 return ExprError();
9589 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009590
Douglas Gregordd027302009-05-19 23:10:31 +00009591 if (!E->isTypeDependent() &&
9592 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00009593 return ExprError(Diag(E->getLocStart(),
9594 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009595 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00009596 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009597
Eli Friedmanb1d796d2009-03-23 00:24:07 +00009598 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00009599 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00009600
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009601 QualType T = TInfo->getType().getNonLValueExprType(Context);
9602 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00009603}
9604
John McCall60d7b3a2010-08-24 06:29:42 +00009605ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009606 // The type of __null will be int or long, depending on the size of
9607 // pointers on the target.
9608 QualType Ty;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009609 unsigned pw = Context.Target.getPointerWidth(0);
9610 if (pw == Context.Target.getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009611 Ty = Context.IntTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009612 else if (pw == Context.Target.getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009613 Ty = Context.LongTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009614 else if (pw == Context.Target.getLongLongWidth())
9615 Ty = Context.LongLongTy;
9616 else {
9617 assert(!"I don't know size of pointer!");
9618 Ty = Context.IntTy;
9619 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009620
Sebastian Redlf53597f2009-03-15 17:47:39 +00009621 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009622}
9623
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009624static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00009625 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009626 if (!SemaRef.getLangOptions().ObjC1)
9627 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009628
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009629 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9630 if (!PT)
9631 return;
9632
9633 // Check if the destination is of type 'id'.
9634 if (!PT->isObjCIdType()) {
9635 // Check if the destination is the 'NSString' interface.
9636 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9637 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9638 return;
9639 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009640
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009641 // Strip off any parens and casts.
9642 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
9643 if (!SL || SL->isWide())
9644 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009645
Douglas Gregor849b2432010-03-31 17:46:05 +00009646 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009647}
9648
Chris Lattner5cf216b2008-01-04 18:04:52 +00009649bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9650 SourceLocation Loc,
9651 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00009652 Expr *SrcExpr, AssignmentAction Action,
9653 bool *Complained) {
9654 if (Complained)
9655 *Complained = false;
9656
Chris Lattner5cf216b2008-01-04 18:04:52 +00009657 // Decode the result (notice that AST's are still created for extensions).
9658 bool isInvalid = false;
9659 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00009660 FixItHint Hint;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009661
Chris Lattner5cf216b2008-01-04 18:04:52 +00009662 switch (ConvTy) {
9663 default: assert(0 && "Unknown conversion type");
9664 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009665 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00009666 DiagKind = diag::ext_typecheck_convert_pointer_int;
9667 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009668 case IntToPointer:
9669 DiagKind = diag::ext_typecheck_convert_int_pointer;
9670 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009671 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00009672 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009673 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9674 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009675 case IncompatiblePointerSign:
9676 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9677 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009678 case FunctionVoidPointer:
9679 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9680 break;
John McCall86c05f32011-02-01 00:10:29 +00009681 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009682 // Perform array-to-pointer decay if necessary.
9683 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9684
John McCall86c05f32011-02-01 00:10:29 +00009685 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9686 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9687 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9688 DiagKind = diag::err_typecheck_incompatible_address_space;
9689 break;
9690 }
9691
9692 llvm_unreachable("unknown error case for discarding qualifiers!");
9693 // fallthrough
9694 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009695 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009696 // If the qualifiers lost were because we were applying the
9697 // (deprecated) C++ conversion from a string literal to a char*
9698 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9699 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009700 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009701 // bit of refactoring (so that the second argument is an
9702 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009703 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009704 // C++ semantics.
9705 if (getLangOptions().CPlusPlus &&
9706 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9707 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009708 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9709 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009710 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009711 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009712 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009713 case IntToBlockPointer:
9714 DiagKind = diag::err_int_to_block_pointer;
9715 break;
9716 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009717 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009718 break;
Steve Naroff39579072008-10-14 22:18:38 +00009719 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009720 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009721 // it can give a more specific diagnostic.
9722 DiagKind = diag::warn_incompatible_qualified_id;
9723 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009724 case IncompatibleVectors:
9725 DiagKind = diag::warn_incompatible_vectors;
9726 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009727 case Incompatible:
9728 DiagKind = diag::err_typecheck_convert_incompatible;
9729 isInvalid = true;
9730 break;
9731 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009732
Douglas Gregord4eea832010-04-09 00:35:39 +00009733 QualType FirstType, SecondType;
9734 switch (Action) {
9735 case AA_Assigning:
9736 case AA_Initializing:
9737 // The destination type comes first.
9738 FirstType = DstType;
9739 SecondType = SrcType;
9740 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009741
Douglas Gregord4eea832010-04-09 00:35:39 +00009742 case AA_Returning:
9743 case AA_Passing:
9744 case AA_Converting:
9745 case AA_Sending:
9746 case AA_Casting:
9747 // The source type comes first.
9748 FirstType = SrcType;
9749 SecondType = DstType;
9750 break;
9751 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009752
Douglas Gregord4eea832010-04-09 00:35:39 +00009753 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009754 << SrcExpr->getSourceRange() << Hint;
Douglas Gregora41a8c52010-04-22 00:20:18 +00009755 if (Complained)
9756 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009757 return isInvalid;
9758}
Anders Carlssone21555e2008-11-30 19:50:32 +00009759
Chris Lattner3bf68932009-04-25 21:59:05 +00009760bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009761 llvm::APSInt ICEResult;
9762 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9763 if (Result)
9764 *Result = ICEResult;
9765 return false;
9766 }
9767
Anders Carlssone21555e2008-11-30 19:50:32 +00009768 Expr::EvalResult EvalResult;
9769
Mike Stumpeed9cac2009-02-19 03:04:26 +00009770 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00009771 EvalResult.HasSideEffects) {
9772 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9773
9774 if (EvalResult.Diag) {
9775 // We only show the note if it's not the usual "invalid subexpression"
9776 // or if it's actually in a subexpression.
9777 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9778 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9779 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9780 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009781
Anders Carlssone21555e2008-11-30 19:50:32 +00009782 return true;
9783 }
9784
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009785 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9786 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00009787
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009788 if (EvalResult.Diag &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009789 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9790 != Diagnostic::Ignored)
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009791 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009792
Anders Carlssone21555e2008-11-30 19:50:32 +00009793 if (Result)
9794 *Result = EvalResult.Val.getInt();
9795 return false;
9796}
Douglas Gregore0762c92009-06-19 23:52:42 +00009797
Douglas Gregor2afce722009-11-26 00:44:06 +00009798void
Mike Stump1eb44332009-09-09 15:08:12 +00009799Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009800 ExprEvalContexts.push_back(
9801 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00009802}
9803
Mike Stump1eb44332009-09-09 15:08:12 +00009804void
Douglas Gregor2afce722009-11-26 00:44:06 +00009805Sema::PopExpressionEvaluationContext() {
9806 // Pop the current expression evaluation context off the stack.
9807 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9808 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009809
Douglas Gregor06d33692009-12-12 07:57:52 +00009810 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9811 if (Rec.PotentiallyReferenced) {
9812 // Mark any remaining declarations in the current position of the stack
9813 // as "referenced". If they were not meant to be referenced, semantic
9814 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009815 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00009816 I = Rec.PotentiallyReferenced->begin(),
9817 IEnd = Rec.PotentiallyReferenced->end();
9818 I != IEnd; ++I)
9819 MarkDeclarationReferenced(I->first, I->second);
9820 }
9821
9822 if (Rec.PotentiallyDiagnosed) {
9823 // Emit any pending diagnostics.
9824 for (PotentiallyEmittedDiagnostics::iterator
9825 I = Rec.PotentiallyDiagnosed->begin(),
9826 IEnd = Rec.PotentiallyDiagnosed->end();
9827 I != IEnd; ++I)
9828 Diag(I->first, I->second);
9829 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009830 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009831
9832 // When are coming out of an unevaluated context, clear out any
9833 // temporaries that we may have created as part of the evaluation of
9834 // the expression in that context: they aren't relevant because they
9835 // will never be constructed.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009836 if (Rec.Context == Unevaluated &&
Douglas Gregor2afce722009-11-26 00:44:06 +00009837 ExprTemporaries.size() > Rec.NumTemporaries)
9838 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9839 ExprTemporaries.end());
9840
9841 // Destroy the popped expression evaluation record.
9842 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009843}
Douglas Gregore0762c92009-06-19 23:52:42 +00009844
9845/// \brief Note that the given declaration was referenced in the source code.
9846///
9847/// This routine should be invoke whenever a given declaration is referenced
9848/// in the source code, and where that reference occurred. If this declaration
9849/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9850/// C99 6.9p3), then the declaration will be marked as used.
9851///
9852/// \param Loc the location where the declaration was referenced.
9853///
9854/// \param D the declaration that has been referenced by the source code.
9855void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9856 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00009857
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +00009858 D->setReferenced();
9859
Douglas Gregorc070cc62010-06-17 23:14:26 +00009860 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009861 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009862
Douglas Gregorb5352cf2009-10-08 21:35:42 +00009863 // Mark a parameter or variable declaration "used", regardless of whether we're in a
9864 // template or not. The reason for this is that unevaluated expressions
9865 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9866 // -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009867 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009868 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson2127ecc2010-10-22 23:37:08 +00009869 D->setUsed();
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009870 return;
9871 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009872
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009873 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9874 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009875
Douglas Gregore0762c92009-06-19 23:52:42 +00009876 // Do not mark anything as "used" within a dependent context; wait for
9877 // an instantiation.
9878 if (CurContext->isDependentContext())
9879 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009880
Douglas Gregor2afce722009-11-26 00:44:06 +00009881 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00009882 case Unevaluated:
9883 // We are in an expression that is not potentially evaluated; do nothing.
9884 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009885
Douglas Gregorac7610d2009-06-22 20:57:11 +00009886 case PotentiallyEvaluated:
9887 // We are in a potentially-evaluated expression, so this declaration is
9888 // "used"; handle this below.
9889 break;
Mike Stump1eb44332009-09-09 15:08:12 +00009890
Douglas Gregorac7610d2009-06-22 20:57:11 +00009891 case PotentiallyPotentiallyEvaluated:
9892 // We are in an expression that may be potentially evaluated; queue this
9893 // declaration reference until we know whether the expression is
9894 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00009895 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00009896 return;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009897
9898 case PotentiallyEvaluatedIfUsed:
9899 // Referenced declarations will only be used if the construct in the
9900 // containing expression is used.
9901 return;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009902 }
Mike Stump1eb44332009-09-09 15:08:12 +00009903
Douglas Gregore0762c92009-06-19 23:52:42 +00009904 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00009905 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009906 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00009907 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00009908 if (Constructor->getParent()->hasTrivialConstructor())
9909 return;
9910 if (!Constructor->isUsed(false))
9911 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00009912 } else if (Constructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00009913 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009914 if (!Constructor->isUsed(false))
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009915 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
9916 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009917
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009918 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009919 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009920 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009921 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009922 if (Destructor->isVirtual())
9923 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009924 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9925 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
9926 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009927 if (!MethodDecl->isUsed(false))
Douglas Gregor39957dc2010-05-01 15:04:51 +00009928 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009929 } else if (MethodDecl->isVirtual())
9930 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009931 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00009932 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall15e310a2011-02-19 02:53:41 +00009933 // Recursive functions should be marked when used from another function.
9934 if (CurContext == Function) return;
9935
Mike Stump1eb44332009-09-09 15:08:12 +00009936 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00009937 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00009938 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009939 bool AlreadyInstantiated = false;
9940 if (FunctionTemplateSpecializationInfo *SpecInfo
9941 = Function->getTemplateSpecializationInfo()) {
9942 if (SpecInfo->getPointOfInstantiation().isInvalid())
9943 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009944 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009945 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009946 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009947 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009948 = Function->getMemberSpecializationInfo()) {
9949 if (MSInfo->getPointOfInstantiation().isInvalid())
9950 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009951 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009952 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009953 AlreadyInstantiated = true;
9954 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009955
Douglas Gregor60406be2010-01-16 22:29:39 +00009956 if (!AlreadyInstantiated) {
9957 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9958 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9959 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9960 Loc));
9961 else
Chandler Carruth62c78d52010-08-25 08:44:16 +00009962 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor60406be2010-01-16 22:29:39 +00009963 }
John McCall15e310a2011-02-19 02:53:41 +00009964 } else {
9965 // Walk redefinitions, as some of them may be instantiable.
Gabor Greif40181c42010-08-28 00:16:06 +00009966 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9967 e(Function->redecls_end()); i != e; ++i) {
Gabor Greifbe9ebe32010-08-28 01:58:12 +00009968 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greif40181c42010-08-28 00:16:06 +00009969 MarkDeclarationReferenced(Loc, *i);
9970 }
John McCall15e310a2011-02-19 02:53:41 +00009971 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009972
John McCall15e310a2011-02-19 02:53:41 +00009973 // Keep track of used but undefined functions.
9974 if (!Function->isPure() && !Function->hasBody() &&
9975 Function->getLinkage() != ExternalLinkage) {
9976 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9977 if (old.isInvalid()) old = Loc;
9978 }
Argyrios Kyrtzidis58b52592010-08-25 10:34:54 +00009979
John McCall15e310a2011-02-19 02:53:41 +00009980 Function->setUsed(true);
Douglas Gregore0762c92009-06-19 23:52:42 +00009981 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009982 }
Mike Stump1eb44332009-09-09 15:08:12 +00009983
Douglas Gregore0762c92009-06-19 23:52:42 +00009984 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00009985 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00009986 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009987 Var->getInstantiatedFromStaticDataMember()) {
9988 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9989 assert(MSInfo && "Missing member specialization information?");
9990 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9991 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9992 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth62c78d52010-08-25 08:44:16 +00009993 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009994 }
9995 }
Mike Stump1eb44332009-09-09 15:08:12 +00009996
John McCall77efc682011-02-21 19:25:48 +00009997 // Keep track of used but undefined variables. We make a hole in
9998 // the warning for static const data members with in-line
9999 // initializers.
John McCall15e310a2011-02-19 02:53:41 +000010000 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall77efc682011-02-21 19:25:48 +000010001 && Var->getLinkage() != ExternalLinkage
10002 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall15e310a2011-02-19 02:53:41 +000010003 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
10004 if (old.isInvalid()) old = Loc;
10005 }
Douglas Gregor7caa6822009-07-24 20:34:43 +000010006
Douglas Gregore0762c92009-06-19 23:52:42 +000010007 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +000010008 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +000010009 }
Douglas Gregore0762c92009-06-19 23:52:42 +000010010}
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010011
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010012namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010013 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010014 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010015 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010016 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10017 Sema &S;
10018 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010019
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010020 public:
10021 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010022
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010023 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010024
10025 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10026 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010027 };
10028}
10029
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010030bool MarkReferencedDecls::TraverseTemplateArgument(
10031 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010032 if (Arg.getKind() == TemplateArgument::Declaration) {
10033 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
10034 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010035
10036 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010037}
10038
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010039bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010040 if (ClassTemplateSpecializationDecl *Spec
10041 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10042 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +000010043 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010044 }
10045
Chandler Carruthe3e210c2010-06-10 10:31:57 +000010046 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010047}
10048
10049void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10050 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010051 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010052}
10053
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010054namespace {
10055 /// \brief Helper class that marks all of the declarations referenced by
10056 /// potentially-evaluated subexpressions as "referenced".
10057 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10058 Sema &S;
10059
10060 public:
10061 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
10062
10063 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
10064
10065 void VisitDeclRefExpr(DeclRefExpr *E) {
10066 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10067 }
10068
10069 void VisitMemberExpr(MemberExpr *E) {
10070 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010071 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010072 }
10073
10074 void VisitCXXNewExpr(CXXNewExpr *E) {
10075 if (E->getConstructor())
10076 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
10077 if (E->getOperatorNew())
10078 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
10079 if (E->getOperatorDelete())
10080 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010081 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010082 }
10083
10084 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
10085 if (E->getOperatorDelete())
10086 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +000010087 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
10088 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10089 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10090 S.MarkDeclarationReferenced(E->getLocStart(),
10091 S.LookupDestructor(Record));
10092 }
10093
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010094 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010095 }
10096
10097 void VisitCXXConstructExpr(CXXConstructExpr *E) {
10098 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010099 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010100 }
10101
10102 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
10103 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10104 }
Douglas Gregor102ff972010-10-19 17:17:35 +000010105
10106 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10107 Visit(E->getExpr());
10108 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010109 };
10110}
10111
10112/// \brief Mark any declarations that appear within this expression or any
10113/// potentially-evaluated subexpressions as "referenced".
10114void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
10115 EvaluatedExprMarker(*this).Visit(E);
10116}
10117
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010118/// \brief Emit a diagnostic that describes an effect on the run-time behavior
10119/// of the program being compiled.
10120///
10121/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010122/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010123/// possibility that the code will actually be executable. Code in sizeof()
10124/// expressions, code used only during overload resolution, etc., are not
10125/// potentially evaluated. This routine will suppress such diagnostics or,
10126/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010127/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010128/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010129///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010130/// This routine should be used for all diagnostics that describe the run-time
10131/// behavior of a program, such as passing a non-POD value through an ellipsis.
10132/// Failure to do so will likely result in spurious diagnostics or failures
10133/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek762696f2011-02-23 01:51:43 +000010134bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010135 const PartialDiagnostic &PD) {
10136 switch (ExprEvalContexts.back().Context ) {
10137 case Unevaluated:
10138 // The argument will never be evaluated, so don't complain.
10139 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010140
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010141 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010142 case PotentiallyEvaluatedIfUsed:
Ted Kremenek351ba912011-02-23 01:52:04 +000010143 if (stmt && getCurFunctionOrMethodDecl()) {
10144 FunctionScopes.back()->PossiblyUnreachableDiags.
10145 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
10146 }
10147 else
10148 Diag(Loc, PD);
10149
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010150 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010151
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010152 case PotentiallyPotentiallyEvaluated:
10153 ExprEvalContexts.back().addDiagnostic(Loc, PD);
10154 break;
10155 }
10156
10157 return false;
10158}
10159
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010160bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
10161 CallExpr *CE, FunctionDecl *FD) {
10162 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
10163 return false;
10164
10165 PartialDiagnostic Note =
10166 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
10167 << FD->getDeclName() : PDiag();
10168 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010169
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010170 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010171 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010172 PDiag(diag::err_call_function_incomplete_return)
10173 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010174 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010175 << CE->getSourceRange(),
10176 std::make_pair(NoteLoc, Note)))
10177 return true;
10178
10179 return false;
10180}
10181
Douglas Gregor92c3a042011-01-19 16:50:08 +000010182// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +000010183// will prevent this condition from triggering, which is what we want.
10184void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
10185 SourceLocation Loc;
10186
John McCalla52ef082009-11-11 02:41:58 +000010187 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +000010188 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +000010189
John McCall5a881bb2009-10-12 21:59:07 +000010190 if (isa<BinaryOperator>(E)) {
10191 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +000010192 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +000010193 return;
10194
Douglas Gregor92c3a042011-01-19 16:50:08 +000010195 IsOrAssign = Op->getOpcode() == BO_OrAssign;
10196
John McCallc8d8ac52009-11-12 00:06:05 +000010197 // Greylist some idioms by putting them into a warning subcategory.
10198 if (ObjCMessageExpr *ME
10199 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
10200 Selector Sel = ME->getSelector();
10201
John McCallc8d8ac52009-11-12 00:06:05 +000010202 // self = [<foo> init...]
Douglas Gregor813d8342011-02-18 22:29:55 +000010203 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +000010204 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10205
10206 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +000010207 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +000010208 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10209 }
John McCalla52ef082009-11-11 02:41:58 +000010210
John McCall5a881bb2009-10-12 21:59:07 +000010211 Loc = Op->getOperatorLoc();
10212 } else if (isa<CXXOperatorCallExpr>(E)) {
10213 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +000010214 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +000010215 return;
10216
Douglas Gregor92c3a042011-01-19 16:50:08 +000010217 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +000010218 Loc = Op->getOperatorLoc();
10219 } else {
10220 // Not an assignment.
10221 return;
10222 }
10223
Douglas Gregor55b38842010-04-14 16:09:52 +000010224 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +000010225
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000010226 SourceLocation Open = E->getSourceRange().getBegin();
10227 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
10228 Diag(Loc, diag::note_condition_assign_silence)
10229 << FixItHint::CreateInsertion(Open, "(")
10230 << FixItHint::CreateInsertion(Close, ")");
10231
Douglas Gregor92c3a042011-01-19 16:50:08 +000010232 if (IsOrAssign)
10233 Diag(Loc, diag::note_condition_or_assign_to_comparison)
10234 << FixItHint::CreateReplacement(Loc, "!=");
10235 else
10236 Diag(Loc, diag::note_condition_assign_to_comparison)
10237 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +000010238}
10239
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010240/// \brief Redundant parentheses over an equality comparison can indicate
10241/// that the user intended an assignment used as condition.
10242void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000010243 // Don't warn if the parens came from a macro.
10244 SourceLocation parenLoc = parenE->getLocStart();
10245 if (parenLoc.isInvalid() || parenLoc.isMacroID())
10246 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000010247 // Don't warn for dependent expressions.
10248 if (parenE->isTypeDependent())
10249 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000010250
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010251 Expr *E = parenE->IgnoreParens();
10252
10253 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +000010254 if (opE->getOpcode() == BO_EQ &&
10255 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
10256 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010257 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +000010258
Ted Kremenekf7275cd2011-02-02 02:20:30 +000010259 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +000010260 Diag(Loc, diag::note_equality_comparison_silence)
10261 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
10262 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000010263 Diag(Loc, diag::note_equality_comparison_to_assign)
10264 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010265 }
10266}
10267
John Wiegley429bb272011-04-08 18:41:53 +000010268ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +000010269 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010270 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
10271 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +000010272
John McCall864c0412011-04-26 20:42:42 +000010273 ExprResult result = CheckPlaceholderExpr(E);
10274 if (result.isInvalid()) return ExprError();
10275 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +000010276
John McCall864c0412011-04-26 20:42:42 +000010277 if (!E->isTypeDependent()) {
John McCallf6a16482010-12-04 03:47:34 +000010278 if (getLangOptions().CPlusPlus)
10279 return CheckCXXBooleanCondition(E); // C++ 6.4p4
10280
John Wiegley429bb272011-04-08 18:41:53 +000010281 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
10282 if (ERes.isInvalid())
10283 return ExprError();
10284 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +000010285
10286 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +000010287 if (!T->isScalarType()) { // C99 6.8.4.1p1
10288 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
10289 << T << E->getSourceRange();
10290 return ExprError();
10291 }
John McCall5a881bb2009-10-12 21:59:07 +000010292 }
10293
John Wiegley429bb272011-04-08 18:41:53 +000010294 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +000010295}
Douglas Gregor586596f2010-05-06 17:25:47 +000010296
John McCall60d7b3a2010-08-24 06:29:42 +000010297ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
10298 Expr *Sub) {
Douglas Gregoreecf38f2010-05-06 21:39:56 +000010299 if (!Sub)
Douglas Gregor586596f2010-05-06 17:25:47 +000010300 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010301
10302 return CheckBooleanCondition(Sub, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +000010303}
John McCall2a984ca2010-10-12 00:20:44 +000010304
John McCall1de4d4e2011-04-07 08:22:57 +000010305namespace {
John McCall755d8492011-04-12 00:42:48 +000010306 /// A visitor for rebuilding a call to an __unknown_any expression
10307 /// to have an appropriate type.
10308 struct RebuildUnknownAnyFunction
10309 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
10310
10311 Sema &S;
10312
10313 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
10314
10315 ExprResult VisitStmt(Stmt *S) {
10316 llvm_unreachable("unexpected statement!");
10317 return ExprError();
10318 }
10319
10320 ExprResult VisitExpr(Expr *expr) {
10321 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
10322 << expr->getSourceRange();
10323 return ExprError();
10324 }
10325
10326 /// Rebuild an expression which simply semantically wraps another
10327 /// expression which it shares the type and value kind of.
10328 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10329 ExprResult subResult = Visit(expr->getSubExpr());
10330 if (subResult.isInvalid()) return ExprError();
10331
10332 Expr *subExpr = subResult.take();
10333 expr->setSubExpr(subExpr);
10334 expr->setType(subExpr->getType());
10335 expr->setValueKind(subExpr->getValueKind());
10336 assert(expr->getObjectKind() == OK_Ordinary);
10337 return expr;
10338 }
10339
10340 ExprResult VisitParenExpr(ParenExpr *paren) {
10341 return rebuildSugarExpr(paren);
10342 }
10343
10344 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10345 return rebuildSugarExpr(op);
10346 }
10347
10348 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10349 ExprResult subResult = Visit(op->getSubExpr());
10350 if (subResult.isInvalid()) return ExprError();
10351
10352 Expr *subExpr = subResult.take();
10353 op->setSubExpr(subExpr);
10354 op->setType(S.Context.getPointerType(subExpr->getType()));
10355 assert(op->getValueKind() == VK_RValue);
10356 assert(op->getObjectKind() == OK_Ordinary);
10357 return op;
10358 }
10359
10360 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
10361 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
10362
10363 expr->setType(decl->getType());
10364
10365 assert(expr->getValueKind() == VK_RValue);
10366 if (S.getLangOptions().CPlusPlus &&
10367 !(isa<CXXMethodDecl>(decl) &&
10368 cast<CXXMethodDecl>(decl)->isInstance()))
10369 expr->setValueKind(VK_LValue);
10370
10371 return expr;
10372 }
10373
10374 ExprResult VisitMemberExpr(MemberExpr *mem) {
10375 return resolveDecl(mem, mem->getMemberDecl());
10376 }
10377
10378 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
10379 return resolveDecl(ref, ref->getDecl());
10380 }
10381 };
10382}
10383
10384/// Given a function expression of unknown-any type, try to rebuild it
10385/// to have a function type.
10386static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
10387 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
10388 if (result.isInvalid()) return ExprError();
10389 return S.DefaultFunctionArrayConversion(result.take());
10390}
10391
10392namespace {
John McCall379b5152011-04-11 07:02:50 +000010393 /// A visitor for rebuilding an expression of type __unknown_anytype
10394 /// into one which resolves the type directly on the referring
10395 /// expression. Strict preservation of the original source
10396 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +000010397 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +000010398 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +000010399
10400 Sema &S;
10401
10402 /// The current destination type.
10403 QualType DestType;
10404
10405 RebuildUnknownAnyExpr(Sema &S, QualType castType)
10406 : S(S), DestType(castType) {}
10407
John McCalla5fc4722011-04-09 22:50:59 +000010408 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +000010409 llvm_unreachable("unexpected statement!");
John McCalla5fc4722011-04-09 22:50:59 +000010410 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000010411 }
10412
John McCall379b5152011-04-11 07:02:50 +000010413 ExprResult VisitExpr(Expr *expr) {
10414 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10415 << expr->getSourceRange();
10416 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000010417 }
10418
John McCall379b5152011-04-11 07:02:50 +000010419 ExprResult VisitCallExpr(CallExpr *call);
10420 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
10421
John McCalla5fc4722011-04-09 22:50:59 +000010422 /// Rebuild an expression which simply semantically wraps another
10423 /// expression which it shares the type and value kind of.
10424 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10425 ExprResult subResult = Visit(expr->getSubExpr());
John McCall755d8492011-04-12 00:42:48 +000010426 if (subResult.isInvalid()) return ExprError();
John McCalla5fc4722011-04-09 22:50:59 +000010427 Expr *subExpr = subResult.take();
10428 expr->setSubExpr(subExpr);
10429 expr->setType(subExpr->getType());
10430 expr->setValueKind(subExpr->getValueKind());
10431 assert(expr->getObjectKind() == OK_Ordinary);
10432 return expr;
10433 }
John McCall1de4d4e2011-04-07 08:22:57 +000010434
John McCalla5fc4722011-04-09 22:50:59 +000010435 ExprResult VisitParenExpr(ParenExpr *paren) {
10436 return rebuildSugarExpr(paren);
10437 }
10438
10439 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10440 return rebuildSugarExpr(op);
10441 }
10442
John McCall755d8492011-04-12 00:42:48 +000010443 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10444 const PointerType *ptr = DestType->getAs<PointerType>();
10445 if (!ptr) {
10446 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
10447 << op->getSourceRange();
10448 return ExprError();
10449 }
10450 assert(op->getValueKind() == VK_RValue);
10451 assert(op->getObjectKind() == OK_Ordinary);
10452 op->setType(DestType);
10453
10454 // Build the sub-expression as if it were an object of the pointee type.
10455 DestType = ptr->getPointeeType();
10456 ExprResult subResult = Visit(op->getSubExpr());
10457 if (subResult.isInvalid()) return ExprError();
10458 op->setSubExpr(subResult.take());
10459 return op;
10460 }
10461
John McCall379b5152011-04-11 07:02:50 +000010462 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCalla5fc4722011-04-09 22:50:59 +000010463
John McCall755d8492011-04-12 00:42:48 +000010464 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCalla5fc4722011-04-09 22:50:59 +000010465
John McCall755d8492011-04-12 00:42:48 +000010466 ExprResult VisitMemberExpr(MemberExpr *mem) {
10467 return resolveDecl(mem, mem->getMemberDecl());
10468 }
John McCalla5fc4722011-04-09 22:50:59 +000010469
10470 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall379b5152011-04-11 07:02:50 +000010471 return resolveDecl(ref, ref->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +000010472 }
10473 };
10474}
10475
John McCall379b5152011-04-11 07:02:50 +000010476/// Rebuilds a call expression which yielded __unknown_anytype.
10477ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
10478 Expr *callee = call->getCallee();
10479
10480 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +000010481 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +000010482 FK_FunctionPointer,
10483 FK_BlockPointer
10484 };
10485
10486 FnKind kind;
10487 QualType type = callee->getType();
John McCallf5307512011-04-27 00:36:17 +000010488 if (type == S.Context.BoundMemberTy) {
10489 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
10490 kind = FK_MemberFunction;
10491 type = Expr::findBoundMemberType(callee);
John McCall379b5152011-04-11 07:02:50 +000010492 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
10493 type = ptr->getPointeeType();
10494 kind = FK_FunctionPointer;
10495 } else {
10496 type = type->castAs<BlockPointerType>()->getPointeeType();
10497 kind = FK_BlockPointer;
10498 }
10499 const FunctionType *fnType = type->castAs<FunctionType>();
10500
10501 // Verify that this is a legal result type of a function.
10502 if (DestType->isArrayType() || DestType->isFunctionType()) {
10503 unsigned diagID = diag::err_func_returning_array_function;
10504 if (kind == FK_BlockPointer)
10505 diagID = diag::err_block_returning_array_function;
10506
10507 S.Diag(call->getExprLoc(), diagID)
10508 << DestType->isFunctionType() << DestType;
10509 return ExprError();
10510 }
10511
10512 // Otherwise, go ahead and set DestType as the call's result.
10513 call->setType(DestType.getNonLValueExprType(S.Context));
10514 call->setValueKind(Expr::getValueKindForType(DestType));
10515 assert(call->getObjectKind() == OK_Ordinary);
10516
10517 // Rebuild the function type, replacing the result type with DestType.
10518 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
10519 DestType = S.Context.getFunctionType(DestType,
10520 proto->arg_type_begin(),
10521 proto->getNumArgs(),
10522 proto->getExtProtoInfo());
10523 else
10524 DestType = S.Context.getFunctionNoProtoType(DestType,
10525 fnType->getExtInfo());
10526
10527 // Rebuild the appropriate pointer-to-function type.
10528 switch (kind) {
John McCallf5307512011-04-27 00:36:17 +000010529 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +000010530 // Nothing to do.
10531 break;
10532
10533 case FK_FunctionPointer:
10534 DestType = S.Context.getPointerType(DestType);
10535 break;
10536
10537 case FK_BlockPointer:
10538 DestType = S.Context.getBlockPointerType(DestType);
10539 break;
10540 }
10541
10542 // Finally, we can recurse.
10543 ExprResult calleeResult = Visit(callee);
10544 if (!calleeResult.isUsable()) return ExprError();
10545 call->setCallee(calleeResult.take());
10546
10547 // Bind a temporary if necessary.
10548 return S.MaybeBindToTemporary(call);
10549}
10550
10551ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall755d8492011-04-12 00:42:48 +000010552 ObjCMethodDecl *method = msg->getMethodDecl();
10553 assert(method && "__unknown_anytype message without result type?");
John McCall379b5152011-04-11 07:02:50 +000010554
John McCall755d8492011-04-12 00:42:48 +000010555 // Verify that this is a legal result type of a call.
10556 if (DestType->isArrayType() || DestType->isFunctionType()) {
10557 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
10558 << DestType->isFunctionType() << DestType;
10559 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000010560 }
10561
John McCall755d8492011-04-12 00:42:48 +000010562 assert(method->getResultType() == S.Context.UnknownAnyTy);
10563 method->setResultType(DestType);
10564
John McCall379b5152011-04-11 07:02:50 +000010565 // Change the type of the message.
John McCall755d8492011-04-12 00:42:48 +000010566 msg->setType(DestType.getNonReferenceType());
10567 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +000010568
John McCall755d8492011-04-12 00:42:48 +000010569 return S.MaybeBindToTemporary(msg);
John McCall379b5152011-04-11 07:02:50 +000010570}
10571
10572ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall755d8492011-04-12 00:42:48 +000010573 // The only case we should ever see here is a function-to-pointer decay.
John McCall379b5152011-04-11 07:02:50 +000010574 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall379b5152011-04-11 07:02:50 +000010575 assert(ice->getValueKind() == VK_RValue);
10576 assert(ice->getObjectKind() == OK_Ordinary);
10577
John McCall755d8492011-04-12 00:42:48 +000010578 ice->setType(DestType);
10579
John McCall379b5152011-04-11 07:02:50 +000010580 // Rebuild the sub-expression as the pointee (function) type.
10581 DestType = DestType->castAs<PointerType>()->getPointeeType();
10582
10583 ExprResult result = Visit(ice->getSubExpr());
10584 if (!result.isUsable()) return ExprError();
10585
10586 ice->setSubExpr(result.take());
10587 return S.Owned(ice);
10588}
10589
John McCall755d8492011-04-12 00:42:48 +000010590ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall379b5152011-04-11 07:02:50 +000010591 ExprValueKind valueKind = VK_LValue;
John McCall379b5152011-04-11 07:02:50 +000010592 QualType type = DestType;
10593
10594 // We know how to make this work for certain kinds of decls:
10595
10596 // - functions
John McCall755d8492011-04-12 00:42:48 +000010597 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCall379b5152011-04-11 07:02:50 +000010598 // This is true because FunctionDecls must always have function
10599 // type, so we can't be resolving the entire thing at once.
10600 assert(type->isFunctionType());
10601
John McCallf5307512011-04-27 00:36:17 +000010602 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
10603 if (method->isInstance()) {
10604 valueKind = VK_RValue;
10605 type = S.Context.BoundMemberTy;
10606 }
10607
John McCall379b5152011-04-11 07:02:50 +000010608 // Function references aren't l-values in C.
10609 if (!S.getLangOptions().CPlusPlus)
10610 valueKind = VK_RValue;
10611
10612 // - variables
10613 } else if (isa<VarDecl>(decl)) {
John McCall755d8492011-04-12 00:42:48 +000010614 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
10615 type = refTy->getPointeeType();
John McCall379b5152011-04-11 07:02:50 +000010616 } else if (type->isFunctionType()) {
John McCall755d8492011-04-12 00:42:48 +000010617 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
10618 << decl << expr->getSourceRange();
10619 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000010620 }
10621
10622 // - nothing else
10623 } else {
10624 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
10625 << decl << expr->getSourceRange();
10626 return ExprError();
10627 }
10628
John McCall755d8492011-04-12 00:42:48 +000010629 decl->setType(DestType);
10630 expr->setType(type);
10631 expr->setValueKind(valueKind);
10632 return S.Owned(expr);
John McCall379b5152011-04-11 07:02:50 +000010633}
10634
John McCall1de4d4e2011-04-07 08:22:57 +000010635/// Check a cast of an unknown-any type. We intentionally only
10636/// trigger this for C-style casts.
John Wiegley429bb272011-04-08 18:41:53 +000010637ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
10638 Expr *castExpr, CastKind &castKind,
10639 ExprValueKind &VK, CXXCastPath &path) {
John McCall1de4d4e2011-04-07 08:22:57 +000010640 // Rewrite the casted expression from scratch.
John McCalla5fc4722011-04-09 22:50:59 +000010641 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
10642 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000010643
John McCalla5fc4722011-04-09 22:50:59 +000010644 castExpr = result.take();
10645 VK = castExpr->getValueKind();
10646 castKind = CK_NoOp;
10647
10648 return castExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000010649}
10650
10651static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
10652 Expr *orig = e;
John McCall379b5152011-04-11 07:02:50 +000010653 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000010654 while (true) {
10655 e = e->IgnoreParenImpCasts();
John McCall379b5152011-04-11 07:02:50 +000010656 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall1de4d4e2011-04-07 08:22:57 +000010657 e = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000010658 diagID = diag::err_uncasted_call_of_unknown_any;
10659 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000010660 break;
John McCall379b5152011-04-11 07:02:50 +000010661 }
John McCall1de4d4e2011-04-07 08:22:57 +000010662 }
10663
John McCall379b5152011-04-11 07:02:50 +000010664 SourceLocation loc;
10665 NamedDecl *d;
10666 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10667 loc = ref->getLocation();
10668 d = ref->getDecl();
10669 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
10670 loc = mem->getMemberLoc();
10671 d = mem->getMemberDecl();
10672 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
10673 diagID = diag::err_uncasted_call_of_unknown_any;
10674 loc = msg->getSelectorLoc();
10675 d = msg->getMethodDecl();
10676 assert(d && "unknown method returning __unknown_any?");
10677 } else {
10678 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10679 << e->getSourceRange();
10680 return ExprError();
10681 }
10682
10683 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000010684
10685 // Never recoverable.
10686 return ExprError();
10687}
10688
John McCall2a984ca2010-10-12 00:20:44 +000010689/// Check for operands with placeholder types and complain if found.
10690/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000010691ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall1de4d4e2011-04-07 08:22:57 +000010692 // Placeholder types are always *exactly* the appropriate builtin type.
10693 QualType type = E->getType();
John McCall2a984ca2010-10-12 00:20:44 +000010694
John McCall1de4d4e2011-04-07 08:22:57 +000010695 // Overloaded expressions.
10696 if (type == Context.OverloadTy)
10697 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregordb2eae62011-03-16 19:16:25 +000010698 E->getSourceRange(),
John McCall1de4d4e2011-04-07 08:22:57 +000010699 QualType(),
10700 diag::err_ovl_unresolvable);
10701
John McCall864c0412011-04-26 20:42:42 +000010702 // Bound member functions.
10703 if (type == Context.BoundMemberTy) {
10704 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
10705 << E->getSourceRange();
10706 return ExprError();
10707 }
10708
John McCall1de4d4e2011-04-07 08:22:57 +000010709 // Expressions of unknown type.
10710 if (type == Context.UnknownAnyTy)
10711 return diagnoseUnknownAnyExpr(*this, E);
10712
10713 assert(!type->isPlaceholderType());
10714 return Owned(E);
John McCall2a984ca2010-10-12 00:20:44 +000010715}
Richard Trieubb9b80c2011-04-21 21:44:26 +000010716
10717bool Sema::CheckCaseExpression(Expr *expr) {
10718 if (expr->isTypeDependent())
10719 return true;
10720 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
10721 return expr->getType()->isIntegralOrEnumerationType();
10722 return false;
10723}