blob: 546d2e7e388a63bca2d027b74216aa408ba4d991 [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,
Peter Collingbourne743b82b2011-01-02 19:53:12 +000059 bool 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
71 // them again for this specialization. However, we don't remove this
72 // 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
Chris Lattner76a642f2009-02-15 22:43:40 +000085 // See if the decl is deprecated.
Benjamin Kramerce2d1862010-10-09 15:49:00 +000086 if (const DeprecatedAttr *DA = D->getAttr<DeprecatedAttr>())
Peter Collingbourne743b82b2011-01-02 19:53:12 +000087 EmitDeprecationWarning(D, DA->getMessage(), Loc, UnknownObjCClass);
Chris Lattner76a642f2009-02-15 22:43:40 +000088
Chris Lattnerffb93682009-10-25 17:21:40 +000089 // See if the decl is unavailable
Fariborz Jahanianc784dc12010-10-06 23:12:32 +000090 if (const UnavailableAttr *UA = D->getAttr<UnavailableAttr>()) {
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000091 if (UA->getMessage().empty()) {
Peter Collingbourne743b82b2011-01-02 19:53:12 +000092 if (!UnknownObjCClass)
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000093 Diag(Loc, diag::err_unavailable) << D->getDeclName();
94 else
95 Diag(Loc, diag::warn_unavailable_fwdclass_message)
96 << D->getDeclName();
97 }
98 else
Fariborz Jahanianc784dc12010-10-06 23:12:32 +000099 Diag(Loc, diag::err_unavailable_message)
Benjamin Kramerce2d1862010-10-09 15:49:00 +0000100 << D->getDeclName() << UA->getMessage();
Chris Lattnerffb93682009-10-25 17:21:40 +0000101 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
102 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000103
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000104 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +0000105 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000106 if (FD->isDeleted()) {
107 Diag(Loc, diag::err_deleted_function_use);
108 Diag(D->getLocation(), diag::note_unavailable_here) << true;
109 return true;
110 }
Douglas Gregor25d944a2009-02-24 04:26:15 +0000111 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000112
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000113 // Warn if this is used but marked unused.
114 if (D->hasAttr<UnusedAttr>())
115 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
116
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000117 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000118}
119
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000120/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +0000121/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000122/// attribute. It warns if call does not have the sentinel argument.
123///
124void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000125 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000126 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000127 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000128 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000129
130 // FIXME: In C++0x, if any of the arguments are parameter pack
131 // expansions, we can't check for the sentinel now.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000132 int sentinelPos = attr->getSentinel();
133 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +0000134
Mike Stump390b4cc2009-05-16 07:39:55 +0000135 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
136 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000137 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000138 bool warnNotEnoughArgs = false;
139 int isMethod = 0;
140 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
141 // skip over named parameters.
142 ObjCMethodDecl::param_iterator P, E = MD->param_end();
143 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
144 if (nullPos)
145 --nullPos;
146 else
147 ++i;
148 }
149 warnNotEnoughArgs = (P != E || i >= NumArgs);
150 isMethod = 1;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000151 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000152 // skip over named parameters.
153 ObjCMethodDecl::param_iterator P, E = FD->param_end();
154 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
155 if (nullPos)
156 --nullPos;
157 else
158 ++i;
159 }
160 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000161 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000162 // block or function pointer call.
163 QualType Ty = V->getType();
164 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000165 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000166 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
167 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000168 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
169 unsigned NumArgsInProto = Proto->getNumArgs();
170 unsigned k;
171 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
172 if (nullPos)
173 --nullPos;
174 else
175 ++i;
176 }
177 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
178 }
179 if (Ty->isBlockPointerType())
180 isMethod = 2;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000181 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000182 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000183 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000184 return;
185
186 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000187 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000188 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000189 return;
190 }
191 int sentinel = i;
192 while (sentinelPos > 0 && i < NumArgs-1) {
193 --sentinelPos;
194 ++i;
195 }
196 if (sentinelPos > 0) {
197 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000198 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000199 return;
200 }
201 while (i < NumArgs-1) {
202 ++i;
203 ++sentinel;
204 }
205 Expr *sentinelExpr = Args[sentinel];
John McCall8eb662e2010-05-06 23:53:00 +0000206 if (!sentinelExpr) return;
207 if (sentinelExpr->isTypeDependent()) return;
208 if (sentinelExpr->isValueDependent()) return;
Anders Carlsson343e6ff2010-11-05 15:21:33 +0000209
210 // nullptr_t is always treated as null.
211 if (sentinelExpr->getType()->isNullPtrType()) return;
212
Fariborz Jahanian9ccd7252010-07-14 16:37:51 +0000213 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall8eb662e2010-05-06 23:53:00 +0000214 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
215 Expr::NPC_ValueDependentIsNull))
216 return;
217
218 // Unfortunately, __null has type 'int'.
219 if (isa<GNUNullExpr>(sentinelExpr)) return;
220
221 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
222 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000223}
224
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000225SourceRange Sema::getExprRange(ExprTy *E) const {
226 Expr *Ex = (Expr *)E;
227 return Ex? Ex->getSourceRange() : SourceRange();
228}
229
Chris Lattnere7a2e912008-07-25 21:10:04 +0000230//===----------------------------------------------------------------------===//
231// Standard Promotions and Conversions
232//===----------------------------------------------------------------------===//
233
Chris Lattnere7a2e912008-07-25 21:10:04 +0000234/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
235void Sema::DefaultFunctionArrayConversion(Expr *&E) {
236 QualType Ty = E->getType();
237 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
238
Chris Lattnere7a2e912008-07-25 21:10:04 +0000239 if (Ty->isFunctionType())
Mike Stump1eb44332009-09-09 15:08:12 +0000240 ImpCastExprToType(E, Context.getPointerType(Ty),
John McCall2de56d12010-08-25 11:45:40 +0000241 CK_FunctionToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000242 else if (Ty->isArrayType()) {
243 // In C90 mode, arrays only promote to pointers if the array expression is
244 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
245 // type 'array of type' is converted to an expression that has type 'pointer
246 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
247 // that has type 'array of type' ...". The relevant change is "an lvalue"
248 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000249 //
250 // C++ 4.2p1:
251 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
252 // T" can be converted to an rvalue of type "pointer to T".
253 //
John McCall7eb0a9e2010-11-24 05:12:34 +0000254 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
Anders Carlsson112a0a82009-08-07 23:48:20 +0000255 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
John McCall2de56d12010-08-25 11:45:40 +0000256 CK_ArrayToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000257 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000258}
259
John McCall409fa9a2010-12-06 20:48:59 +0000260void Sema::DefaultLvalueConversion(Expr *&E) {
John McCall0ae287a2010-12-01 04:43:34 +0000261 // C++ [conv.lval]p1:
262 // A glvalue of a non-function, non-array type T can be
263 // converted to a prvalue.
John McCall409fa9a2010-12-06 20:48:59 +0000264 if (!E->isGLValue()) return;
John McCallf6a16482010-12-04 03:47:34 +0000265
John McCall409fa9a2010-12-06 20:48:59 +0000266 QualType T = E->getType();
267 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000268
John McCall409fa9a2010-12-06 20:48:59 +0000269 // Create a load out of an ObjCProperty l-value, if necessary.
270 if (E->getObjectKind() == OK_ObjCProperty) {
271 ConvertPropertyForRValue(E);
272 if (!E->isGLValue())
John McCallf6a16482010-12-04 03:47:34 +0000273 return;
Douglas Gregora873dfc2010-02-03 00:27:59 +0000274 }
John McCall409fa9a2010-12-06 20:48:59 +0000275
276 // We don't want to throw lvalue-to-rvalue casts on top of
277 // expressions of certain types in C++.
278 if (getLangOptions().CPlusPlus &&
279 (E->getType() == Context.OverloadTy ||
280 T->isDependentType() ||
281 T->isRecordType()))
282 return;
283
284 // The C standard is actually really unclear on this point, and
285 // DR106 tells us what the result should be but not why. It's
286 // generally best to say that void types just doesn't undergo
287 // lvalue-to-rvalue at all. Note that expressions of unqualified
288 // 'void' type are never l-values, but qualified void can be.
289 if (T->isVoidType())
290 return;
291
292 // C++ [conv.lval]p1:
293 // [...] If T is a non-class type, the type of the prvalue is the
294 // cv-unqualified version of T. Otherwise, the type of the
295 // rvalue is T.
296 //
297 // C99 6.3.2.1p2:
298 // If the lvalue has qualified type, the value has the unqualified
299 // version of the type of the lvalue; otherwise, the value has the
300 // type of the lvalue.
301 if (T.hasQualifiers())
302 T = T.getUnqualifiedType();
303
Ted Kremenek3aea4da2011-03-01 18:41:00 +0000304 CheckArrayAccess(E);
Ted Kremeneka0125d82011-02-16 01:57:07 +0000305
John McCall409fa9a2010-12-06 20:48:59 +0000306 E = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
307 E, 0, VK_RValue);
308}
309
310void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
311 DefaultFunctionArrayConversion(E);
312 DefaultLvalueConversion(E);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000313}
314
315
Chris Lattnere7a2e912008-07-25 21:10:04 +0000316/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000317/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnere7a2e912008-07-25 21:10:04 +0000318/// sometimes surpressed. For example, the array->pointer conversion doesn't
319/// apply if the array is an argument to the sizeof or address (&) operators.
320/// In these instances, this routine should *not* be called.
John McCall0ae287a2010-12-01 04:43:34 +0000321Expr *Sema::UsualUnaryConversions(Expr *&E) {
322 // First, convert to an r-value.
323 DefaultFunctionArrayLvalueConversion(E);
324
325 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000326 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCall0ae287a2010-12-01 04:43:34 +0000327
328 // Try to perform integral promotions if the object has a theoretically
329 // promotable type.
330 if (Ty->isIntegralOrUnscopedEnumerationType()) {
331 // C99 6.3.1.1p2:
332 //
333 // The following may be used in an expression wherever an int or
334 // unsigned int may be used:
335 // - an object or expression with an integer type whose integer
336 // conversion rank is less than or equal to the rank of int
337 // and unsigned int.
338 // - A bit-field of type _Bool, int, signed int, or unsigned int.
339 //
340 // If an int can represent all values of the original type, the
341 // value is converted to an int; otherwise, it is converted to an
342 // unsigned int. These are called the integer promotions. All
343 // other types are unchanged by the integer promotions.
344
345 QualType PTy = Context.isPromotableBitField(E);
346 if (!PTy.isNull()) {
347 ImpCastExprToType(E, PTy, CK_IntegralCast);
348 return E;
349 }
350 if (Ty->isPromotableIntegerType()) {
351 QualType PT = Context.getPromotedIntegerType(Ty);
352 ImpCastExprToType(E, PT, CK_IntegralCast);
353 return E;
354 }
Eli Friedman04e83572009-08-20 04:21:42 +0000355 }
356
John McCall0ae287a2010-12-01 04:43:34 +0000357 return E;
Chris Lattnere7a2e912008-07-25 21:10:04 +0000358}
359
Chris Lattner05faf172008-07-25 22:25:12 +0000360/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000361/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000362/// double. All other argument types are converted by UsualUnaryConversions().
363void Sema::DefaultArgumentPromotion(Expr *&Expr) {
364 QualType Ty = Expr->getType();
365 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000366
John McCall40c29132010-12-06 18:36:11 +0000367 UsualUnaryConversions(Expr);
368
Chris Lattner05faf172008-07-25 22:25:12 +0000369 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000370 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John McCall40c29132010-12-06 18:36:11 +0000371 return ImpCastExprToType(Expr, Context.DoubleTy, CK_FloatingCast);
Chris Lattner05faf172008-07-25 22:25:12 +0000372}
373
Chris Lattner312531a2009-04-12 08:11:20 +0000374/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
375/// will warn if the resulting type is not a POD type, and rejects ObjC
376/// interfaces passed by value. This returns true if the argument type is
377/// completely illegal.
Chris Lattner40378332010-05-16 04:01:30 +0000378bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
379 FunctionDecl *FDecl) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000380 DefaultArgumentPromotion(Expr);
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Chris Lattner40378332010-05-16 04:01:30 +0000382 // __builtin_va_start takes the second argument as a "varargs" argument, but
383 // it doesn't actually do anything with it. It doesn't need to be non-pod
384 // etc.
385 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
386 return false;
387
John McCallc12c5bb2010-05-15 11:32:37 +0000388 if (Expr->getType()->isObjCObjectType() &&
Ted Kremenek351ba912011-02-23 01:52:04 +0000389 DiagRuntimeBehavior(Expr->getLocStart(), 0,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000390 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
391 << Expr->getType() << CT))
392 return true;
Douglas Gregor75b699a2009-12-12 07:25:49 +0000393
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000394 if (!Expr->getType()->isPODType() &&
Ted Kremenek351ba912011-02-23 01:52:04 +0000395 DiagRuntimeBehavior(Expr->getLocStart(), 0,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000396 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
397 << Expr->getType() << CT))
398 return true;
Chris Lattner312531a2009-04-12 08:11:20 +0000399
400 return false;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000401}
402
Chris Lattnere7a2e912008-07-25 21:10:04 +0000403/// UsualArithmeticConversions - Performs various conversions that are common to
404/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000405/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000406/// responsible for emitting appropriate error diagnostics.
407/// FIXME: verify the conversion rules for "complex int" are consistent with
408/// GCC.
409QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
410 bool isCompAssign) {
Eli Friedmanab3a8522009-03-28 01:22:36 +0000411 if (!isCompAssign)
Chris Lattnere7a2e912008-07-25 21:10:04 +0000412 UsualUnaryConversions(lhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000413
414 UsualUnaryConversions(rhsExpr);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000415
Mike Stump1eb44332009-09-09 15:08:12 +0000416 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000417 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000418 QualType lhs =
419 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000420 QualType rhs =
Chris Lattnerb77792e2008-07-26 22:17:49 +0000421 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000422
423 // If both types are identical, no conversion is needed.
424 if (lhs == rhs)
425 return lhs;
426
427 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
428 // The caller can deal with this (e.g. pointer + int).
429 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
430 return lhs;
431
John McCallcf33b242010-11-13 08:17:45 +0000432 // Apply unary and bitfield promotions to the LHS's type.
433 QualType lhs_unpromoted = lhs;
434 if (lhs->isPromotableIntegerType())
435 lhs = Context.getPromotedIntegerType(lhs);
Eli Friedman04e83572009-08-20 04:21:42 +0000436 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000437 if (!LHSBitfieldPromoteTy.isNull())
438 lhs = LHSBitfieldPromoteTy;
John McCallcf33b242010-11-13 08:17:45 +0000439 if (lhs != lhs_unpromoted && !isCompAssign)
440 ImpCastExprToType(lhsExpr, lhs, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000441
John McCallcf33b242010-11-13 08:17:45 +0000442 // If both types are identical, no conversion is needed.
443 if (lhs == rhs)
444 return lhs;
445
446 // At this point, we have two different arithmetic types.
447
448 // Handle complex types first (C99 6.3.1.8p1).
449 bool LHSComplexFloat = lhs->isComplexType();
450 bool RHSComplexFloat = rhs->isComplexType();
451 if (LHSComplexFloat || RHSComplexFloat) {
452 // if we have an integer operand, the result is the complex type.
453
John McCall2bb5d002010-11-13 09:02:35 +0000454 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
455 if (rhs->isIntegerType()) {
456 QualType fp = cast<ComplexType>(lhs)->getElementType();
457 ImpCastExprToType(rhsExpr, fp, CK_IntegralToFloating);
458 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
459 } else {
460 assert(rhs->isComplexIntegerType());
John McCallf3ea8cf2010-11-14 08:17:51 +0000461 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000462 }
John McCallcf33b242010-11-13 08:17:45 +0000463 return lhs;
464 }
465
John McCall2bb5d002010-11-13 09:02:35 +0000466 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
467 if (!isCompAssign) {
468 // int -> float -> _Complex float
469 if (lhs->isIntegerType()) {
470 QualType fp = cast<ComplexType>(rhs)->getElementType();
471 ImpCastExprToType(lhsExpr, fp, CK_IntegralToFloating);
472 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
473 } else {
474 assert(lhs->isComplexIntegerType());
John McCallf3ea8cf2010-11-14 08:17:51 +0000475 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000476 }
477 }
John McCallcf33b242010-11-13 08:17:45 +0000478 return rhs;
479 }
480
481 // This handles complex/complex, complex/float, or float/complex.
482 // When both operands are complex, the shorter operand is converted to the
483 // type of the longer, and that is the type of the result. This corresponds
484 // to what is done when combining two real floating-point operands.
485 // The fun begins when size promotion occur across type domains.
486 // From H&S 6.3.4: When one operand is complex and the other is a real
487 // floating-point type, the less precise type is converted, within it's
488 // real or complex domain, to the precision of the other type. For example,
489 // when combining a "long double" with a "double _Complex", the
490 // "double _Complex" is promoted to "long double _Complex".
491 int order = Context.getFloatingTypeOrder(lhs, rhs);
492
493 // If both are complex, just cast to the more precise type.
494 if (LHSComplexFloat && RHSComplexFloat) {
495 if (order > 0) {
496 // _Complex float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000497 ImpCastExprToType(rhsExpr, lhs, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000498 return lhs;
499
500 } else if (order < 0) {
501 // _Complex float -> _Complex double
502 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000503 ImpCastExprToType(lhsExpr, rhs, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000504 return rhs;
505 }
506 return lhs;
507 }
508
509 // If just the LHS is complex, the RHS needs to be converted,
510 // and the LHS might need to be promoted.
511 if (LHSComplexFloat) {
512 if (order > 0) { // LHS is wider
513 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000514 QualType fp = cast<ComplexType>(lhs)->getElementType();
515 ImpCastExprToType(rhsExpr, fp, CK_FloatingCast);
516 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000517 return lhs;
518 }
519
520 // RHS is at least as wide. Find its corresponding complex type.
521 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
522
523 // double -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000524 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000525
526 // _Complex float -> _Complex double
527 if (!isCompAssign && order < 0)
John McCall2bb5d002010-11-13 09:02:35 +0000528 ImpCastExprToType(lhsExpr, result, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000529
530 return result;
531 }
532
533 // Just the RHS is complex, so the LHS needs to be converted
534 // and the RHS might need to be promoted.
535 assert(RHSComplexFloat);
536
537 if (order < 0) { // RHS is wider
538 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000539 if (!isCompAssign) {
Argyrios Kyrtzidise1889332011-01-18 18:49:33 +0000540 QualType fp = cast<ComplexType>(rhs)->getElementType();
541 ImpCastExprToType(lhsExpr, fp, CK_FloatingCast);
John McCall2bb5d002010-11-13 09:02:35 +0000542 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
543 }
John McCallcf33b242010-11-13 08:17:45 +0000544 return rhs;
545 }
546
547 // LHS is at least as wide. Find its corresponding complex type.
548 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
549
550 // double -> _Complex double
551 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000552 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000553
554 // _Complex float -> _Complex double
555 if (order > 0)
John McCall2bb5d002010-11-13 09:02:35 +0000556 ImpCastExprToType(rhsExpr, result, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000557
558 return result;
559 }
560
561 // Now handle "real" floating types (i.e. float, double, long double).
562 bool LHSFloat = lhs->isRealFloatingType();
563 bool RHSFloat = rhs->isRealFloatingType();
564 if (LHSFloat || RHSFloat) {
565 // If we have two real floating types, convert the smaller operand
566 // to the bigger result.
567 if (LHSFloat && RHSFloat) {
568 int order = Context.getFloatingTypeOrder(lhs, rhs);
569 if (order > 0) {
570 ImpCastExprToType(rhsExpr, lhs, CK_FloatingCast);
571 return lhs;
572 }
573
574 assert(order < 0 && "illegal float comparison");
575 if (!isCompAssign)
576 ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast);
577 return rhs;
578 }
579
580 // If we have an integer operand, the result is the real floating type.
581 if (LHSFloat) {
582 if (rhs->isIntegerType()) {
583 // Convert rhs to the lhs floating point type.
584 ImpCastExprToType(rhsExpr, lhs, CK_IntegralToFloating);
585 return lhs;
586 }
587
588 // Convert both sides to the appropriate complex float.
589 assert(rhs->isComplexIntegerType());
590 QualType result = Context.getComplexType(lhs);
591
592 // _Complex int -> _Complex float
John McCallf3ea8cf2010-11-14 08:17:51 +0000593 ImpCastExprToType(rhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000594
595 // float -> _Complex float
596 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000597 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000598
599 return result;
600 }
601
602 assert(RHSFloat);
603 if (lhs->isIntegerType()) {
604 // Convert lhs to the rhs floating point type.
605 if (!isCompAssign)
606 ImpCastExprToType(lhsExpr, rhs, CK_IntegralToFloating);
607 return rhs;
608 }
609
610 // Convert both sides to the appropriate complex float.
611 assert(lhs->isComplexIntegerType());
612 QualType result = Context.getComplexType(rhs);
613
614 // _Complex int -> _Complex float
615 if (!isCompAssign)
John McCallf3ea8cf2010-11-14 08:17:51 +0000616 ImpCastExprToType(lhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000617
618 // float -> _Complex float
John McCall2bb5d002010-11-13 09:02:35 +0000619 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000620
621 return result;
622 }
623
624 // Handle GCC complex int extension.
625 // FIXME: if the operands are (int, _Complex long), we currently
626 // don't promote the complex. Also, signedness?
627 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
628 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
629 if (lhsComplexInt && rhsComplexInt) {
630 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
631 rhsComplexInt->getElementType());
632 assert(order && "inequal types with equal element ordering");
633 if (order > 0) {
634 // _Complex int -> _Complex long
John McCall2bb5d002010-11-13 09:02:35 +0000635 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000636 return lhs;
637 }
638
639 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000640 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000641 return rhs;
642 } else if (lhsComplexInt) {
643 // int -> _Complex int
John McCall2bb5d002010-11-13 09:02:35 +0000644 ImpCastExprToType(rhsExpr, lhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000645 return lhs;
646 } else if (rhsComplexInt) {
647 // int -> _Complex int
648 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000649 ImpCastExprToType(lhsExpr, rhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000650 return rhs;
651 }
652
653 // Finally, we have two differing integer types.
654 // The rules for this case are in C99 6.3.1.8
655 int compare = Context.getIntegerTypeOrder(lhs, rhs);
656 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
657 rhsSigned = rhs->hasSignedIntegerRepresentation();
658 if (lhsSigned == rhsSigned) {
659 // Same signedness; use the higher-ranked type
660 if (compare >= 0) {
661 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
662 return lhs;
663 } else if (!isCompAssign)
664 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
665 return rhs;
666 } else if (compare != (lhsSigned ? 1 : -1)) {
667 // The unsigned type has greater than or equal rank to the
668 // signed type, so use the unsigned type
669 if (rhsSigned) {
670 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
671 return lhs;
672 } else if (!isCompAssign)
673 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
674 return rhs;
675 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
676 // The two types are different widths; if we are here, that
677 // means the signed type is larger than the unsigned type, so
678 // use the signed type.
679 if (lhsSigned) {
680 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
681 return lhs;
682 } else if (!isCompAssign)
683 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
684 return rhs;
685 } else {
686 // The signed type is higher-ranked than the unsigned type,
687 // but isn't actually any bigger (like unsigned int and long
688 // on most 32-bit systems). Use the unsigned type corresponding
689 // to the signed type.
690 QualType result =
691 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
692 ImpCastExprToType(rhsExpr, result, CK_IntegralCast);
693 if (!isCompAssign)
694 ImpCastExprToType(lhsExpr, result, CK_IntegralCast);
695 return result;
696 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000697}
698
Chris Lattnere7a2e912008-07-25 21:10:04 +0000699//===----------------------------------------------------------------------===//
700// Semantic Analysis for various Expression Types
701//===----------------------------------------------------------------------===//
702
703
Steve Narofff69936d2007-09-16 03:34:24 +0000704/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000705/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
706/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
707/// multiple tokens. However, the common case is that StringToks points to one
708/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000709///
John McCall60d7b3a2010-08-24 06:29:42 +0000710ExprResult
Sean Hunt6cf75022010-08-30 17:47:05 +0000711Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000712 assert(NumStringToks && "Must have at least one string!");
713
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000714 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000715 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000716 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000717
718 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
719 for (unsigned i = 0; i != NumStringToks; ++i)
720 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000721
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000722 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000723 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000724 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000725
726 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +0000727 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +0000728 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000729
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000730 // Get an array type for the string, according to C99 6.4.5. This includes
731 // the nul terminator character as well as the string length for pascal
732 // strings.
733 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000734 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000735 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000736
Reid Spencer5f016e22007-07-11 17:01:13 +0000737 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sean Hunt6cf75022010-08-30 17:47:05 +0000738 return Owned(StringLiteral::Create(Context, Literal.GetString(),
739 Literal.GetStringLength(),
740 Literal.AnyWide, StrTy,
741 &StringTokLocs[0],
742 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000743}
744
John McCall469a1eb2011-02-02 13:00:07 +0000745enum CaptureResult {
746 /// No capture is required.
747 CR_NoCapture,
748
749 /// A capture is required.
750 CR_Capture,
751
John McCall6b5a61b2011-02-07 10:33:21 +0000752 /// A by-ref capture is required.
753 CR_CaptureByRef,
754
John McCall469a1eb2011-02-02 13:00:07 +0000755 /// An error occurred when trying to capture the given variable.
756 CR_Error
757};
758
759/// Diagnose an uncapturable value reference.
Chris Lattner639e2d32008-10-20 05:16:36 +0000760///
John McCall469a1eb2011-02-02 13:00:07 +0000761/// \param var - the variable referenced
762/// \param DC - the context which we couldn't capture through
763static CaptureResult
John McCall6b5a61b2011-02-07 10:33:21 +0000764diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +0000765 VarDecl *var, DeclContext *DC) {
766 switch (S.ExprEvalContexts.back().Context) {
767 case Sema::Unevaluated:
768 // The argument will never be evaluated, so don't complain.
769 return CR_NoCapture;
Mike Stump1eb44332009-09-09 15:08:12 +0000770
John McCall469a1eb2011-02-02 13:00:07 +0000771 case Sema::PotentiallyEvaluated:
772 case Sema::PotentiallyEvaluatedIfUsed:
773 break;
Chris Lattner639e2d32008-10-20 05:16:36 +0000774
John McCall469a1eb2011-02-02 13:00:07 +0000775 case Sema::PotentiallyPotentiallyEvaluated:
776 // FIXME: delay these!
777 break;
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000778 }
Mike Stump1eb44332009-09-09 15:08:12 +0000779
John McCall469a1eb2011-02-02 13:00:07 +0000780 // Don't diagnose about capture if we're not actually in code right
781 // now; in general, there are more appropriate places that will
782 // diagnose this.
783 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
784
785 // This particular madness can happen in ill-formed default
786 // arguments; claim it's okay and let downstream code handle it.
787 if (isa<ParmVarDecl>(var) &&
788 S.CurContext == var->getDeclContext()->getParent())
789 return CR_NoCapture;
790
791 DeclarationName functionName;
792 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
793 functionName = fn->getDeclName();
794 // FIXME: variable from enclosing block that we couldn't capture from!
795
796 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
797 << var->getIdentifier() << functionName;
798 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
799 << var->getIdentifier();
800
801 return CR_Error;
Mike Stump1eb44332009-09-09 15:08:12 +0000802}
803
John McCall6b5a61b2011-02-07 10:33:21 +0000804/// There is a well-formed capture at a particular scope level;
805/// propagate it through all the nested blocks.
806static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
807 const BlockDecl::Capture &capture) {
808 VarDecl *var = capture.getVariable();
809
810 // Update all the inner blocks with the capture information.
811 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
812 i != e; ++i) {
813 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
814 innerBlock->Captures.push_back(
815 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
816 /*nested*/ true, capture.getCopyExpr()));
817 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
818 }
819
820 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
821}
822
823/// shouldCaptureValueReference - Determine if a reference to the
John McCall469a1eb2011-02-02 13:00:07 +0000824/// given value in the current context requires a variable capture.
825///
826/// This also keeps the captures set in the BlockScopeInfo records
827/// up-to-date.
John McCall6b5a61b2011-02-07 10:33:21 +0000828static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +0000829 ValueDecl *value) {
830 // Only variables ever require capture.
831 VarDecl *var = dyn_cast<VarDecl>(value);
John McCall76a40212011-02-09 01:13:10 +0000832 if (!var) return CR_NoCapture;
John McCall469a1eb2011-02-02 13:00:07 +0000833
834 // Fast path: variables from the current context never require capture.
835 DeclContext *DC = S.CurContext;
836 if (var->getDeclContext() == DC) return CR_NoCapture;
837
838 // Only variables with local storage require capture.
839 // FIXME: What about 'const' variables in C++?
840 if (!var->hasLocalStorage()) return CR_NoCapture;
841
842 // Otherwise, we need to capture.
843
844 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCall469a1eb2011-02-02 13:00:07 +0000845 do {
846 // Only blocks (and eventually C++0x closures) can capture; other
847 // scopes don't work.
848 if (!isa<BlockDecl>(DC))
John McCall6b5a61b2011-02-07 10:33:21 +0000849 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCall469a1eb2011-02-02 13:00:07 +0000850
851 BlockScopeInfo *blockScope =
852 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
853 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
854
John McCall6b5a61b2011-02-07 10:33:21 +0000855 // Check whether we've already captured it in this block. If so,
856 // we're done.
857 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
858 return propagateCapture(S, functionScopesIndex,
859 blockScope->Captures[indexPlus1 - 1]);
John McCall469a1eb2011-02-02 13:00:07 +0000860
861 functionScopesIndex--;
862 DC = cast<BlockDecl>(DC)->getDeclContext();
863 } while (var->getDeclContext() != DC);
864
John McCall6b5a61b2011-02-07 10:33:21 +0000865 // Okay, we descended all the way to the block that defines the variable.
866 // Actually try to capture it.
867 QualType type = var->getType();
868
869 // Prohibit variably-modified types.
870 if (type->isVariablyModifiedType()) {
871 S.Diag(loc, diag::err_ref_vm_type);
872 S.Diag(var->getLocation(), diag::note_declared_at);
873 return CR_Error;
874 }
875
876 // Prohibit arrays, even in __block variables, but not references to
877 // them.
878 if (type->isArrayType()) {
879 S.Diag(loc, diag::err_ref_array_type);
880 S.Diag(var->getLocation(), diag::note_declared_at);
881 return CR_Error;
882 }
883
884 S.MarkDeclarationReferenced(loc, var);
885
886 // The BlocksAttr indicates the variable is bound by-reference.
887 bool byRef = var->hasAttr<BlocksAttr>();
888
889 // Build a copy expression.
890 Expr *copyExpr = 0;
891 if (!byRef && S.getLangOptions().CPlusPlus &&
892 !type->isDependentType() && type->isStructureOrClassType()) {
893 // According to the blocks spec, the capture of a variable from
894 // the stack requires a const copy constructor. This is not true
895 // of the copy/move done to move a __block variable to the heap.
896 type.addConst();
897
898 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
899 ExprResult result =
900 S.PerformCopyInitialization(
901 InitializedEntity::InitializeBlock(var->getLocation(),
902 type, false),
903 loc, S.Owned(declRef));
904
905 // Build a full-expression copy expression if initialization
906 // succeeded and used a non-trivial constructor. Recover from
907 // errors by pretending that the copy isn't necessary.
908 if (!result.isInvalid() &&
909 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
910 result = S.MaybeCreateExprWithCleanups(result);
911 copyExpr = result.take();
912 }
913 }
914
915 // We're currently at the declarer; go back to the closure.
916 functionScopesIndex++;
917 BlockScopeInfo *blockScope =
918 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
919
920 // Build a valid capture in this scope.
921 blockScope->Captures.push_back(
922 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
923 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
924
925 // Propagate that to inner captures if necessary.
926 return propagateCapture(S, functionScopesIndex,
927 blockScope->Captures.back());
928}
929
930static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
931 const DeclarationNameInfo &NameInfo,
932 bool byRef) {
933 assert(isa<VarDecl>(vd) && "capturing non-variable");
934
935 VarDecl *var = cast<VarDecl>(vd);
936 assert(var->hasLocalStorage() && "capturing non-local");
937 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
938
939 QualType exprType = var->getType().getNonReferenceType();
940
941 BlockDeclRefExpr *BDRE;
942 if (!byRef) {
943 // The variable will be bound by copy; make it const within the
944 // closure, but record that this was done in the expression.
945 bool constAdded = !exprType.isConstQualified();
946 exprType.addConst();
947
948 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
949 NameInfo.getLoc(), false,
950 constAdded);
951 } else {
952 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
953 NameInfo.getLoc(), true);
954 }
955
956 return S.Owned(BDRE);
John McCall469a1eb2011-02-02 13:00:07 +0000957}
Chris Lattner639e2d32008-10-20 05:16:36 +0000958
John McCall60d7b3a2010-08-24 06:29:42 +0000959ExprResult
John McCallf89e55a2010-11-18 06:31:45 +0000960Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +0000961 SourceLocation Loc,
962 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000963 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +0000964 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +0000965}
966
John McCall76a40212011-02-09 01:13:10 +0000967/// BuildDeclRefExpr - Build an expression that references a
968/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +0000969ExprResult
John McCall76a40212011-02-09 01:13:10 +0000970Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +0000971 const DeclarationNameInfo &NameInfo,
972 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000973 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +0000974
John McCall7eb0a9e2010-11-24 05:12:34 +0000975 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +0000976 SS? SS->getWithLocInContext(Context)
977 : NestedNameSpecifierLoc(),
John McCall7eb0a9e2010-11-24 05:12:34 +0000978 D, NameInfo, Ty, VK);
979
980 // Just in case we're building an illegal pointer-to-member.
981 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
982 E->setObjectKind(OK_BitField);
983
984 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +0000985}
986
John McCalldfa1edb2010-11-23 20:48:44 +0000987static ExprResult
988BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
989 const CXXScopeSpec &SS, FieldDecl *Field,
990 DeclAccessPair FoundDecl,
991 const DeclarationNameInfo &MemberNameInfo);
992
John McCall60d7b3a2010-08-24 06:29:42 +0000993ExprResult
John McCall5808ce42011-02-03 08:15:49 +0000994Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
995 SourceLocation loc,
996 IndirectFieldDecl *indirectField,
997 Expr *baseObjectExpr,
998 SourceLocation opLoc) {
999 // First, build the expression that refers to the base object.
1000
1001 bool baseObjectIsPointer = false;
1002 Qualifiers baseQuals;
1003
1004 // Case 1: the base of the indirect field is not a field.
1005 VarDecl *baseVariable = indirectField->getVarDecl();
Douglas Gregorf5848322011-02-18 02:44:58 +00001006 CXXScopeSpec EmptySS;
John McCall5808ce42011-02-03 08:15:49 +00001007 if (baseVariable) {
1008 assert(baseVariable->getType()->isRecordType());
1009
1010 // In principle we could have a member access expression that
1011 // accesses an anonymous struct/union that's a static member of
1012 // the base object's class. However, under the current standard,
1013 // static data members cannot be anonymous structs or unions.
1014 // Supporting this is as easy as building a MemberExpr here.
1015 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1016
1017 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1018
1019 ExprResult result =
Douglas Gregorf5848322011-02-18 02:44:58 +00001020 BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
John McCall5808ce42011-02-03 08:15:49 +00001021 if (result.isInvalid()) return ExprError();
1022
1023 baseObjectExpr = result.take();
1024 baseObjectIsPointer = false;
1025 baseQuals = baseObjectExpr->getType().getQualifiers();
1026
1027 // Case 2: the base of the indirect field is a field and the user
1028 // wrote a member expression.
1029 } else if (baseObjectExpr) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001030 // The caller provided the base object expression. Determine
1031 // whether its a pointer and whether it adds any qualifiers to the
1032 // anonymous struct/union fields we're looking into.
John McCall5808ce42011-02-03 08:15:49 +00001033 QualType objectType = baseObjectExpr->getType();
1034
1035 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1036 baseObjectIsPointer = true;
1037 objectType = ptr->getPointeeType();
1038 } else {
1039 baseObjectIsPointer = false;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001040 }
John McCall5808ce42011-02-03 08:15:49 +00001041 baseQuals = objectType.getQualifiers();
1042
1043 // Case 3: the base of the indirect field is a field and we should
1044 // build an implicit member access.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001045 } else {
1046 // We've found a member of an anonymous struct/union that is
1047 // inside a non-anonymous struct/union, so in a well-formed
1048 // program our base object expression is "this".
John McCall5808ce42011-02-03 08:15:49 +00001049 CXXMethodDecl *method = tryCaptureCXXThis();
1050 if (!method) {
1051 Diag(loc, diag::err_invalid_member_use_in_static_method)
1052 << indirectField->getDeclName();
1053 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001054 }
1055
John McCall5808ce42011-02-03 08:15:49 +00001056 // Our base object expression is "this".
1057 baseObjectExpr =
1058 new (Context) CXXThisExpr(loc, method->getThisType(Context),
1059 /*isImplicit=*/ true);
1060 baseObjectIsPointer = true;
1061 baseQuals = Qualifiers::fromCVRMask(method->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001062 }
1063
1064 // Build the implicit member references to the field of the
1065 // anonymous struct/union.
John McCall5808ce42011-02-03 08:15:49 +00001066 Expr *result = baseObjectExpr;
1067 IndirectFieldDecl::chain_iterator
1068 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCalldfa1edb2010-11-23 20:48:44 +00001069
John McCall5808ce42011-02-03 08:15:49 +00001070 // Build the first member access in the chain with full information.
1071 if (!baseVariable) {
1072 FieldDecl *field = cast<FieldDecl>(*FI);
John McCalldfa1edb2010-11-23 20:48:44 +00001073
John McCall5808ce42011-02-03 08:15:49 +00001074 // FIXME: use the real found-decl info!
1075 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall0953e762009-09-24 19:53:00 +00001076
John McCall5808ce42011-02-03 08:15:49 +00001077 // Make a nameInfo that properly uses the anonymous name.
1078 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall0953e762009-09-24 19:53:00 +00001079
John McCall5808ce42011-02-03 08:15:49 +00001080 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Douglas Gregorf5848322011-02-18 02:44:58 +00001081 EmptySS, field, foundDecl,
John McCall5808ce42011-02-03 08:15:49 +00001082 memberNameInfo).take();
1083 baseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +00001084
John McCall5808ce42011-02-03 08:15:49 +00001085 // FIXME: check qualified member access
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001086 }
1087
John McCall5808ce42011-02-03 08:15:49 +00001088 // In all cases, we should now skip the first declaration in the chain.
1089 ++FI;
1090
Douglas Gregorf5848322011-02-18 02:44:58 +00001091 while (FI != FEnd) {
1092 FieldDecl *field = cast<FieldDecl>(*FI++);
John McCall5808ce42011-02-03 08:15:49 +00001093
1094 // FIXME: these are somewhat meaningless
1095 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1096 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall5808ce42011-02-03 08:15:49 +00001097
1098 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Douglas Gregorf5848322011-02-18 02:44:58 +00001099 (FI == FEnd? SS : EmptySS), field,
1100 foundDecl, memberNameInfo)
John McCall5808ce42011-02-03 08:15:49 +00001101 .take();
1102 }
1103
1104 return Owned(result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001105}
1106
Abramo Bagnara25777432010-08-11 22:01:17 +00001107/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001108/// possibly a list of template arguments.
1109///
1110/// If this produces template arguments, it is permitted to call
1111/// DecomposeTemplateName.
1112///
1113/// This actually loses a lot of source location information for
1114/// non-standard name kinds; we should consider preserving that in
1115/// some way.
1116static void DecomposeUnqualifiedId(Sema &SemaRef,
1117 const UnqualifiedId &Id,
1118 TemplateArgumentListInfo &Buffer,
Abramo Bagnara25777432010-08-11 22:01:17 +00001119 DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00001120 const TemplateArgumentListInfo *&TemplateArgs) {
1121 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1122 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1123 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1124
1125 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1126 Id.TemplateId->getTemplateArgs(),
1127 Id.TemplateId->NumArgs);
1128 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1129 TemplateArgsPtr.release();
1130
John McCall2b5289b2010-08-23 07:28:44 +00001131 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001132 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1133 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001134 TemplateArgs = &Buffer;
1135 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001136 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001137 TemplateArgs = 0;
1138 }
1139}
1140
John McCallaa81e162009-12-01 22:10:20 +00001141/// Determines if the given class is provably not derived from all of
1142/// the prospective base classes.
1143static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1144 CXXRecordDecl *Record,
1145 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCallb1b42562009-12-01 22:28:41 +00001146 if (Bases.count(Record->getCanonicalDecl()))
John McCallaa81e162009-12-01 22:10:20 +00001147 return false;
1148
Douglas Gregor952b0172010-02-11 01:04:33 +00001149 RecordDecl *RD = Record->getDefinition();
John McCallb1b42562009-12-01 22:28:41 +00001150 if (!RD) return false;
1151 Record = cast<CXXRecordDecl>(RD);
1152
John McCallaa81e162009-12-01 22:10:20 +00001153 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1154 E = Record->bases_end(); I != E; ++I) {
1155 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1156 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1157 if (!BaseRT) return false;
1158
1159 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCallaa81e162009-12-01 22:10:20 +00001160 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1161 return false;
1162 }
1163
1164 return true;
1165}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001166
John McCallaa81e162009-12-01 22:10:20 +00001167enum IMAKind {
1168 /// The reference is definitely not an instance member access.
1169 IMA_Static,
1170
1171 /// The reference may be an implicit instance member access.
1172 IMA_Mixed,
1173
1174 /// The reference may be to an instance member, but it is invalid if
1175 /// so, because the context is not an instance method.
1176 IMA_Mixed_StaticContext,
1177
1178 /// The reference may be to an instance member, but it is invalid if
1179 /// so, because the context is from an unrelated class.
1180 IMA_Mixed_Unrelated,
1181
1182 /// The reference is definitely an implicit instance member access.
1183 IMA_Instance,
1184
1185 /// The reference may be to an unresolved using declaration.
1186 IMA_Unresolved,
1187
1188 /// The reference may be to an unresolved using declaration and the
1189 /// context is not an instance method.
1190 IMA_Unresolved_StaticContext,
1191
John McCallaa81e162009-12-01 22:10:20 +00001192 /// All possible referrents are instance members and the current
1193 /// context is not an instance method.
1194 IMA_Error_StaticContext,
1195
1196 /// All possible referrents are instance members of an unrelated
1197 /// class.
1198 IMA_Error_Unrelated
1199};
1200
1201/// The given lookup names class member(s) and is not being used for
1202/// an address-of-member expression. Classify the type of access
1203/// according to whether it's possible that this reference names an
1204/// instance member. This is best-effort; it is okay to
1205/// conservatively answer "yes", in which case some errors will simply
1206/// not be caught until template-instantiation.
1207static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1208 const LookupResult &R) {
John McCall3b4294e2009-12-16 12:17:52 +00001209 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCallaa81e162009-12-01 22:10:20 +00001210
John McCallea1471e2010-05-20 01:18:31 +00001211 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCallaa81e162009-12-01 22:10:20 +00001212 bool isStaticContext =
John McCallea1471e2010-05-20 01:18:31 +00001213 (!isa<CXXMethodDecl>(DC) ||
1214 cast<CXXMethodDecl>(DC)->isStatic());
John McCallaa81e162009-12-01 22:10:20 +00001215
1216 if (R.isUnresolvableResult())
1217 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1218
1219 // Collect all the declaring classes of instance members we find.
1220 bool hasNonInstance = false;
Sebastian Redlf9780002010-11-26 16:28:07 +00001221 bool hasField = false;
John McCallaa81e162009-12-01 22:10:20 +00001222 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1223 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall161755a2010-04-06 21:38:20 +00001224 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00001225
John McCall161755a2010-04-06 21:38:20 +00001226 if (D->isCXXInstanceMember()) {
Sebastian Redlf9780002010-11-26 16:28:07 +00001227 if (dyn_cast<FieldDecl>(D))
1228 hasField = true;
1229
John McCallaa81e162009-12-01 22:10:20 +00001230 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCallaa81e162009-12-01 22:10:20 +00001231 Classes.insert(R->getCanonicalDecl());
1232 }
1233 else
1234 hasNonInstance = true;
1235 }
1236
1237 // If we didn't find any instance members, it can't be an implicit
1238 // member reference.
1239 if (Classes.empty())
1240 return IMA_Static;
1241
1242 // If the current context is not an instance method, it can't be
1243 // an implicit member reference.
Sebastian Redlf9780002010-11-26 16:28:07 +00001244 if (isStaticContext) {
1245 if (hasNonInstance)
1246 return IMA_Mixed_StaticContext;
1247
1248 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1249 // C++0x [expr.prim.general]p10:
1250 // An id-expression that denotes a non-static data member or non-static
1251 // member function of a class can only be used:
1252 // (...)
1253 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1254 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1255 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1256 if (isUnevaluatedExpression)
1257 return IMA_Mixed_StaticContext;
1258 }
1259
1260 return IMA_Error_StaticContext;
1261 }
John McCallaa81e162009-12-01 22:10:20 +00001262
1263 // If we can prove that the current context is unrelated to all the
1264 // declaring classes, it can't be an implicit member reference (in
1265 // which case it's an error if any of those members are selected).
1266 if (IsProvablyNotDerivedFrom(SemaRef,
John McCallea1471e2010-05-20 01:18:31 +00001267 cast<CXXMethodDecl>(DC)->getParent(),
John McCallaa81e162009-12-01 22:10:20 +00001268 Classes))
1269 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1270
1271 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1272}
1273
1274/// Diagnose a reference to a field with no object available.
1275static void DiagnoseInstanceReference(Sema &SemaRef,
1276 const CXXScopeSpec &SS,
John McCall5808ce42011-02-03 08:15:49 +00001277 NamedDecl *rep,
1278 const DeclarationNameInfo &nameInfo) {
1279 SourceLocation Loc = nameInfo.getLoc();
John McCallaa81e162009-12-01 22:10:20 +00001280 SourceRange Range(Loc);
1281 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1282
John McCall5808ce42011-02-03 08:15:49 +00001283 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCallaa81e162009-12-01 22:10:20 +00001284 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1285 if (MD->isStatic()) {
1286 // "invalid use of member 'x' in static member function"
1287 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCall5808ce42011-02-03 08:15:49 +00001288 << Range << nameInfo.getName();
John McCallaa81e162009-12-01 22:10:20 +00001289 return;
1290 }
1291 }
1292
1293 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCall5808ce42011-02-03 08:15:49 +00001294 << nameInfo.getName() << Range;
John McCallaa81e162009-12-01 22:10:20 +00001295 return;
1296 }
1297
1298 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +00001299}
1300
John McCall578b69b2009-12-16 08:11:27 +00001301/// Diagnose an empty lookup.
1302///
1303/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001304bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1305 CorrectTypoContext CTC) {
John McCall578b69b2009-12-16 08:11:27 +00001306 DeclarationName Name = R.getLookupName();
1307
John McCall578b69b2009-12-16 08:11:27 +00001308 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001309 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001310 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1311 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001312 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001313 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001314 diagnostic_suggest = diag::err_undeclared_use_suggest;
1315 }
John McCall578b69b2009-12-16 08:11:27 +00001316
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001317 // If the original lookup was an unqualified lookup, fake an
1318 // unqualified lookup. This is useful when (for example) the
1319 // original lookup would not have found something because it was a
1320 // dependent name.
Nick Lewycky03d98c52010-07-06 19:51:49 +00001321 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001322 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +00001323 if (isa<CXXRecordDecl>(DC)) {
1324 LookupQualifiedName(R, DC);
1325
1326 if (!R.empty()) {
1327 // Don't give errors about ambiguities in this lookup.
1328 R.suppressDiagnostics();
1329
1330 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1331 bool isInstance = CurMethod &&
1332 CurMethod->isInstance() &&
1333 DC == CurMethod->getParent();
1334
1335 // Give a code modification hint to insert 'this->'.
1336 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1337 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +00001338 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +00001339 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1340 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001341 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +00001342 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +00001343 if (DepMethod) {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001344 Diag(R.getNameLoc(), diagnostic) << Name
1345 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1346 QualType DepThisType = DepMethod->getThisType(Context);
1347 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1348 R.getNameLoc(), DepThisType, false);
1349 TemplateArgumentListInfo TList;
1350 if (ULE->hasExplicitTemplateArgs())
1351 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001352
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001353 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00001354 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001355 CXXDependentScopeMemberExpr *DepExpr =
1356 CXXDependentScopeMemberExpr::Create(
1357 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001358 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001359 R.getLookupNameInfo(), &TList);
1360 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +00001361 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001362 // FIXME: we should be able to handle this case too. It is correct
1363 // to add this-> here. This is a workaround for PR7947.
1364 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +00001365 }
Nick Lewycky03d98c52010-07-06 19:51:49 +00001366 } else {
John McCall578b69b2009-12-16 08:11:27 +00001367 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001368 }
John McCall578b69b2009-12-16 08:11:27 +00001369
1370 // Do we really want to note all of these?
1371 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1372 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1373
1374 // Tell the callee to try to recover.
1375 return false;
1376 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001377
1378 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001379 }
1380 }
1381
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001382 // We didn't find anything, so try to correct for a typo.
Douglas Gregoraaf87162010-04-14 20:04:41 +00001383 DeclarationName Corrected;
Daniel Dunbardc32cdf2010-06-02 15:46:52 +00001384 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001385 if (!R.empty()) {
1386 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1387 if (SS.isEmpty())
1388 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1389 << FixItHint::CreateReplacement(R.getNameLoc(),
1390 R.getLookupName().getAsString());
1391 else
1392 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1393 << Name << computeDeclContext(SS, false) << R.getLookupName()
1394 << SS.getRange()
1395 << FixItHint::CreateReplacement(R.getNameLoc(),
1396 R.getLookupName().getAsString());
1397 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1398 Diag(ND->getLocation(), diag::note_previous_decl)
1399 << ND->getDeclName();
1400
1401 // Tell the callee to try to recover.
1402 return false;
1403 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001404
Douglas Gregoraaf87162010-04-14 20:04:41 +00001405 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1406 // FIXME: If we ended up with a typo for a type name or
1407 // Objective-C class name, we're in trouble because the parser
1408 // is in the wrong place to recover. Suggest the typo
1409 // correction, but don't make it a fix-it since we're not going
1410 // to recover well anyway.
1411 if (SS.isEmpty())
1412 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1413 else
1414 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1415 << Name << computeDeclContext(SS, false) << R.getLookupName()
1416 << SS.getRange();
1417
1418 // Don't try to recover; it won't work.
1419 return true;
1420 }
1421 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001422 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001423 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001424 if (SS.isEmpty())
Douglas Gregoraaf87162010-04-14 20:04:41 +00001425 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001426 else
Douglas Gregord203a162010-01-01 00:15:04 +00001427 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001428 << Name << computeDeclContext(SS, false) << Corrected
1429 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001430 return true;
1431 }
Douglas Gregord203a162010-01-01 00:15:04 +00001432 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001433 }
1434
1435 // Emit a special diagnostic for failed member lookups.
1436 // FIXME: computing the declaration context might fail here (?)
1437 if (!SS.isEmpty()) {
1438 Diag(R.getNameLoc(), diag::err_no_member)
1439 << Name << computeDeclContext(SS, false)
1440 << SS.getRange();
1441 return true;
1442 }
1443
John McCall578b69b2009-12-16 08:11:27 +00001444 // Give up, we can't recover.
1445 Diag(R.getNameLoc(), diagnostic) << Name;
1446 return true;
1447}
1448
Douglas Gregorca45da02010-11-02 20:36:02 +00001449ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1450 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001451 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1452 if (!IDecl)
1453 return 0;
1454 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1455 if (!ClassImpDecl)
1456 return 0;
Douglas Gregorca45da02010-11-02 20:36:02 +00001457 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001458 if (!property)
1459 return 0;
1460 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregorca45da02010-11-02 20:36:02 +00001461 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1462 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001463 return 0;
1464 return property;
1465}
1466
Douglas Gregorca45da02010-11-02 20:36:02 +00001467bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1468 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1469 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1470 if (!IDecl)
1471 return false;
1472 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1473 if (!ClassImpDecl)
1474 return false;
1475 if (ObjCPropertyImplDecl *PIDecl
1476 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1477 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1478 PIDecl->getPropertyIvarDecl())
1479 return false;
1480
1481 return true;
1482}
1483
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001484static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001485 LookupResult &Lookup,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001486 IdentifierInfo *II,
1487 SourceLocation NameLoc) {
1488 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001489 bool LookForIvars;
1490 if (Lookup.empty())
1491 LookForIvars = true;
1492 else if (CurMeth->isClassMethod())
1493 LookForIvars = false;
1494 else
1495 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahaniand0fbadd2011-01-26 00:57:01 +00001496 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1497 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001498 if (!LookForIvars)
1499 return 0;
1500
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001501 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1502 if (!IDecl)
1503 return 0;
1504 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001505 if (!ClassImpDecl)
1506 return 0;
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001507 bool DynamicImplSeen = false;
1508 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1509 if (!property)
1510 return 0;
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001511 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001512 DynamicImplSeen =
1513 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001514 // property implementation has a designated ivar. No need to assume a new
1515 // one.
1516 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1517 return 0;
1518 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001519 if (!DynamicImplSeen) {
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001520 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1521 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001522 NameLoc, NameLoc,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001523 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian75049662010-12-15 23:29:04 +00001524 ObjCIvarDecl::Private,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001525 (Expr *)0, true);
1526 ClassImpDecl->addDecl(Ivar);
1527 IDecl->makeDeclVisibleInContext(Ivar, false);
1528 property->setPropertyIvarDecl(Ivar);
1529 return Ivar;
1530 }
1531 return 0;
1532}
1533
John McCall60d7b3a2010-08-24 06:29:42 +00001534ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001535 CXXScopeSpec &SS,
1536 UnqualifiedId &Id,
1537 bool HasTrailingLParen,
1538 bool isAddressOfOperand) {
John McCallf7a1a742009-11-24 19:00:30 +00001539 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1540 "cannot be direct & operand and have a trailing lparen");
1541
1542 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001543 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001544
John McCall129e2df2009-11-30 22:42:35 +00001545 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001546
1547 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001548 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001549 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnara25777432010-08-11 22:01:17 +00001550 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001551
Abramo Bagnara25777432010-08-11 22:01:17 +00001552 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001553 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001554 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001555
John McCallf7a1a742009-11-24 19:00:30 +00001556 // C++ [temp.dep.expr]p3:
1557 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001558 // -- an identifier that was declared with a dependent type,
1559 // (note: handled after lookup)
1560 // -- a template-id that is dependent,
1561 // (note: handled in BuildTemplateIdExpr)
1562 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001563 // -- a nested-name-specifier that contains a class-name that
1564 // names a dependent type.
1565 // Determine whether this is a member of an unknown specialization;
1566 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001567 bool DependentID = false;
1568 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1569 Name.getCXXNameType()->isDependentType()) {
1570 DependentID = true;
1571 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001572 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001573 if (RequireCompleteDeclContext(SS, DC))
1574 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001575 } else {
1576 DependentID = true;
1577 }
1578 }
1579
Chris Lattner337e5502011-02-18 01:27:55 +00001580 if (DependentID)
Abramo Bagnara25777432010-08-11 22:01:17 +00001581 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001582 TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001583
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001584 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001585 // Perform the required lookup.
Abramo Bagnara25777432010-08-11 22:01:17 +00001586 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001587 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001588 // Lookup the template name again to correctly establish the context in
1589 // which it was found. This is really unfortunate as we already did the
1590 // lookup to determine that it was a template name in the first place. If
1591 // this becomes a performance hit, we can work harder to preserve those
1592 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001593 bool MemberOfUnknownSpecialization;
1594 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1595 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001596
1597 if (MemberOfUnknownSpecialization ||
1598 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1599 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1600 TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001601 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001602 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001603 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001604
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001605 // If the result might be in a dependent base class, this is a dependent
1606 // id-expression.
1607 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1608 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1609 TemplateArgs);
1610
John McCallf7a1a742009-11-24 19:00:30 +00001611 // If this reference is in an Objective-C method, then we need to do
1612 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001613 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001614 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001615 if (E.isInvalid())
1616 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001617
Chris Lattner337e5502011-02-18 01:27:55 +00001618 if (Expr *Ex = E.takeAs<Expr>())
1619 return Owned(Ex);
1620
1621 // Synthesize ivars lazily.
Fariborz Jahaniane776f882011-01-03 18:08:02 +00001622 if (getLangOptions().ObjCDefaultSynthProperties &&
1623 getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahaniande267602010-11-17 19:41:23 +00001624 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1625 if (const ObjCPropertyDecl *Property =
1626 canSynthesizeProvisionalIvar(II)) {
1627 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1628 Diag(Property->getLocation(), diag::note_property_declare);
1629 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001630 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1631 isAddressOfOperand);
Fariborz Jahaniande267602010-11-17 19:41:23 +00001632 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001633 }
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001634 // for further use, this must be set to false if in class method.
1635 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001636 }
Chris Lattner8a934232008-03-31 00:36:02 +00001637 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001638
John McCallf7a1a742009-11-24 19:00:30 +00001639 if (R.isAmbiguous())
1640 return ExprError();
1641
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001642 // Determine whether this name might be a candidate for
1643 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001644 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001645
John McCallf7a1a742009-11-24 19:00:30 +00001646 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001647 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001648 // in C90, extension in C99, forbidden in C++).
1649 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1650 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1651 if (D) R.addDecl(D);
1652 }
1653
1654 // If this name wasn't predeclared and if this is not a function
1655 // call, diagnose the problem.
1656 if (R.empty()) {
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001657 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001658 return ExprError();
1659
1660 assert(!R.empty() &&
1661 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001662
1663 // If we found an Objective-C instance variable, let
1664 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001665 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001666 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1667 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001668 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001669 assert(E.isInvalid() || E.get());
1670 return move(E);
1671 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001672 }
1673 }
Mike Stump1eb44332009-09-09 15:08:12 +00001674
John McCallf7a1a742009-11-24 19:00:30 +00001675 // This is guaranteed from this point on.
1676 assert(!R.empty() || ADL);
1677
John McCallaa81e162009-12-01 22:10:20 +00001678 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001679 // C++ [class.mfct.non-static]p3:
1680 // When an id-expression that is not part of a class member access
1681 // syntax and not used to form a pointer to member is used in the
1682 // body of a non-static member function of class X, if name lookup
1683 // resolves the name in the id-expression to a non-static non-type
1684 // member of some class C, the id-expression is transformed into a
1685 // class member access expression using (*this) as the
1686 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001687 //
1688 // But we don't actually need to do this for '&' operands if R
1689 // resolved to a function or overloaded function set, because the
1690 // expression is ill-formed if it actually works out to be a
1691 // non-static member function:
1692 //
1693 // C++ [expr.ref]p4:
1694 // Otherwise, if E1.E2 refers to a non-static member function. . .
1695 // [t]he expression can be used only as the left-hand operand of a
1696 // member function call.
1697 //
1698 // There are other safeguards against such uses, but it's important
1699 // to get this right here so that we don't end up making a
1700 // spuriously dependent expression if we're inside a dependent
1701 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001702 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001703 bool MightBeImplicitMember;
1704 if (!isAddressOfOperand)
1705 MightBeImplicitMember = true;
1706 else if (!SS.isEmpty())
1707 MightBeImplicitMember = false;
1708 else if (R.isOverloadedResult())
1709 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001710 else if (R.isUnresolvableResult())
1711 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001712 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001713 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1714 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001715
1716 if (MightBeImplicitMember)
John McCall3b4294e2009-12-16 12:17:52 +00001717 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001718 }
1719
John McCallf7a1a742009-11-24 19:00:30 +00001720 if (TemplateArgs)
1721 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001722
John McCallf7a1a742009-11-24 19:00:30 +00001723 return BuildDeclarationNameExpr(SS, R, ADL);
1724}
1725
John McCall3b4294e2009-12-16 12:17:52 +00001726/// Builds an expression which might be an implicit member expression.
John McCall60d7b3a2010-08-24 06:29:42 +00001727ExprResult
John McCall3b4294e2009-12-16 12:17:52 +00001728Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1729 LookupResult &R,
1730 const TemplateArgumentListInfo *TemplateArgs) {
1731 switch (ClassifyImplicitMemberAccess(*this, R)) {
1732 case IMA_Instance:
1733 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1734
John McCall3b4294e2009-12-16 12:17:52 +00001735 case IMA_Mixed:
1736 case IMA_Mixed_Unrelated:
1737 case IMA_Unresolved:
1738 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1739
1740 case IMA_Static:
1741 case IMA_Mixed_StaticContext:
1742 case IMA_Unresolved_StaticContext:
1743 if (TemplateArgs)
1744 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1745 return BuildDeclarationNameExpr(SS, R, false);
1746
1747 case IMA_Error_StaticContext:
1748 case IMA_Error_Unrelated:
John McCall5808ce42011-02-03 08:15:49 +00001749 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
1750 R.getLookupNameInfo());
John McCall3b4294e2009-12-16 12:17:52 +00001751 return ExprError();
1752 }
1753
1754 llvm_unreachable("unexpected instance member access kind");
1755 return ExprError();
1756}
1757
John McCall129e2df2009-11-30 22:42:35 +00001758/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1759/// declaration name, generally during template instantiation.
1760/// There's a large number of things which don't need to be done along
1761/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001762ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001763Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001764 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001765 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001766 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00001767 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00001768
John McCall77bb1aa2010-05-01 00:40:08 +00001769 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001770 return ExprError();
1771
Abramo Bagnara25777432010-08-11 22:01:17 +00001772 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001773 LookupQualifiedName(R, DC);
1774
1775 if (R.isAmbiguous())
1776 return ExprError();
1777
1778 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001779 Diag(NameInfo.getLoc(), diag::err_no_member)
1780 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001781 return ExprError();
1782 }
1783
1784 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1785}
1786
1787/// LookupInObjCMethod - The parser has read a name in, and Sema has
1788/// detected that we're currently inside an ObjC method. Perform some
1789/// additional lookup.
1790///
1791/// Ideally, most of this would be done by lookup, but there's
1792/// actually quite a lot of extra work involved.
1793///
1794/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001795ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001796Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001797 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001798 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001799 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001800
John McCallf7a1a742009-11-24 19:00:30 +00001801 // There are two cases to handle here. 1) scoped lookup could have failed,
1802 // in which case we should look for an ivar. 2) scoped lookup could have
1803 // found a decl, but that decl is outside the current instance method (i.e.
1804 // a global variable). In these two cases, we do a lookup for an ivar with
1805 // this name, if the lookup sucedes, we replace it our current decl.
1806
1807 // If we're in a class method, we don't normally want to look for
1808 // ivars. But if we don't find anything else, and there's an
1809 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001810 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001811
1812 bool LookForIvars;
1813 if (Lookup.empty())
1814 LookForIvars = true;
1815 else if (IsClassMethod)
1816 LookForIvars = false;
1817 else
1818 LookForIvars = (Lookup.isSingleResult() &&
1819 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001820 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001821 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001822 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001823 ObjCInterfaceDecl *ClassDeclared;
1824 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1825 // Diagnose using an ivar in a class method.
1826 if (IsClassMethod)
1827 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1828 << IV->getDeclName());
1829
1830 // If we're referencing an invalid decl, just return this as a silent
1831 // error node. The error diagnostic was already emitted on the decl.
1832 if (IV->isInvalidDecl())
1833 return ExprError();
1834
1835 // Check if referencing a field with __attribute__((deprecated)).
1836 if (DiagnoseUseOfDecl(IV, Loc))
1837 return ExprError();
1838
1839 // Diagnose the use of an ivar outside of the declaring class.
1840 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1841 ClassDeclared != IFace)
1842 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1843
1844 // FIXME: This should use a new expr for a direct reference, don't
1845 // turn this into Self->ivar, just return a BareIVarExpr or something.
1846 IdentifierInfo &II = Context.Idents.get("self");
1847 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001848 SelfName.setIdentifier(&II, SourceLocation());
John McCallf7a1a742009-11-24 19:00:30 +00001849 CXXScopeSpec SelfScopeSpec;
John McCall60d7b3a2010-08-24 06:29:42 +00001850 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001851 SelfName, false, false);
1852 if (SelfExpr.isInvalid())
1853 return ExprError();
1854
John McCall409fa9a2010-12-06 20:48:59 +00001855 Expr *SelfE = SelfExpr.take();
1856 DefaultLvalueConversion(SelfE);
1857
John McCallf7a1a742009-11-24 19:00:30 +00001858 MarkDeclarationReferenced(Loc, IV);
1859 return Owned(new (Context)
1860 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John McCall409fa9a2010-12-06 20:48:59 +00001861 SelfE, true, true));
John McCallf7a1a742009-11-24 19:00:30 +00001862 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001863 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001864 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00001865 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001866 ObjCInterfaceDecl *ClassDeclared;
1867 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1868 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1869 IFace == ClassDeclared)
1870 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1871 }
1872 }
1873
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001874 if (Lookup.empty() && II && AllowBuiltinCreation) {
1875 // FIXME. Consolidate this with similar code in LookupName.
1876 if (unsigned BuiltinID = II->getBuiltinID()) {
1877 if (!(getLangOptions().CPlusPlus &&
1878 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1879 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1880 S, Lookup.isForRedeclaration(),
1881 Lookup.getNameLoc());
1882 if (D) Lookup.addDecl(D);
1883 }
1884 }
1885 }
John McCallf7a1a742009-11-24 19:00:30 +00001886 // Sentinel value saying that we didn't do anything special.
1887 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001888}
John McCallba135432009-11-21 08:51:07 +00001889
John McCall6bb80172010-03-30 21:47:33 +00001890/// \brief Cast a base object to a member's actual type.
1891///
1892/// Logically this happens in three phases:
1893///
1894/// * First we cast from the base type to the naming class.
1895/// The naming class is the class into which we were looking
1896/// when we found the member; it's the qualifier type if a
1897/// qualifier was provided, and otherwise it's the base type.
1898///
1899/// * Next we cast from the naming class to the declaring class.
1900/// If the member we found was brought into a class's scope by
1901/// a using declaration, this is that class; otherwise it's
1902/// the class declaring the member.
1903///
1904/// * Finally we cast from the declaring class to the "true"
1905/// declaring class of the member. This conversion does not
1906/// obey access control.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001907bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00001908Sema::PerformObjectMemberConversion(Expr *&From,
1909 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00001910 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001911 NamedDecl *Member) {
1912 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1913 if (!RD)
1914 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001915
Douglas Gregor5fccd362010-03-03 23:55:11 +00001916 QualType DestRecordType;
1917 QualType DestType;
1918 QualType FromRecordType;
1919 QualType FromType = From->getType();
1920 bool PointerConversions = false;
1921 if (isa<FieldDecl>(Member)) {
1922 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001923
Douglas Gregor5fccd362010-03-03 23:55:11 +00001924 if (FromType->getAs<PointerType>()) {
1925 DestType = Context.getPointerType(DestRecordType);
1926 FromRecordType = FromType->getPointeeType();
1927 PointerConversions = true;
1928 } else {
1929 DestType = DestRecordType;
1930 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001931 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001932 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1933 if (Method->isStatic())
1934 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001935
Douglas Gregor5fccd362010-03-03 23:55:11 +00001936 DestType = Method->getThisType(Context);
1937 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001938
Douglas Gregor5fccd362010-03-03 23:55:11 +00001939 if (FromType->getAs<PointerType>()) {
1940 FromRecordType = FromType->getPointeeType();
1941 PointerConversions = true;
1942 } else {
1943 FromRecordType = FromType;
1944 DestType = DestRecordType;
1945 }
1946 } else {
1947 // No conversion necessary.
1948 return false;
1949 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001950
Douglas Gregor5fccd362010-03-03 23:55:11 +00001951 if (DestType->isDependentType() || FromType->isDependentType())
1952 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001953
Douglas Gregor5fccd362010-03-03 23:55:11 +00001954 // If the unqualified types are the same, no conversion is necessary.
1955 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1956 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001957
John McCall6bb80172010-03-30 21:47:33 +00001958 SourceRange FromRange = From->getSourceRange();
1959 SourceLocation FromLoc = FromRange.getBegin();
1960
John McCall5baba9d2010-08-25 10:28:54 +00001961 ExprValueKind VK = CastCategory(From);
Sebastian Redl906082e2010-07-20 04:20:21 +00001962
Douglas Gregor5fccd362010-03-03 23:55:11 +00001963 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001964 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00001965 // class name.
1966 //
1967 // If the member was a qualified name and the qualified referred to a
1968 // specific base subobject type, we'll cast to that intermediate type
1969 // first and then to the object in which the member is declared. That allows
1970 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1971 //
1972 // class Base { public: int x; };
1973 // class Derived1 : public Base { };
1974 // class Derived2 : public Base { };
1975 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1976 //
1977 // void VeryDerived::f() {
1978 // x = 17; // error: ambiguous base subobjects
1979 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1980 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001981 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00001982 QualType QType = QualType(Qualifier->getAsType(), 0);
1983 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1984 assert(QType->isRecordType() && "lookup done with non-record type");
1985
1986 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1987
1988 // In C++98, the qualifier type doesn't actually have to be a base
1989 // type of the object type, in which case we just ignore it.
1990 // Otherwise build the appropriate casts.
1991 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00001992 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00001993 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00001994 FromLoc, FromRange, &BasePath))
John McCall6bb80172010-03-30 21:47:33 +00001995 return true;
1996
Douglas Gregor5fccd362010-03-03 23:55:11 +00001997 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00001998 QType = Context.getPointerType(QType);
John McCall5baba9d2010-08-25 10:28:54 +00001999 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2000 VK, &BasePath);
John McCall6bb80172010-03-30 21:47:33 +00002001
2002 FromType = QType;
2003 FromRecordType = QRecordType;
2004
2005 // If the qualifier type was the same as the destination type,
2006 // we're done.
2007 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2008 return false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002009 }
2010 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002011
John McCall6bb80172010-03-30 21:47:33 +00002012 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002013
John McCall6bb80172010-03-30 21:47:33 +00002014 // If we actually found the member through a using declaration, cast
2015 // down to the using declaration's type.
2016 //
2017 // Pointer equality is fine here because only one declaration of a
2018 // class ever has member declarations.
2019 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2020 assert(isa<UsingShadowDecl>(FoundDecl));
2021 QualType URecordType = Context.getTypeDeclType(
2022 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2023
2024 // We only need to do this if the naming-class to declaring-class
2025 // conversion is non-trivial.
2026 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2027 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002028 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002029 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002030 FromLoc, FromRange, &BasePath))
John McCall6bb80172010-03-30 21:47:33 +00002031 return true;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002032
John McCall6bb80172010-03-30 21:47:33 +00002033 QualType UType = URecordType;
2034 if (PointerConversions)
2035 UType = Context.getPointerType(UType);
John McCall2de56d12010-08-25 11:45:40 +00002036 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00002037 VK, &BasePath);
John McCall6bb80172010-03-30 21:47:33 +00002038 FromType = UType;
2039 FromRecordType = URecordType;
2040 }
2041
2042 // We don't do access control for the conversion from the
2043 // declaring class to the true declaring class.
2044 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002045 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002046
John McCallf871d0c2010-08-07 06:22:56 +00002047 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002048 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2049 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002050 IgnoreAccess))
Douglas Gregor5fccd362010-03-03 23:55:11 +00002051 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002052
John McCall2de56d12010-08-25 11:45:40 +00002053 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00002054 VK, &BasePath);
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00002055 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002056}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002057
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002058/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00002059static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00002060 const CXXScopeSpec &SS, ValueDecl *Member,
John McCall161755a2010-04-06 21:38:20 +00002061 DeclAccessPair FoundDecl,
Abramo Bagnara25777432010-08-11 22:01:17 +00002062 const DeclarationNameInfo &MemberNameInfo,
2063 QualType Ty,
John McCallf89e55a2010-11-18 06:31:45 +00002064 ExprValueKind VK, ExprObjectKind OK,
John McCallf7a1a742009-11-24 19:00:30 +00002065 const TemplateArgumentListInfo *TemplateArgs = 0) {
Douglas Gregor40d96a62011-02-28 21:54:11 +00002066 return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
Abramo Bagnara25777432010-08-11 22:01:17 +00002067 Member, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002068 TemplateArgs, Ty, VK, OK);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002069}
2070
John McCalldfa1edb2010-11-23 20:48:44 +00002071static ExprResult
2072BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2073 const CXXScopeSpec &SS, FieldDecl *Field,
2074 DeclAccessPair FoundDecl,
2075 const DeclarationNameInfo &MemberNameInfo) {
2076 // x.a is an l-value if 'a' has a reference type. Otherwise:
2077 // x.a is an l-value/x-value/pr-value if the base is (and note
2078 // that *x is always an l-value), except that if the base isn't
2079 // an ordinary object then we must have an rvalue.
2080 ExprValueKind VK = VK_LValue;
2081 ExprObjectKind OK = OK_Ordinary;
2082 if (!IsArrow) {
2083 if (BaseExpr->getObjectKind() == OK_Ordinary)
2084 VK = BaseExpr->getValueKind();
2085 else
2086 VK = VK_RValue;
2087 }
2088 if (VK != VK_RValue && Field->isBitField())
2089 OK = OK_BitField;
2090
2091 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2092 QualType MemberType = Field->getType();
2093 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2094 MemberType = Ref->getPointeeType();
2095 VK = VK_LValue;
2096 } else {
2097 QualType BaseType = BaseExpr->getType();
2098 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2099
2100 Qualifiers BaseQuals = BaseType.getQualifiers();
2101
2102 // GC attributes are never picked up by members.
2103 BaseQuals.removeObjCGCAttr();
2104
2105 // CVR attributes from the base are picked up by members,
2106 // except that 'mutable' members don't pick up 'const'.
2107 if (Field->isMutable()) BaseQuals.removeConst();
2108
2109 Qualifiers MemberQuals
2110 = S.Context.getCanonicalType(MemberType).getQualifiers();
2111
2112 // TR 18037 does not allow fields to be declared with address spaces.
2113 assert(!MemberQuals.hasAddressSpace());
2114
2115 Qualifiers Combined = BaseQuals + MemberQuals;
2116 if (Combined != MemberQuals)
2117 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2118 }
2119
2120 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
2121 if (S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2122 FoundDecl, Field))
2123 return ExprError();
2124 return S.Owned(BuildMemberExpr(S.Context, BaseExpr, IsArrow, SS,
2125 Field, FoundDecl, MemberNameInfo,
2126 MemberType, VK, OK));
2127}
2128
John McCallaa81e162009-12-01 22:10:20 +00002129/// Builds an implicit member access expression. The current context
2130/// is known to be an instance method, and the given unqualified lookup
2131/// set is known to contain only instance members, at least one of which
2132/// is from an appropriate type.
John McCall60d7b3a2010-08-24 06:29:42 +00002133ExprResult
John McCallaa81e162009-12-01 22:10:20 +00002134Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2135 LookupResult &R,
2136 const TemplateArgumentListInfo *TemplateArgs,
2137 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00002138 assert(!R.empty() && !R.isAmbiguous());
2139
John McCall5808ce42011-02-03 08:15:49 +00002140 SourceLocation loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00002141
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002142 // We may have found a field within an anonymous union or struct
2143 // (C++ [class.union]).
John McCallf7a1a742009-11-24 19:00:30 +00002144 // FIXME: template-ids inside anonymous structs?
Francois Pichet87c2e122010-11-21 06:08:52 +00002145 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCall5808ce42011-02-03 08:15:49 +00002146 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet87c2e122010-11-21 06:08:52 +00002147
John McCall5808ce42011-02-03 08:15:49 +00002148 // If this is known to be an instance access, go ahead and build an
2149 // implicit 'this' expression now.
John McCallaa81e162009-12-01 22:10:20 +00002150 // 'this' expression now.
John McCall5808ce42011-02-03 08:15:49 +00002151 CXXMethodDecl *method = tryCaptureCXXThis();
2152 assert(method && "didn't correctly pre-flight capture of 'this'");
2153
2154 QualType thisType = method->getThisType(Context);
2155 Expr *baseExpr = 0; // null signifies implicit access
John McCallaa81e162009-12-01 22:10:20 +00002156 if (IsKnownInstance) {
Douglas Gregor828a1972010-01-07 23:12:05 +00002157 SourceLocation Loc = R.getNameLoc();
2158 if (SS.getRange().isValid())
2159 Loc = SS.getRange().getBegin();
John McCall5808ce42011-02-03 08:15:49 +00002160 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
Douglas Gregor88a35142008-12-22 05:46:06 +00002161 }
2162
John McCall5808ce42011-02-03 08:15:49 +00002163 return BuildMemberReferenceExpr(baseExpr, thisType,
John McCallaa81e162009-12-01 22:10:20 +00002164 /*OpLoc*/ SourceLocation(),
2165 /*IsArrow*/ true,
John McCallc2233c52010-01-15 08:34:02 +00002166 SS,
2167 /*FirstQualifierInScope*/ 0,
2168 R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00002169}
2170
John McCallf7a1a742009-11-24 19:00:30 +00002171bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002172 const LookupResult &R,
2173 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002174 // Only when used directly as the postfix-expression of a call.
2175 if (!HasTrailingLParen)
2176 return false;
2177
2178 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002179 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002180 return false;
2181
2182 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00002183 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002184 return false;
2185
2186 // Turn off ADL when we find certain kinds of declarations during
2187 // normal lookup:
2188 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2189 NamedDecl *D = *I;
2190
2191 // C++0x [basic.lookup.argdep]p3:
2192 // -- a declaration of a class member
2193 // Since using decls preserve this property, we check this on the
2194 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002195 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002196 return false;
2197
2198 // C++0x [basic.lookup.argdep]p3:
2199 // -- a block-scope function declaration that is not a
2200 // using-declaration
2201 // NOTE: we also trigger this for function templates (in fact, we
2202 // don't check the decl type at all, since all other decl types
2203 // turn off ADL anyway).
2204 if (isa<UsingShadowDecl>(D))
2205 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2206 else if (D->getDeclContext()->isFunctionOrMethod())
2207 return false;
2208
2209 // C++0x [basic.lookup.argdep]p3:
2210 // -- a declaration that is neither a function or a function
2211 // template
2212 // And also for builtin functions.
2213 if (isa<FunctionDecl>(D)) {
2214 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2215
2216 // But also builtin functions.
2217 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2218 return false;
2219 } else if (!isa<FunctionTemplateDecl>(D))
2220 return false;
2221 }
2222
2223 return true;
2224}
2225
2226
John McCallba135432009-11-21 08:51:07 +00002227/// Diagnoses obvious problems with the use of the given declaration
2228/// as an expression. This is only actually called for lookups that
2229/// were not overloaded, and it doesn't promise that the declaration
2230/// will in fact be used.
2231static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2232 if (isa<TypedefDecl>(D)) {
2233 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2234 return true;
2235 }
2236
2237 if (isa<ObjCInterfaceDecl>(D)) {
2238 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2239 return true;
2240 }
2241
2242 if (isa<NamespaceDecl>(D)) {
2243 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2244 return true;
2245 }
2246
2247 return false;
2248}
2249
John McCall60d7b3a2010-08-24 06:29:42 +00002250ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002251Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002252 LookupResult &R,
2253 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002254 // If this is a single, fully-resolved result and we don't need ADL,
2255 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002256 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002257 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2258 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002259
2260 // We only need to check the declaration if there's exactly one
2261 // result, because in the overloaded case the results can only be
2262 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002263 if (R.isSingleResult() &&
2264 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002265 return ExprError();
2266
John McCallc373d482010-01-27 01:50:18 +00002267 // Otherwise, just build an unresolved lookup expression. Suppress
2268 // any lookup-related diagnostics; we'll hash these out later, when
2269 // we've picked a target.
2270 R.suppressDiagnostics();
2271
John McCallba135432009-11-21 08:51:07 +00002272 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002273 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002274 SS.getWithLocInContext(Context),
2275 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002276 NeedsADL, R.isOverloadedResult(),
2277 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002278
2279 return Owned(ULE);
2280}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002281
John McCallba135432009-11-21 08:51:07 +00002282/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002283ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002284Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002285 const DeclarationNameInfo &NameInfo,
2286 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002287 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002288 assert(!isa<FunctionTemplateDecl>(D) &&
2289 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002290
Abramo Bagnara25777432010-08-11 22:01:17 +00002291 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002292 if (CheckDeclInExpr(*this, Loc, D))
2293 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002294
Douglas Gregor9af2f522009-12-01 16:58:18 +00002295 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2296 // Specifically diagnose references to class templates that are missing
2297 // a template argument list.
2298 Diag(Loc, diag::err_template_decl_ref)
2299 << Template << SS.getRange();
2300 Diag(Template->getLocation(), diag::note_template_decl_here);
2301 return ExprError();
2302 }
2303
2304 // Make sure that we're referring to a value.
2305 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2306 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002307 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002308 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002309 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002310 return ExprError();
2311 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002312
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002313 // Check whether this declaration can be used. Note that we suppress
2314 // this check when we're going to perform argument-dependent lookup
2315 // on this function name, because this might not be the function
2316 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002317 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002318 return ExprError();
2319
Steve Naroffdd972f22008-09-05 22:11:13 +00002320 // Only create DeclRefExpr's for valid Decl's.
2321 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002322 return ExprError();
2323
John McCall5808ce42011-02-03 08:15:49 +00002324 // Handle members of anonymous structs and unions. If we got here,
2325 // and the reference is to a class member indirect field, then this
2326 // must be the subject of a pointer-to-member expression.
2327 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2328 if (!indirectField->isCXXClassMember())
2329 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2330 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002331
Chris Lattner639e2d32008-10-20 05:16:36 +00002332 // If the identifier reference is inside a block, and it refers to a value
2333 // that is outside the block, create a BlockDeclRefExpr instead of a
2334 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2335 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00002336 //
Chris Lattner639e2d32008-10-20 05:16:36 +00002337 // We do not do this for things like enum constants, global variables, etc,
2338 // as they do not get snapshotted.
2339 //
John McCall6b5a61b2011-02-07 10:33:21 +00002340 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCall469a1eb2011-02-02 13:00:07 +00002341 case CR_Error:
2342 return ExprError();
Mike Stump0d6fd572010-01-05 02:56:35 +00002343
John McCall469a1eb2011-02-02 13:00:07 +00002344 case CR_Capture:
John McCall6b5a61b2011-02-07 10:33:21 +00002345 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2346 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2347
2348 case CR_CaptureByRef:
2349 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2350 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCall76a40212011-02-09 01:13:10 +00002351
2352 case CR_NoCapture: {
2353 // If this reference is not in a block or if the referenced
2354 // variable is within the block, create a normal DeclRefExpr.
2355
2356 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002357 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002358
2359 switch (D->getKind()) {
2360 // Ignore all the non-ValueDecl kinds.
2361#define ABSTRACT_DECL(kind)
2362#define VALUE(type, base)
2363#define DECL(type, base) \
2364 case Decl::type:
2365#include "clang/AST/DeclNodes.inc"
2366 llvm_unreachable("invalid value decl kind");
2367 return ExprError();
2368
2369 // These shouldn't make it here.
2370 case Decl::ObjCAtDefsField:
2371 case Decl::ObjCIvar:
2372 llvm_unreachable("forming non-member reference to ivar?");
2373 return ExprError();
2374
2375 // Enum constants are always r-values and never references.
2376 // Unresolved using declarations are dependent.
2377 case Decl::EnumConstant:
2378 case Decl::UnresolvedUsingValue:
2379 valueKind = VK_RValue;
2380 break;
2381
2382 // Fields and indirect fields that got here must be for
2383 // pointer-to-member expressions; we just call them l-values for
2384 // internal consistency, because this subexpression doesn't really
2385 // exist in the high-level semantics.
2386 case Decl::Field:
2387 case Decl::IndirectField:
2388 assert(getLangOptions().CPlusPlus &&
2389 "building reference to field in C?");
2390
2391 // These can't have reference type in well-formed programs, but
2392 // for internal consistency we do this anyway.
2393 type = type.getNonReferenceType();
2394 valueKind = VK_LValue;
2395 break;
2396
2397 // Non-type template parameters are either l-values or r-values
2398 // depending on the type.
2399 case Decl::NonTypeTemplateParm: {
2400 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2401 type = reftype->getPointeeType();
2402 valueKind = VK_LValue; // even if the parameter is an r-value reference
2403 break;
2404 }
2405
2406 // For non-references, we need to strip qualifiers just in case
2407 // the template parameter was declared as 'const int' or whatever.
2408 valueKind = VK_RValue;
2409 type = type.getUnqualifiedType();
2410 break;
2411 }
2412
2413 case Decl::Var:
2414 // In C, "extern void blah;" is valid and is an r-value.
2415 if (!getLangOptions().CPlusPlus &&
2416 !type.hasQualifiers() &&
2417 type->isVoidType()) {
2418 valueKind = VK_RValue;
2419 break;
2420 }
2421 // fallthrough
2422
2423 case Decl::ImplicitParam:
2424 case Decl::ParmVar:
2425 // These are always l-values.
2426 valueKind = VK_LValue;
2427 type = type.getNonReferenceType();
2428 break;
2429
2430 case Decl::Function: {
2431 // Functions are l-values in C++.
2432 if (getLangOptions().CPlusPlus) {
2433 valueKind = VK_LValue;
2434 break;
2435 }
2436
2437 // C99 DR 316 says that, if a function type comes from a
2438 // function definition (without a prototype), that type is only
2439 // used for checking compatibility. Therefore, when referencing
2440 // the function, we pretend that we don't have the full function
2441 // type.
2442 if (!cast<FunctionDecl>(VD)->hasPrototype())
2443 if (const FunctionProtoType *proto = type->getAs<FunctionProtoType>())
2444 type = Context.getFunctionNoProtoType(proto->getResultType(),
2445 proto->getExtInfo());
2446
2447 // Functions are r-values in C.
2448 valueKind = VK_RValue;
2449 break;
2450 }
2451
2452 case Decl::CXXMethod:
2453 // C++ methods are l-values if static, r-values if non-static.
2454 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2455 valueKind = VK_LValue;
2456 break;
2457 }
2458 // fallthrough
2459
2460 case Decl::CXXConversion:
2461 case Decl::CXXDestructor:
2462 case Decl::CXXConstructor:
2463 valueKind = VK_RValue;
2464 break;
2465 }
2466
2467 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2468 }
2469
John McCall469a1eb2011-02-02 13:00:07 +00002470 }
John McCallf89e55a2010-11-18 06:31:45 +00002471
John McCall6b5a61b2011-02-07 10:33:21 +00002472 llvm_unreachable("unknown capture result");
2473 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002474}
2475
John McCall60d7b3a2010-08-24 06:29:42 +00002476ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Sebastian Redlcd965b92009-01-18 18:53:16 +00002477 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002478 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002479
Reid Spencer5f016e22007-07-11 17:01:13 +00002480 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00002481 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002482 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2483 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2484 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002485 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002486
Chris Lattnerfa28b302008-01-12 08:14:25 +00002487 // Pre-defined identifiers are of type char[x], where x is the length of the
2488 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002489
Anders Carlsson3a082d82009-09-08 18:24:21 +00002490 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002491 if (!currentDecl && getCurBlock())
2492 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002493 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002494 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002495 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002496 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002497
Anders Carlsson773f3972009-09-11 01:22:35 +00002498 QualType ResTy;
2499 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2500 ResTy = Context.DependentTy;
2501 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002502 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002503
Anders Carlsson773f3972009-09-11 01:22:35 +00002504 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00002505 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002506 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2507 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002508 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002509}
2510
John McCall60d7b3a2010-08-24 06:29:42 +00002511ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002512 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002513 bool Invalid = false;
2514 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2515 if (Invalid)
2516 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002517
Benjamin Kramerddeea562010-02-27 13:44:12 +00002518 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2519 PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00002520 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002521 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002522
Chris Lattnere8337df2009-12-30 21:19:39 +00002523 QualType Ty;
2524 if (!getLangOptions().CPlusPlus)
2525 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2526 else if (Literal.isWide())
2527 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedman136b0cd2010-02-03 18:21:45 +00002528 else if (Literal.isMultiChar())
2529 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002530 else
2531 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002532
Sebastian Redle91b3bc2009-01-20 22:23:13 +00002533 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2534 Literal.isWide(),
Chris Lattnere8337df2009-12-30 21:19:39 +00002535 Ty, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002536}
2537
John McCall60d7b3a2010-08-24 06:29:42 +00002538ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002539 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00002540 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2541 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002542 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00002543 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002544 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00002545 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002546 }
Ted Kremenek28396602009-01-13 23:19:12 +00002547
Reid Spencer5f016e22007-07-11 17:01:13 +00002548 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002549 // Add padding so that NumericLiteralParser can overread by one character.
2550 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002551 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002552
Reid Spencer5f016e22007-07-11 17:01:13 +00002553 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002554 bool Invalid = false;
2555 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2556 if (Invalid)
2557 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002558
Mike Stump1eb44332009-09-09 15:08:12 +00002559 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002560 Tok.getLocation(), PP);
2561 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002562 return ExprError();
2563
Chris Lattner5d661452007-08-26 03:42:43 +00002564 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002565
Chris Lattner5d661452007-08-26 03:42:43 +00002566 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002567 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002568 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002569 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002570 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002571 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002572 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002573 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002574
2575 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2576
John McCall94c939d2009-12-24 09:08:04 +00002577 using llvm::APFloat;
2578 APFloat Val(Format);
2579
2580 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00002581
2582 // Overflow is always an error, but underflow is only an error if
2583 // we underflowed to zero (APFloat reports denormals as underflow).
2584 if ((result & APFloat::opOverflow) ||
2585 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00002586 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002587 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00002588 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00002589 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00002590 APFloat::getLargest(Format).toString(buffer);
2591 } else {
John McCall2a0d7572010-02-26 23:35:57 +00002592 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00002593 APFloat::getSmallest(Format).toString(buffer);
2594 }
2595
2596 Diag(Tok.getLocation(), diagnostic)
2597 << Ty
2598 << llvm::StringRef(buffer.data(), buffer.size());
2599 }
2600
2601 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002602 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002603
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002604 if (Ty == Context.DoubleTy) {
2605 if (getLangOptions().SinglePrecisionConstants) {
2606 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2607 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2608 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
2609 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2610 }
2611 }
Chris Lattner5d661452007-08-26 03:42:43 +00002612 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002613 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002614 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002615 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002616
Neil Boothb9449512007-08-29 22:00:19 +00002617 // long long is a C99 feature.
2618 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00002619 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00002620 Diag(Tok.getLocation(), diag::ext_longlong);
2621
Reid Spencer5f016e22007-07-11 17:01:13 +00002622 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00002623 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002624
Reid Spencer5f016e22007-07-11 17:01:13 +00002625 if (Literal.GetIntegerValue(ResultVal)) {
2626 // If this value didn't fit into uintmax_t, warn and force to ull.
2627 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002628 Ty = Context.UnsignedLongLongTy;
2629 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002630 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002631 } else {
2632 // If this value fits into a ULL, try to figure out what else it fits into
2633 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002634
Reid Spencer5f016e22007-07-11 17:01:13 +00002635 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2636 // be an unsigned int.
2637 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2638
2639 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002640 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002641 if (!Literal.isLong && !Literal.isLongLong) {
2642 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002643 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002644
Reid Spencer5f016e22007-07-11 17:01:13 +00002645 // Does it fit in a unsigned int?
2646 if (ResultVal.isIntN(IntSize)) {
2647 // Does it fit in a signed int?
2648 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002649 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002650 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002651 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002652 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002653 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002654 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002655
Reid Spencer5f016e22007-07-11 17:01:13 +00002656 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002657 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002658 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002659
Reid Spencer5f016e22007-07-11 17:01:13 +00002660 // Does it fit in a unsigned long?
2661 if (ResultVal.isIntN(LongSize)) {
2662 // Does it fit in a signed long?
2663 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002664 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002665 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002666 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002667 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002668 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002669 }
2670
Reid Spencer5f016e22007-07-11 17:01:13 +00002671 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002672 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002673 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002674
Reid Spencer5f016e22007-07-11 17:01:13 +00002675 // Does it fit in a unsigned long long?
2676 if (ResultVal.isIntN(LongLongSize)) {
2677 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002678 // To be compatible with MSVC, hex integer literals ending with the
2679 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002680 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2681 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002682 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002683 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002684 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002685 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002686 }
2687 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002688
Reid Spencer5f016e22007-07-11 17:01:13 +00002689 // If we still couldn't decide a type, we probably have something that
2690 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002691 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002692 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002693 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002694 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002695 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002696
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002697 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002698 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002699 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002700 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002701 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002702
Chris Lattner5d661452007-08-26 03:42:43 +00002703 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2704 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002705 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002706 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002707
2708 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002709}
2710
John McCall60d7b3a2010-08-24 06:29:42 +00002711ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCall9ae2f072010-08-23 23:25:46 +00002712 SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002713 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002714 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002715}
2716
2717/// The UsualUnaryConversions() function is *not* called by this routine.
2718/// See C99 6.3.2.1p[2-4] for more details.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002719bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2720 SourceLocation OpLoc,
2721 SourceRange ExprRange,
2722 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl28507842009-02-26 14:39:58 +00002723 if (exprType->isDependentType())
2724 return false;
2725
Sebastian Redl5d484e82009-11-23 17:18:46 +00002726 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2727 // the result is the size of the referenced type."
2728 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2729 // result shall be the alignment of the referenced type."
2730 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2731 exprType = Ref->getPointeeType();
2732
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002733 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2734 // scalar or vector data type argument..."
2735 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2736 // type (C99 6.2.5p18) or void.
2737 if (ExprKind == UETT_VecStep) {
2738 if (!(exprType->isArithmeticType() || exprType->isVoidType() ||
2739 exprType->isVectorType())) {
2740 Diag(OpLoc, diag::err_vecstep_non_scalar_vector_type)
2741 << exprType << ExprRange;
2742 return true;
2743 }
2744 }
2745
Reid Spencer5f016e22007-07-11 17:01:13 +00002746 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00002747 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002748 // alignof(function) is allowed as an extension.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002749 if (ExprKind == UETT_SizeOf)
2750 Diag(OpLoc, diag::ext_sizeof_function_type)
2751 << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00002752 return false;
2753 }
Mike Stump1eb44332009-09-09 15:08:12 +00002754
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002755 // Allow sizeof(void)/alignof(void) as an extension. vec_step(void) is not
2756 // an extension, as void is a built-in scalar type (OpenCL 1.1 6.1.1).
Chris Lattner01072922009-01-24 19:46:37 +00002757 if (exprType->isVoidType()) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002758 if (ExprKind != UETT_VecStep)
2759 Diag(OpLoc, diag::ext_sizeof_void_type)
2760 << ExprKind << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00002761 return false;
2762 }
Mike Stump1eb44332009-09-09 15:08:12 +00002763
Chris Lattner1efaa952009-04-24 00:30:45 +00002764 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00002765 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002766 << ExprKind << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00002767 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002768
Chris Lattner1efaa952009-04-24 00:30:45 +00002769 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCallc12c5bb2010-05-15 11:32:37 +00002770 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002771 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002772 << exprType << (ExprKind == UETT_SizeOf)
2773 << ExprRange;
Chris Lattner5cb10d32009-04-24 22:30:50 +00002774 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00002775 }
Mike Stump1eb44332009-09-09 15:08:12 +00002776
Chris Lattner1efaa952009-04-24 00:30:45 +00002777 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002778}
2779
John McCall2a984ca2010-10-12 00:20:44 +00002780static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2781 SourceRange ExprRange) {
Chris Lattner31e21e02009-01-24 20:17:12 +00002782 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00002783
Mike Stump1eb44332009-09-09 15:08:12 +00002784 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00002785 if (isa<DeclRefExpr>(E))
2786 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00002787
2788 // Cannot know anything else if the expression is dependent.
2789 if (E->isTypeDependent())
2790 return false;
2791
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002792 if (E->getBitField()) {
John McCall2a984ca2010-10-12 00:20:44 +00002793 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002794 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00002795 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002796
2797 // Alignment of a field access is always okay, so long as it isn't a
2798 // bit-field.
2799 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00002800 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002801 return false;
2802
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002803 return S.CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
2804 UETT_AlignOf);
2805}
2806
2807bool Sema::CheckVecStepExpr(Expr *E, SourceLocation OpLoc,
2808 SourceRange ExprRange) {
2809 E = E->IgnoreParens();
2810
2811 // Cannot know anything else if the expression is dependent.
2812 if (E->isTypeDependent())
2813 return false;
2814
2815 return CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
2816 UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00002817}
2818
Douglas Gregorba498172009-03-13 21:01:28 +00002819/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002820ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002821Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2822 SourceLocation OpLoc,
2823 UnaryExprOrTypeTrait ExprKind,
2824 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00002825 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00002826 return ExprError();
2827
John McCalla93c9342009-12-07 02:54:59 +00002828 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00002829
Douglas Gregorba498172009-03-13 21:01:28 +00002830 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002831 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00002832 return ExprError();
2833
2834 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002835 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2836 Context.getSizeType(),
2837 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00002838}
2839
2840/// \brief Build a sizeof or alignof expression given an expression
2841/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002842ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002843Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2844 UnaryExprOrTypeTrait ExprKind,
2845 SourceRange R) {
Douglas Gregorba498172009-03-13 21:01:28 +00002846 // Verify that the operand is valid.
2847 bool isInvalid = false;
2848 if (E->isTypeDependent()) {
2849 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002850 } else if (ExprKind == UETT_AlignOf) {
John McCall2a984ca2010-10-12 00:20:44 +00002851 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002852 } else if (ExprKind == UETT_VecStep) {
2853 isInvalid = CheckVecStepExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002854 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00002855 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2856 isInvalid = true;
John McCall2cd11fe2010-10-12 02:09:17 +00002857 } else if (E->getType()->isPlaceholderType()) {
2858 ExprResult PE = CheckPlaceholderExpr(E, OpLoc);
2859 if (PE.isInvalid()) return ExprError();
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002860 return CreateUnaryExprOrTypeTraitExpr(PE.take(), OpLoc, ExprKind, R);
Douglas Gregorba498172009-03-13 21:01:28 +00002861 } else {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002862 isInvalid = CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, R,
2863 UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00002864 }
2865
2866 if (isInvalid)
2867 return ExprError();
2868
2869 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002870 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, E,
2871 Context.getSizeType(),
2872 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00002873}
2874
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002875/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2876/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00002877/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00002878ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002879Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2880 UnaryExprOrTypeTrait ExprKind, bool isType,
2881 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002882 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002883 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002884
Sebastian Redl05189992008-11-11 17:56:53 +00002885 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00002886 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00002887 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002888 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00002889 }
Sebastian Redl05189992008-11-11 17:56:53 +00002890
Douglas Gregorba498172009-03-13 21:01:28 +00002891 Expr *ArgEx = (Expr *)TyOrEx;
John McCall60d7b3a2010-08-24 06:29:42 +00002892 ExprResult Result
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002893 = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind,
2894 ArgEx->getSourceRange());
Douglas Gregorba498172009-03-13 21:01:28 +00002895
Douglas Gregorba498172009-03-13 21:01:28 +00002896 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002897}
2898
John McCall09431682010-11-18 19:01:18 +00002899static QualType CheckRealImagOperand(Sema &S, Expr *&V, SourceLocation Loc,
2900 bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00002901 if (V->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00002902 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002903
John McCallf6a16482010-12-04 03:47:34 +00002904 // _Real and _Imag are only l-values for normal l-values.
2905 if (V->getObjectKind() != OK_Ordinary)
John McCall409fa9a2010-12-06 20:48:59 +00002906 S.DefaultLvalueConversion(V);
John McCallf6a16482010-12-04 03:47:34 +00002907
Chris Lattnercc26ed72007-08-26 05:39:26 +00002908 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00002909 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00002910 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002911
Chris Lattnercc26ed72007-08-26 05:39:26 +00002912 // Otherwise they pass through real integer and floating point types here.
2913 if (V->getType()->isArithmeticType())
2914 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002915
John McCall2cd11fe2010-10-12 02:09:17 +00002916 // Test for placeholders.
John McCall09431682010-11-18 19:01:18 +00002917 ExprResult PR = S.CheckPlaceholderExpr(V, Loc);
John McCall2cd11fe2010-10-12 02:09:17 +00002918 if (PR.isInvalid()) return QualType();
2919 if (PR.take() != V) {
2920 V = PR.take();
John McCall09431682010-11-18 19:01:18 +00002921 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall2cd11fe2010-10-12 02:09:17 +00002922 }
2923
Chris Lattnercc26ed72007-08-26 05:39:26 +00002924 // Reject anything else.
John McCall09431682010-11-18 19:01:18 +00002925 S.Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
Chris Lattnerba27e2a2009-02-17 08:12:06 +00002926 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00002927 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00002928}
2929
2930
Reid Spencer5f016e22007-07-11 17:01:13 +00002931
John McCall60d7b3a2010-08-24 06:29:42 +00002932ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00002933Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002934 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00002935 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00002936 switch (Kind) {
2937 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00002938 case tok::plusplus: Opc = UO_PostInc; break;
2939 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002940 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002941
John McCall9ae2f072010-08-23 23:25:46 +00002942 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00002943}
2944
John McCall09431682010-11-18 19:01:18 +00002945/// Expressions of certain arbitrary types are forbidden by C from
2946/// having l-value type. These are:
2947/// - 'void', but not qualified void
2948/// - function types
2949///
2950/// The exact rule here is C99 6.3.2.1:
2951/// An lvalue is an expression with an object type or an incomplete
2952/// type other than void.
2953static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
2954 return ((T->isVoidType() && !T.hasQualifiers()) ||
2955 T->isFunctionType());
2956}
2957
John McCall60d7b3a2010-08-24 06:29:42 +00002958ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002959Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2960 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00002961 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00002962 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00002963 if (Result.isInvalid()) return ExprError();
2964 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00002965
John McCall9ae2f072010-08-23 23:25:46 +00002966 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00002967
Douglas Gregor337c6b92008-11-19 17:17:41 +00002968 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002969 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002970 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00002971 Context.DependentTy,
2972 VK_LValue, OK_Ordinary,
2973 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002974 }
2975
Mike Stump1eb44332009-09-09 15:08:12 +00002976 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00002977 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00002978 LHSExp->getType()->isEnumeralType() ||
2979 RHSExp->getType()->isRecordType() ||
2980 RHSExp->getType()->isEnumeralType())) {
John McCall9ae2f072010-08-23 23:25:46 +00002981 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00002982 }
2983
John McCall9ae2f072010-08-23 23:25:46 +00002984 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00002985}
2986
2987
John McCall60d7b3a2010-08-24 06:29:42 +00002988ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002989Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2990 Expr *Idx, SourceLocation RLoc) {
2991 Expr *LHSExp = Base;
2992 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00002993
Chris Lattner12d9ff62007-07-16 00:14:47 +00002994 // Perform default conversions.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002995 if (!LHSExp->getType()->getAs<VectorType>())
2996 DefaultFunctionArrayLvalueConversion(LHSExp);
2997 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002998
Chris Lattner12d9ff62007-07-16 00:14:47 +00002999 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003000 ExprValueKind VK = VK_LValue;
3001 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003002
Reid Spencer5f016e22007-07-11 17:01:13 +00003003 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003004 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003005 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003006 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003007 Expr *BaseExpr, *IndexExpr;
3008 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003009 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3010 BaseExpr = LHSExp;
3011 IndexExpr = RHSExp;
3012 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003013 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003014 BaseExpr = LHSExp;
3015 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003016 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003017 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00003018 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00003019 BaseExpr = RHSExp;
3020 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003021 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003022 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003023 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003024 BaseExpr = LHSExp;
3025 IndexExpr = RHSExp;
3026 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003027 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003028 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003029 // Handle the uncommon case of "123[Ptr]".
3030 BaseExpr = RHSExp;
3031 IndexExpr = LHSExp;
3032 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003033 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003034 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003035 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003036 VK = LHSExp->getValueKind();
3037 if (VK != VK_RValue)
3038 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003039
Chris Lattner12d9ff62007-07-16 00:14:47 +00003040 // FIXME: need to deal with const...
3041 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003042 } else if (LHSTy->isArrayType()) {
3043 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003044 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003045 // wasn't promoted because of the C90 rule that doesn't
3046 // allow promoting non-lvalue arrays. Warn, then
3047 // force the promotion here.
3048 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3049 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003050 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
John McCall2de56d12010-08-25 11:45:40 +00003051 CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003052 LHSTy = LHSExp->getType();
3053
3054 BaseExpr = LHSExp;
3055 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003056 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003057 } else if (RHSTy->isArrayType()) {
3058 // Same as previous, except for 123[f().a] case
3059 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3060 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003061 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
John McCall2de56d12010-08-25 11:45:40 +00003062 CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003063 RHSTy = RHSExp->getType();
3064
3065 BaseExpr = RHSExp;
3066 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003067 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003068 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003069 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3070 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003071 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003072 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003073 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003074 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3075 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003076
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003077 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003078 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3079 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003080 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3081
Douglas Gregore7450f52009-03-24 19:52:54 +00003082 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003083 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3084 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003085 // incomplete types are not object types.
3086 if (ResultType->isFunctionType()) {
3087 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3088 << ResultType << BaseExpr->getSourceRange();
3089 return ExprError();
3090 }
Mike Stump1eb44332009-09-09 15:08:12 +00003091
Abramo Bagnara46358452010-09-13 06:50:07 +00003092 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3093 // GNU extension: subscripting on pointer to void
3094 Diag(LLoc, diag::ext_gnu_void_ptr)
3095 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003096
3097 // C forbids expressions of unqualified void type from being l-values.
3098 // See IsCForbiddenLValueType.
3099 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003100 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003101 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003102 PDiag(diag::err_subscript_incomplete_type)
3103 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00003104 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003105
Chris Lattner1efaa952009-04-24 00:30:45 +00003106 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00003107 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003108 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3109 << ResultType << BaseExpr->getSourceRange();
3110 return ExprError();
3111 }
Mike Stump1eb44332009-09-09 15:08:12 +00003112
John McCall09431682010-11-18 19:01:18 +00003113 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3114 !IsCForbiddenLValueType(Context, ResultType));
3115
Mike Stumpeed9cac2009-02-19 03:04:26 +00003116 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003117 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003118}
3119
John McCall09431682010-11-18 19:01:18 +00003120/// Check an ext-vector component access expression.
3121///
3122/// VK should be set in advance to the value kind of the base
3123/// expression.
3124static QualType
3125CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3126 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00003127 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00003128 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3129 // see FIXME there.
3130 //
3131 // FIXME: This logic can be greatly simplified by splitting it along
3132 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00003133 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00003134
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003135 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00003136 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00003137
Mike Stumpeed9cac2009-02-19 03:04:26 +00003138 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00003139 // special names that indicate a subset of exactly half the elements are
3140 // to be selected.
3141 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003142
Nate Begeman353417a2009-01-18 01:47:54 +00003143 // This flag determines whether or not CompName has an 's' char prefix,
3144 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00003145 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00003146
John McCall09431682010-11-18 19:01:18 +00003147 bool HasRepeated = false;
3148 bool HasIndex[16] = {};
3149
3150 int Idx;
3151
Nate Begeman8a997642008-05-09 06:41:27 +00003152 // Check that we've found one of the special components, or that the component
3153 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003154 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00003155 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3156 HalvingSwizzle = true;
John McCall09431682010-11-18 19:01:18 +00003157 } else if (!HexSwizzle &&
3158 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3159 do {
3160 if (HasIndex[Idx]) HasRepeated = true;
3161 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00003162 compStr++;
John McCall09431682010-11-18 19:01:18 +00003163 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3164 } else {
3165 if (HexSwizzle) compStr++;
3166 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3167 if (HasIndex[Idx]) HasRepeated = true;
3168 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00003169 compStr++;
John McCall09431682010-11-18 19:01:18 +00003170 }
Chris Lattner88dca042007-08-02 22:33:49 +00003171 }
Nate Begeman353417a2009-01-18 01:47:54 +00003172
Mike Stumpeed9cac2009-02-19 03:04:26 +00003173 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003174 // We didn't get to the end of the string. This means the component names
3175 // didn't come from the same set *or* we encountered an illegal name.
John McCall09431682010-11-18 19:01:18 +00003176 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00003177 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003178 return QualType();
3179 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003180
Nate Begeman353417a2009-01-18 01:47:54 +00003181 // Ensure no component accessor exceeds the width of the vector type it
3182 // operates on.
3183 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00003184 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00003185
3186 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003187 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00003188
3189 while (*compStr) {
3190 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall09431682010-11-18 19:01:18 +00003191 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begeman353417a2009-01-18 01:47:54 +00003192 << baseType << SourceRange(CompLoc);
3193 return QualType();
3194 }
3195 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003196 }
Nate Begeman8a997642008-05-09 06:41:27 +00003197
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003198 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003199 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003200 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00003201 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00003202 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman0479a0b2009-12-15 18:13:04 +00003203 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00003204 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00003205 if (HexSwizzle)
3206 CompSize--;
3207
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003208 if (CompSize == 1)
3209 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003210
John McCall09431682010-11-18 19:01:18 +00003211 if (HasRepeated) VK = VK_RValue;
3212
3213 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003214 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00003215 // diagostics look bad. We want extended vector types to appear built-in.
John McCall09431682010-11-18 19:01:18 +00003216 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3217 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3218 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00003219 }
3220 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003221}
3222
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003223static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00003224 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003225 const Selector &Sel,
3226 ASTContext &Context) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003227 if (Member)
3228 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3229 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003230 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003231 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00003232
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003233 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3234 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003235 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3236 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003237 return D;
3238 }
3239 return 0;
3240}
3241
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003242static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3243 IdentifierInfo *Member,
3244 const Selector &Sel,
3245 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003246 // Check protocols on qualified interfaces.
3247 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003248 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003249 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003250 if (Member)
3251 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3252 GDecl = PD;
3253 break;
3254 }
3255 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003256 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003257 GDecl = OMD;
3258 break;
3259 }
3260 }
3261 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003262 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003263 E = QIdTy->qual_end(); I != E; ++I) {
3264 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003265 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3266 Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003267 if (GDecl)
3268 return GDecl;
3269 }
3270 }
3271 return GDecl;
3272}
Chris Lattner76a642f2009-02-15 22:43:40 +00003273
John McCall60d7b3a2010-08-24 06:29:42 +00003274ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003275Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCallaa81e162009-12-01 22:10:20 +00003276 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00003277 const CXXScopeSpec &SS,
3278 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003279 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003280 const TemplateArgumentListInfo *TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00003281 // Even in dependent contexts, try to diagnose base expressions with
3282 // obviously wrong types, e.g.:
3283 //
3284 // T* t;
3285 // t.f;
3286 //
3287 // In Obj-C++, however, the above expression is valid, since it could be
3288 // accessing the 'f' property if T is an Obj-C interface. The extra check
3289 // allows this, while still reporting an error if T is a struct pointer.
3290 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00003291 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00003292 if (PT && (!getLangOptions().ObjC1 ||
3293 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00003294 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnara25777432010-08-11 22:01:17 +00003295 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00003296 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00003297 return ExprError();
3298 }
3299 }
3300
Abramo Bagnara25777432010-08-11 22:01:17 +00003301 assert(BaseType->isDependentType() ||
3302 NameInfo.getName().isDependentName() ||
Douglas Gregor01e56ae2010-04-12 20:54:26 +00003303 isDependentScopeSpecifier(SS));
John McCall129e2df2009-11-30 22:42:35 +00003304
3305 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3306 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00003307 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003308 IsArrow, OpLoc,
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003309 SS.getWithLocInContext(Context),
John McCall129e2df2009-11-30 22:42:35 +00003310 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003311 NameInfo, TemplateArgs));
John McCall129e2df2009-11-30 22:42:35 +00003312}
3313
3314/// We know that the given qualified member reference points only to
3315/// declarations which do not belong to the static type of the base
3316/// expression. Diagnose the problem.
3317static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3318 Expr *BaseExpr,
3319 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003320 const CXXScopeSpec &SS,
John McCall5808ce42011-02-03 08:15:49 +00003321 NamedDecl *rep,
3322 const DeclarationNameInfo &nameInfo) {
John McCall2f841ba2009-12-02 03:53:29 +00003323 // If this is an implicit member access, use a different set of
3324 // diagnostics.
3325 if (!BaseExpr)
John McCall5808ce42011-02-03 08:15:49 +00003326 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall129e2df2009-11-30 22:42:35 +00003327
John McCall5808ce42011-02-03 08:15:49 +00003328 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3329 << SS.getRange() << rep << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00003330}
3331
3332// Check whether the declarations we found through a nested-name
3333// specifier in a member expression are actually members of the base
3334// type. The restriction here is:
3335//
3336// C++ [expr.ref]p2:
3337// ... In these cases, the id-expression shall name a
3338// member of the class or of one of its base classes.
3339//
3340// So it's perfectly legitimate for the nested-name specifier to name
3341// an unrelated class, and for us to find an overload set including
3342// decls from classes which are not superclasses, as long as the decl
3343// we actually pick through overload resolution is from a superclass.
3344bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3345 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003346 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003347 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00003348 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3349 if (!BaseRT) {
3350 // We can't check this yet because the base type is still
3351 // dependent.
3352 assert(BaseType->isDependentType());
3353 return false;
3354 }
3355 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00003356
3357 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00003358 // If this is an implicit member reference and we find a
3359 // non-instance member, it's not an error.
John McCall161755a2010-04-06 21:38:20 +00003360 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCallaa81e162009-12-01 22:10:20 +00003361 return false;
John McCall129e2df2009-11-30 22:42:35 +00003362
John McCallaa81e162009-12-01 22:10:20 +00003363 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman02463762010-07-27 20:51:02 +00003364 DeclContext *DC = (*I)->getDeclContext();
3365 while (DC->isTransparentContext())
3366 DC = DC->getParent();
John McCallaa81e162009-12-01 22:10:20 +00003367
Douglas Gregor9d4bb942010-07-28 22:27:52 +00003368 if (!DC->isRecord())
3369 continue;
3370
John McCallaa81e162009-12-01 22:10:20 +00003371 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman02463762010-07-27 20:51:02 +00003372 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCallaa81e162009-12-01 22:10:20 +00003373
3374 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3375 return false;
3376 }
3377
John McCall5808ce42011-02-03 08:15:49 +00003378 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3379 R.getRepresentativeDecl(),
3380 R.getLookupNameInfo());
John McCallaa81e162009-12-01 22:10:20 +00003381 return true;
3382}
3383
3384static bool
3385LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3386 SourceRange BaseRange, const RecordType *RTy,
John McCallad00b772010-06-16 08:42:20 +00003387 SourceLocation OpLoc, CXXScopeSpec &SS,
3388 bool HasTemplateArgs) {
John McCallaa81e162009-12-01 22:10:20 +00003389 RecordDecl *RDecl = RTy->getDecl();
3390 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003391 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCallaa81e162009-12-01 22:10:20 +00003392 << BaseRange))
3393 return true;
3394
John McCallad00b772010-06-16 08:42:20 +00003395 if (HasTemplateArgs) {
3396 // LookupTemplateName doesn't expect these both to exist simultaneously.
3397 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3398
3399 bool MOUS;
3400 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3401 return false;
3402 }
3403
John McCallaa81e162009-12-01 22:10:20 +00003404 DeclContext *DC = RDecl;
3405 if (SS.isSet()) {
3406 // If the member name was a qualified-id, look into the
3407 // nested-name-specifier.
3408 DC = SemaRef.computeDeclContext(SS, false);
3409
John McCall77bb1aa2010-05-01 00:40:08 +00003410 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCall2f841ba2009-12-02 03:53:29 +00003411 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3412 << SS.getRange() << DC;
3413 return true;
3414 }
3415
John McCallaa81e162009-12-01 22:10:20 +00003416 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003417
John McCallaa81e162009-12-01 22:10:20 +00003418 if (!isa<TypeDecl>(DC)) {
3419 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3420 << DC << SS.getRange();
3421 return true;
John McCall129e2df2009-11-30 22:42:35 +00003422 }
3423 }
3424
John McCallaa81e162009-12-01 22:10:20 +00003425 // The record definition is complete, now look up the member.
3426 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00003427
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003428 if (!R.empty())
3429 return false;
3430
3431 // We didn't find anything with the given name, so try to correct
3432 // for typos.
3433 DeclarationName Name = R.getLookupName();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003434 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00003435 !R.empty() &&
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003436 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3437 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3438 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00003439 << FixItHint::CreateReplacement(R.getNameLoc(),
3440 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00003441 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3442 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3443 << ND->getDeclName();
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003444 return false;
3445 } else {
3446 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003447 R.setLookupName(Name);
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003448 }
3449
John McCall129e2df2009-11-30 22:42:35 +00003450 return false;
3451}
3452
John McCall60d7b3a2010-08-24 06:29:42 +00003453ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003454Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003455 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003456 CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003457 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003458 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003459 const TemplateArgumentListInfo *TemplateArgs) {
John McCall2f841ba2009-12-02 03:53:29 +00003460 if (BaseType->isDependentType() ||
3461 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCall9ae2f072010-08-23 23:25:46 +00003462 return ActOnDependentMemberExpr(Base, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003463 IsArrow, OpLoc,
3464 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003465 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003466
Abramo Bagnara25777432010-08-11 22:01:17 +00003467 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00003468
John McCallaa81e162009-12-01 22:10:20 +00003469 // Implicit member accesses.
3470 if (!Base) {
3471 QualType RecordTy = BaseType;
3472 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3473 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3474 RecordTy->getAs<RecordType>(),
John McCallad00b772010-06-16 08:42:20 +00003475 OpLoc, SS, TemplateArgs != 0))
John McCallaa81e162009-12-01 22:10:20 +00003476 return ExprError();
3477
3478 // Explicit member accesses.
3479 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00003480 ExprResult Result =
John McCallaa81e162009-12-01 22:10:20 +00003481 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCalld226f652010-08-21 09:40:31 +00003482 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCallaa81e162009-12-01 22:10:20 +00003483
3484 if (Result.isInvalid()) {
3485 Owned(Base);
3486 return ExprError();
3487 }
3488
3489 if (Result.get())
3490 return move(Result);
Sebastian Redlf3e63372010-05-07 09:25:11 +00003491
3492 // LookupMemberExpr can modify Base, and thus change BaseType
3493 BaseType = Base->getType();
John McCall129e2df2009-11-30 22:42:35 +00003494 }
3495
John McCall9ae2f072010-08-23 23:25:46 +00003496 return BuildMemberReferenceExpr(Base, BaseType,
John McCallc2233c52010-01-15 08:34:02 +00003497 OpLoc, IsArrow, SS, FirstQualifierInScope,
3498 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003499}
3500
John McCall60d7b3a2010-08-24 06:29:42 +00003501ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003502Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCallaa81e162009-12-01 22:10:20 +00003503 SourceLocation OpLoc, bool IsArrow,
3504 const CXXScopeSpec &SS,
John McCallc2233c52010-01-15 08:34:02 +00003505 NamedDecl *FirstQualifierInScope,
John McCall129e2df2009-11-30 22:42:35 +00003506 LookupResult &R,
Douglas Gregor06a9f362010-05-01 20:49:11 +00003507 const TemplateArgumentListInfo *TemplateArgs,
3508 bool SuppressQualifierCheck) {
John McCallaa81e162009-12-01 22:10:20 +00003509 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00003510 if (IsArrow) {
3511 assert(BaseType->isPointerType());
3512 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3513 }
John McCall161755a2010-04-06 21:38:20 +00003514 R.setBaseObjectType(BaseType);
John McCall129e2df2009-11-30 22:42:35 +00003515
Abramo Bagnara25777432010-08-11 22:01:17 +00003516 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3517 DeclarationName MemberName = MemberNameInfo.getName();
3518 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall129e2df2009-11-30 22:42:35 +00003519
3520 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00003521 return ExprError();
3522
John McCall129e2df2009-11-30 22:42:35 +00003523 if (R.empty()) {
3524 // Rederive where we looked up.
3525 DeclContext *DC = (SS.isSet()
3526 ? computeDeclContext(SS, false)
3527 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00003528
John McCall129e2df2009-11-30 22:42:35 +00003529 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00003530 << MemberName << DC
3531 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00003532 return ExprError();
3533 }
3534
John McCallc2233c52010-01-15 08:34:02 +00003535 // Diagnose lookups that find only declarations from a non-base
3536 // type. This is possible for either qualified lookups (which may
3537 // have been qualified with an unrelated type) or implicit member
3538 // expressions (which were found with unqualified lookup and thus
3539 // may have come from an enclosing scope). Note that it's okay for
3540 // lookup to find declarations from a non-base type as long as those
3541 // aren't the ones picked by overload resolution.
3542 if ((SS.isSet() || !BaseExpr ||
3543 (isa<CXXThisExpr>(BaseExpr) &&
3544 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00003545 !SuppressQualifierCheck &&
John McCallc2233c52010-01-15 08:34:02 +00003546 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00003547 return ExprError();
3548
3549 // Construct an unresolved result if we in fact got an unresolved
3550 // result.
3551 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallc373d482010-01-27 01:50:18 +00003552 // Suppress any lookup-related diagnostics; we'll do these when we
3553 // pick a member.
3554 R.suppressDiagnostics();
3555
John McCall129e2df2009-11-30 22:42:35 +00003556 UnresolvedMemberExpr *MemExpr
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003557 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00003558 BaseExpr, BaseExprType,
3559 IsArrow, OpLoc,
Douglas Gregor4c9be892011-02-28 20:01:57 +00003560 SS.getWithLocInContext(Context),
Abramo Bagnara25777432010-08-11 22:01:17 +00003561 MemberNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00003562 TemplateArgs, R.begin(), R.end());
John McCall129e2df2009-11-30 22:42:35 +00003563
3564 return Owned(MemExpr);
3565 }
3566
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003567 assert(R.isSingleResult());
John McCall161755a2010-04-06 21:38:20 +00003568 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall129e2df2009-11-30 22:42:35 +00003569 NamedDecl *MemberDecl = R.getFoundDecl();
3570
3571 // FIXME: diagnose the presence of template arguments now.
3572
3573 // If the decl being referenced had an error, return an error for this
3574 // sub-expr without emitting another error, in order to avoid cascading
3575 // error cases.
3576 if (MemberDecl->isInvalidDecl())
3577 return ExprError();
3578
John McCallaa81e162009-12-01 22:10:20 +00003579 // Handle the implicit-member-access case.
3580 if (!BaseExpr) {
3581 // If this is not an instance member, convert to a non-member access.
John McCall161755a2010-04-06 21:38:20 +00003582 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnara25777432010-08-11 22:01:17 +00003583 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCallaa81e162009-12-01 22:10:20 +00003584
Douglas Gregor828a1972010-01-07 23:12:05 +00003585 SourceLocation Loc = R.getNameLoc();
3586 if (SS.getRange().isValid())
3587 Loc = SS.getRange().getBegin();
3588 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003589 }
3590
John McCall129e2df2009-11-30 22:42:35 +00003591 bool ShouldCheckUse = true;
3592 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3593 // Don't diagnose the use of a virtual member function unless it's
3594 // explicitly qualified.
3595 if (MD->isVirtual() && !SS.isSet())
3596 ShouldCheckUse = false;
3597 }
3598
3599 // Check the use of this member.
3600 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3601 Owned(BaseExpr);
3602 return ExprError();
3603 }
3604
John McCallf6a16482010-12-04 03:47:34 +00003605 // Perform a property load on the base regardless of whether we
3606 // actually need it for the declaration.
3607 if (BaseExpr->getObjectKind() == OK_ObjCProperty)
3608 ConvertPropertyForRValue(BaseExpr);
3609
John McCalldfa1edb2010-11-23 20:48:44 +00003610 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3611 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3612 SS, FD, FoundDecl, MemberNameInfo);
John McCall129e2df2009-11-30 22:42:35 +00003613
Francois Pichet87c2e122010-11-21 06:08:52 +00003614 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3615 // We may have found a field within an anonymous union or struct
3616 // (C++ [class.union]).
John McCall5808ce42011-02-03 08:15:49 +00003617 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCallf6a16482010-12-04 03:47:34 +00003618 BaseExpr, OpLoc);
Francois Pichet87c2e122010-11-21 06:08:52 +00003619
John McCall129e2df2009-11-30 22:42:35 +00003620 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3621 MarkDeclarationReferenced(MemberLoc, Var);
3622 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003623 Var, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003624 Var->getType().getNonReferenceType(),
John McCall09431682010-11-18 19:01:18 +00003625 VK_LValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003626 }
3627
John McCallf89e55a2010-11-18 06:31:45 +00003628 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall129e2df2009-11-30 22:42:35 +00003629 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3630 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003631 MemberFn, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003632 MemberFn->getType(),
3633 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3634 OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003635 }
John McCallf89e55a2010-11-18 06:31:45 +00003636 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall129e2df2009-11-30 22:42:35 +00003637
3638 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3639 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3640 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003641 Enum, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003642 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003643 }
3644
3645 Owned(BaseExpr);
3646
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003647 // We found something that we didn't expect. Complain.
John McCall129e2df2009-11-30 22:42:35 +00003648 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnara25777432010-08-11 22:01:17 +00003649 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003650 << MemberName << BaseType << int(IsArrow);
3651 else
3652 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3653 << MemberName << BaseType << int(IsArrow);
John McCall129e2df2009-11-30 22:42:35 +00003654
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003655 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3656 << MemberName;
Douglas Gregor2b147f02010-04-25 21:15:30 +00003657 R.suppressDiagnostics();
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003658 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00003659}
3660
John McCall028d3972010-12-15 16:46:44 +00003661/// Given that normal member access failed on the given expression,
3662/// and given that the expression's type involves builtin-id or
3663/// builtin-Class, decide whether substituting in the redefinition
3664/// types would be profitable. The redefinition type is whatever
3665/// this translation unit tried to typedef to id/Class; we store
3666/// it to the side and then re-use it in places like this.
3667static bool ShouldTryAgainWithRedefinitionType(Sema &S, Expr *&base) {
3668 const ObjCObjectPointerType *opty
3669 = base->getType()->getAs<ObjCObjectPointerType>();
3670 if (!opty) return false;
3671
3672 const ObjCObjectType *ty = opty->getObjectType();
3673
3674 QualType redef;
3675 if (ty->isObjCId()) {
3676 redef = S.Context.ObjCIdRedefinitionType;
3677 } else if (ty->isObjCClass()) {
3678 redef = S.Context.ObjCClassRedefinitionType;
3679 } else {
3680 return false;
3681 }
3682
3683 // Do the substitution as long as the redefinition type isn't just a
3684 // possibly-qualified pointer to builtin-id or builtin-Class again.
3685 opty = redef->getAs<ObjCObjectPointerType>();
3686 if (opty && !opty->getObjectType()->getInterface() != 0)
3687 return false;
3688
3689 S.ImpCastExprToType(base, redef, CK_BitCast);
3690 return true;
3691}
3692
John McCall129e2df2009-11-30 22:42:35 +00003693/// Look up the given member of the given non-type-dependent
3694/// expression. This can return in one of two ways:
3695/// * If it returns a sentinel null-but-valid result, the caller will
3696/// assume that lookup was performed and the results written into
3697/// the provided structure. It will take over from there.
3698/// * Otherwise, the returned expression will be produced in place of
3699/// an ordinary member expression.
3700///
3701/// The ObjCImpDecl bit is a gross hack that will need to be properly
3702/// fixed for ObjC++.
John McCall60d7b3a2010-08-24 06:29:42 +00003703ExprResult
John McCall129e2df2009-11-30 22:42:35 +00003704Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCall812c1542009-12-07 22:46:59 +00003705 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003706 CXXScopeSpec &SS,
John McCalld226f652010-08-21 09:40:31 +00003707 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003708 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00003709
Steve Naroff3cc4af82007-12-16 21:42:28 +00003710 // Perform default conversions.
3711 DefaultFunctionArrayConversion(BaseExpr);
John McCall5e3c67b2010-12-15 04:42:30 +00003712 if (IsArrow) DefaultLvalueConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003713
Steve Naroffdfa6aae2007-07-26 03:11:44 +00003714 QualType BaseType = BaseExpr->getType();
John McCall129e2df2009-11-30 22:42:35 +00003715 assert(!BaseType->isDependentType());
3716
3717 DeclarationName MemberName = R.getLookupName();
3718 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00003719
John McCall028d3972010-12-15 16:46:44 +00003720 // For later type-checking purposes, turn arrow accesses into dot
3721 // accesses. The only access type we support that doesn't follow
3722 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
3723 // and those never use arrows, so this is unaffected.
3724 if (IsArrow) {
3725 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3726 BaseType = Ptr->getPointeeType();
3727 else if (const ObjCObjectPointerType *Ptr
3728 = BaseType->getAs<ObjCObjectPointerType>())
3729 BaseType = Ptr->getPointeeType();
3730 else if (BaseType->isRecordType()) {
3731 // Recover from arrow accesses to records, e.g.:
3732 // struct MyRecord foo;
3733 // foo->bar
3734 // This is actually well-formed in C++ if MyRecord has an
3735 // overloaded operator->, but that should have been dealt with
3736 // by now.
3737 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3738 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3739 << FixItHint::CreateReplacement(OpLoc, ".");
3740 IsArrow = false;
3741 } else {
3742 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3743 << BaseType << BaseExpr->getSourceRange();
3744 return ExprError();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00003745 }
3746 }
3747
John McCall028d3972010-12-15 16:46:44 +00003748 // Handle field access to simple records.
3749 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
3750 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
3751 RTy, OpLoc, SS, HasTemplateArgs))
3752 return ExprError();
3753
3754 // Returning valid-but-null is how we indicate to the caller that
3755 // the lookup result was filled in.
3756 return Owned((Expr*) 0);
David Chisnall0f436562009-08-17 16:35:33 +00003757 }
John McCall129e2df2009-11-30 22:42:35 +00003758
John McCall028d3972010-12-15 16:46:44 +00003759 // Handle ivar access to Objective-C objects.
3760 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003761 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall028d3972010-12-15 16:46:44 +00003762
3763 // There are three cases for the base type:
3764 // - builtin id (qualified or unqualified)
3765 // - builtin Class (qualified or unqualified)
3766 // - an interface
3767 ObjCInterfaceDecl *IDecl = OTy->getInterface();
3768 if (!IDecl) {
3769 // There's an implicit 'isa' ivar on all objects.
3770 // But we only actually find it this way on objects of type 'id',
3771 // apparently.
3772 if (OTy->isObjCId() && Member->isStr("isa"))
3773 return Owned(new (Context) ObjCIsaExpr(BaseExpr, IsArrow, MemberLoc,
3774 Context.getObjCClassType()));
3775
3776 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3777 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3778 ObjCImpDecl, HasTemplateArgs);
3779 goto fail;
3780 }
3781
3782 ObjCInterfaceDecl *ClassDeclared;
3783 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
3784
3785 if (!IV) {
3786 // Attempt to correct for typos in ivar names.
3787 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3788 LookupMemberName);
3789 if (CorrectTypo(Res, 0, 0, IDecl, false,
3790 IsArrow ? CTC_ObjCIvarLookup
3791 : CTC_ObjCPropertyLookup) &&
3792 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
3793 Diag(R.getNameLoc(),
3794 diag::err_typecheck_member_reference_ivar_suggest)
3795 << IDecl->getDeclName() << MemberName << IV->getDeclName()
3796 << FixItHint::CreateReplacement(R.getNameLoc(),
3797 IV->getNameAsString());
3798 Diag(IV->getLocation(), diag::note_previous_decl)
3799 << IV->getDeclName();
3800 } else {
3801 Res.clear();
3802 Res.setLookupName(Member);
3803
3804 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
3805 << IDecl->getDeclName() << MemberName
3806 << BaseExpr->getSourceRange();
3807 return ExprError();
3808 }
3809 }
3810
3811 // If the decl being referenced had an error, return an error for this
3812 // sub-expr without emitting another error, in order to avoid cascading
3813 // error cases.
3814 if (IV->isInvalidDecl())
3815 return ExprError();
3816
3817 // Check whether we can reference this field.
3818 if (DiagnoseUseOfDecl(IV, MemberLoc))
3819 return ExprError();
3820 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3821 IV->getAccessControl() != ObjCIvarDecl::Package) {
3822 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3823 if (ObjCMethodDecl *MD = getCurMethodDecl())
3824 ClassOfMethodDecl = MD->getClassInterface();
3825 else if (ObjCImpDecl && getCurFunctionDecl()) {
3826 // Case of a c-function declared inside an objc implementation.
3827 // FIXME: For a c-style function nested inside an objc implementation
3828 // class, there is no implementation context available, so we pass
3829 // down the context as argument to this routine. Ideally, this context
3830 // need be passed down in the AST node and somehow calculated from the
3831 // AST for a function decl.
3832 if (ObjCImplementationDecl *IMPD =
3833 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
3834 ClassOfMethodDecl = IMPD->getClassInterface();
3835 else if (ObjCCategoryImplDecl* CatImplClass =
3836 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
3837 ClassOfMethodDecl = CatImplClass->getClassInterface();
3838 }
3839
3840 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3841 if (ClassDeclared != IDecl ||
3842 ClassOfMethodDecl != ClassDeclared)
3843 Diag(MemberLoc, diag::error_private_ivar_access)
3844 << IV->getDeclName();
3845 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3846 // @protected
3847 Diag(MemberLoc, diag::error_protected_ivar_access)
3848 << IV->getDeclName();
3849 }
3850
3851 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3852 MemberLoc, BaseExpr,
3853 IsArrow));
3854 }
3855
3856 // Objective-C property access.
3857 const ObjCObjectPointerType *OPT;
3858 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
3859 // This actually uses the base as an r-value.
3860 DefaultLvalueConversion(BaseExpr);
3861 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr->getType()));
3862
3863 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3864
3865 const ObjCObjectType *OT = OPT->getObjectType();
3866
3867 // id, with and without qualifiers.
3868 if (OT->isObjCId()) {
3869 // Check protocols on qualified interfaces.
3870 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3871 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
3872 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3873 // Check the use of this declaration
3874 if (DiagnoseUseOfDecl(PD, MemberLoc))
3875 return ExprError();
3876
3877 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3878 VK_LValue,
3879 OK_ObjCProperty,
3880 MemberLoc,
3881 BaseExpr));
3882 }
3883
3884 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3885 // Check the use of this method.
3886 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3887 return ExprError();
3888 Selector SetterSel =
3889 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3890 PP.getSelectorTable(), Member);
3891 ObjCMethodDecl *SMD = 0;
3892 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
3893 SetterSel, Context))
3894 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3895 QualType PType = OMD->getSendResultType();
3896
3897 ExprValueKind VK = VK_LValue;
3898 if (!getLangOptions().CPlusPlus &&
3899 IsCForbiddenLValueType(Context, PType))
3900 VK = VK_RValue;
3901 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3902
3903 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
3904 VK, OK,
3905 MemberLoc, BaseExpr));
3906 }
3907 }
3908
3909 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3910 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3911 ObjCImpDecl, HasTemplateArgs);
3912
3913 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3914 << MemberName << BaseType);
3915 }
3916
3917 // 'Class', unqualified only.
3918 if (OT->isObjCClass()) {
3919 // Only works in a method declaration (??!).
3920 ObjCMethodDecl *MD = getCurMethodDecl();
3921 if (!MD) {
3922 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3923 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3924 ObjCImpDecl, HasTemplateArgs);
3925
3926 goto fail;
3927 }
3928
3929 // Also must look for a getter name which uses property syntax.
3930 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003931 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3932 ObjCMethodDecl *Getter;
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003933 if ((Getter = IFace->lookupClassMethod(Sel))) {
3934 // Check the use of this method.
3935 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3936 return ExprError();
John McCall028d3972010-12-15 16:46:44 +00003937 } else
Fariborz Jahanian74b27562010-12-03 23:37:08 +00003938 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003939 // If we found a getter then this may be a valid dot-reference, we
3940 // will look for the matching setter, in case it is needed.
3941 Selector SetterSel =
John McCall028d3972010-12-15 16:46:44 +00003942 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3943 PP.getSelectorTable(), Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003944 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3945 if (!Setter) {
3946 // If this reference is in an @implementation, also check for 'private'
3947 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +00003948 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003949 }
3950 // Look through local category implementations associated with the class.
3951 if (!Setter)
3952 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003953
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003954 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3955 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003956
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003957 if (Getter || Setter) {
3958 QualType PType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003959
John McCall09431682010-11-18 19:01:18 +00003960 ExprValueKind VK = VK_LValue;
3961 if (Getter) {
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003962 PType = Getter->getSendResultType();
John McCall09431682010-11-18 19:01:18 +00003963 if (!getLangOptions().CPlusPlus &&
3964 IsCForbiddenLValueType(Context, PType))
3965 VK = VK_RValue;
3966 } else {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003967 // Get the expression type from Setter's incoming parameter.
3968 PType = (*(Setter->param_end() -1))->getType();
John McCall09431682010-11-18 19:01:18 +00003969 }
3970 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3971
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003972 // FIXME: we must check that the setter has property type.
John McCall12f78a62010-12-02 01:19:52 +00003973 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
3974 PType, VK, OK,
3975 MemberLoc, BaseExpr));
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003976 }
John McCall028d3972010-12-15 16:46:44 +00003977
3978 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3979 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3980 ObjCImpDecl, HasTemplateArgs);
3981
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003982 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall028d3972010-12-15 16:46:44 +00003983 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00003984 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003985
John McCall028d3972010-12-15 16:46:44 +00003986 // Normal property access.
3987 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc,
3988 SourceLocation(), QualType(), false);
Steve Naroff14108da2009-07-10 23:34:53 +00003989 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003990
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003991 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00003992 if (BaseType->isExtVectorType()) {
John McCall5e3c67b2010-12-15 04:42:30 +00003993 // FIXME: this expr should store IsArrow.
Anders Carlsson8f28f992009-08-26 18:25:21 +00003994 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall5e3c67b2010-12-15 04:42:30 +00003995 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr->getValueKind());
John McCall09431682010-11-18 19:01:18 +00003996 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
3997 Member, MemberLoc);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003998 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003999 return ExprError();
John McCall09431682010-11-18 19:01:18 +00004000
4001 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr,
4002 *Member, MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00004003 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004004
John McCall028d3972010-12-15 16:46:44 +00004005 // Adjust builtin-sel to the appropriate redefinition type if that's
4006 // not just a pointer to builtin-sel again.
4007 if (IsArrow &&
4008 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
4009 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
4010 ImpCastExprToType(BaseExpr, Context.ObjCSelRedefinitionType, CK_BitCast);
4011 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4012 ObjCImpDecl, HasTemplateArgs);
4013 }
4014
4015 // Failure cases.
4016 fail:
4017
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004018 // Recover from dot accesses to pointers, e.g.:
4019 // type *foo;
4020 // foo.bar
4021 // This is actually well-formed in two cases:
4022 // - 'type' is an Objective C type
4023 // - 'bar' is a pseudo-destructor name which happens to refer to
4024 // the appropriate pointer type
John McCall028d3972010-12-15 16:46:44 +00004025 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004026 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
4027 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
John McCall028d3972010-12-15 16:46:44 +00004028 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004029 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
4030 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall028d3972010-12-15 16:46:44 +00004031
4032 // Recurse as an -> access.
4033 IsArrow = true;
4034 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4035 ObjCImpDecl, HasTemplateArgs);
4036 }
John McCall028d3972010-12-15 16:46:44 +00004037 }
4038
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004039 // If the user is trying to apply -> or . to a function name, it's probably
4040 // because they forgot parentheses to call that function.
4041 bool TryCall = false;
4042 bool Overloaded = false;
4043 UnresolvedSet<8> AllOverloads;
4044 if (const OverloadExpr *Overloads = dyn_cast<OverloadExpr>(BaseExpr)) {
4045 AllOverloads.append(Overloads->decls_begin(), Overloads->decls_end());
4046 TryCall = true;
4047 Overloaded = true;
4048 } else if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(BaseExpr)) {
4049 if (FunctionDecl* Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
4050 AllOverloads.addDecl(Fun);
4051 TryCall = true;
4052 }
4053 }
John McCall028d3972010-12-15 16:46:44 +00004054
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004055 if (TryCall) {
4056 // Plunder the overload set for something that would make the member
4057 // expression valid.
4058 UnresolvedSet<4> ViableOverloads;
4059 bool HasViableZeroArgOverload = false;
4060 for (OverloadExpr::decls_iterator it = AllOverloads.begin(),
4061 DeclsEnd = AllOverloads.end(); it != DeclsEnd; ++it) {
Matt Beaumont-Gayfbe59942011-03-05 02:42:30 +00004062 // Our overload set may include TemplateDecls, which we'll ignore for the
4063 // purposes of determining whether we can issue a '()' fixit.
4064 if (const FunctionDecl *OverloadDecl = dyn_cast<FunctionDecl>(*it)) {
4065 QualType ResultTy = OverloadDecl->getResultType();
4066 if ((!IsArrow && ResultTy->isRecordType()) ||
4067 (IsArrow && ResultTy->isPointerType() &&
4068 ResultTy->getPointeeType()->isRecordType())) {
4069 ViableOverloads.addDecl(*it);
4070 if (OverloadDecl->getMinRequiredArguments() == 0) {
4071 HasViableZeroArgOverload = true;
4072 }
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004073 }
John McCall028d3972010-12-15 16:46:44 +00004074 }
4075 }
4076
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004077 if (!HasViableZeroArgOverload || ViableOverloads.size() != 1) {
4078 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gayfbe59942011-03-05 02:42:30 +00004079 << (AllOverloads.size() > 1) << 0
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004080 << BaseExpr->getSourceRange();
4081 int ViableOverloadCount = ViableOverloads.size();
4082 int I;
4083 for (I = 0; I < ViableOverloadCount; ++I) {
4084 // FIXME: Magic number for max shown overloads stolen from
4085 // OverloadCandidateSet::NoteCandidates.
4086 if (I >= 4 && Diags.getShowOverloads() == Diagnostic::Ovl_Best) {
4087 break;
4088 }
4089 Diag(ViableOverloads[I].getDecl()->getSourceRange().getBegin(),
4090 diag::note_member_ref_possible_intended_overload);
4091 }
4092 if (I != ViableOverloadCount) {
4093 Diag(BaseExpr->getExprLoc(), diag::note_ovl_too_many_candidates)
4094 << int(ViableOverloadCount - I);
4095 }
4096 return ExprError();
4097 }
4098 } else {
4099 // We don't have an expression that's convenient to get a Decl from, but we
4100 // can at least check if the type is "function of 0 arguments which returns
4101 // an acceptable type".
4102 const FunctionType *Fun = NULL;
4103 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4104 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
4105 TryCall = true;
4106 }
4107 } else if ((Fun = BaseType->getAs<FunctionType>())) {
4108 TryCall = true;
4109 }
John McCall028d3972010-12-15 16:46:44 +00004110
4111 if (TryCall) {
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004112 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
4113 if (FPT->getNumArgs() == 0) {
4114 QualType ResultTy = Fun->getResultType();
4115 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
4116 (IsArrow && ResultTy->isPointerType() &&
4117 ResultTy->getPointeeType()->isRecordType());
4118 }
Matt Beaumont-Gay26ae5dd2011-02-17 02:54:17 +00004119 }
John McCall028d3972010-12-15 16:46:44 +00004120 }
4121 }
4122
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004123 if (TryCall) {
4124 // At this point, we know BaseExpr looks like it's potentially callable with
4125 // 0 arguments, and that it returns something of a reasonable type, so we
4126 // can emit a fixit and carry on pretending that BaseExpr was actually a
4127 // CallExpr.
4128 SourceLocation ParenInsertionLoc =
4129 PP.getLocForEndOfToken(BaseExpr->getLocEnd());
4130 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
4131 << int(Overloaded) << 1
4132 << BaseExpr->getSourceRange()
4133 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
4134 ExprResult NewBase = ActOnCallExpr(0, BaseExpr, ParenInsertionLoc,
4135 MultiExprArg(*this, 0, 0),
4136 ParenInsertionLoc);
4137 if (NewBase.isInvalid())
4138 return ExprError();
4139 BaseExpr = NewBase.takeAs<Expr>();
4140 DefaultFunctionArrayConversion(BaseExpr);
4141 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4142 ObjCImpDecl, HasTemplateArgs);
4143 }
4144
Douglas Gregor214f31a2009-03-27 06:00:30 +00004145 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
4146 << BaseType << BaseExpr->getSourceRange();
4147
Douglas Gregor214f31a2009-03-27 06:00:30 +00004148 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00004149}
4150
John McCall129e2df2009-11-30 22:42:35 +00004151/// The main callback when the parser finds something like
4152/// expression . [nested-name-specifier] identifier
4153/// expression -> [nested-name-specifier] identifier
4154/// where 'identifier' encompasses a fairly broad spectrum of
4155/// possibilities, including destructor and operator references.
4156///
4157/// \param OpKind either tok::arrow or tok::period
4158/// \param HasTrailingLParen whether the next token is '(', which
4159/// is used to diagnose mis-uses of special members that can
4160/// only be called
4161/// \param ObjCImpDecl the current ObjC @implementation decl;
4162/// this is an ugly hack around the fact that ObjC @implementations
4163/// aren't properly put in the context chain
John McCall60d7b3a2010-08-24 06:29:42 +00004164ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall5e3c67b2010-12-15 04:42:30 +00004165 SourceLocation OpLoc,
4166 tok::TokenKind OpKind,
4167 CXXScopeSpec &SS,
4168 UnqualifiedId &Id,
4169 Decl *ObjCImpDecl,
4170 bool HasTrailingLParen) {
John McCall129e2df2009-11-30 22:42:35 +00004171 if (SS.isSet() && SS.isInvalid())
4172 return ExprError();
4173
Francois Pichetdbee3412011-01-18 05:04:39 +00004174 // Warn about the explicit constructor calls Microsoft extension.
4175 if (getLangOptions().Microsoft &&
4176 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4177 Diag(Id.getSourceRange().getBegin(),
4178 diag::ext_ms_explicit_constructor_call);
4179
John McCall129e2df2009-11-30 22:42:35 +00004180 TemplateArgumentListInfo TemplateArgsBuffer;
4181
4182 // Decompose the name into its component parts.
Abramo Bagnara25777432010-08-11 22:01:17 +00004183 DeclarationNameInfo NameInfo;
John McCall129e2df2009-11-30 22:42:35 +00004184 const TemplateArgumentListInfo *TemplateArgs;
4185 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnara25777432010-08-11 22:01:17 +00004186 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004187
Abramo Bagnara25777432010-08-11 22:01:17 +00004188 DeclarationName Name = NameInfo.getName();
John McCall129e2df2009-11-30 22:42:35 +00004189 bool IsArrow = (OpKind == tok::arrow);
4190
4191 NamedDecl *FirstQualifierInScope
4192 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4193 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4194
4195 // This is a postfix expression, so get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004196 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004197 if (Result.isInvalid()) return ExprError();
4198 Base = Result.take();
John McCall129e2df2009-11-30 22:42:35 +00004199
Douglas Gregor01e56ae2010-04-12 20:54:26 +00004200 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4201 isDependentScopeSpecifier(SS)) {
John McCall9ae2f072010-08-23 23:25:46 +00004202 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00004203 IsArrow, OpLoc,
4204 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00004205 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004206 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00004207 LookupResult R(*this, NameInfo, LookupMemberName);
John McCallad00b772010-06-16 08:42:20 +00004208 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
4209 SS, ObjCImpDecl, TemplateArgs != 0);
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004210
John McCallad00b772010-06-16 08:42:20 +00004211 if (Result.isInvalid()) {
4212 Owned(Base);
4213 return ExprError();
4214 }
John McCall129e2df2009-11-30 22:42:35 +00004215
John McCallad00b772010-06-16 08:42:20 +00004216 if (Result.get()) {
4217 // The only way a reference to a destructor can be used is to
4218 // immediately call it, which falls into this case. If the
4219 // next token is not a '(', produce a diagnostic and build the
4220 // call now.
4221 if (!HasTrailingLParen &&
4222 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCall9ae2f072010-08-23 23:25:46 +00004223 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall129e2df2009-11-30 22:42:35 +00004224
John McCallad00b772010-06-16 08:42:20 +00004225 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00004226 }
4227
John McCall9ae2f072010-08-23 23:25:46 +00004228 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCallc2233c52010-01-15 08:34:02 +00004229 OpLoc, IsArrow, SS, FirstQualifierInScope,
4230 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004231 }
4232
4233 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00004234}
4235
John McCall60d7b3a2010-08-24 06:29:42 +00004236ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00004237 FunctionDecl *FD,
4238 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00004239 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004240 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00004241 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00004242 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00004243 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00004244 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004245 return ExprError();
4246 }
4247
4248 if (Param->hasUninstantiatedDefaultArg()) {
4249 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00004250
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004251 // Instantiate the expression.
4252 MultiLevelTemplateArgumentList ArgList
4253 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00004254
Nico Weber08e41a62010-11-29 18:19:25 +00004255 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004256 = ArgList.getInnermost();
4257 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4258 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004259
Nico Weber08e41a62010-11-29 18:19:25 +00004260 ExprResult Result;
4261 {
4262 // C++ [dcl.fct.default]p5:
4263 // The names in the [default argument] expression are bound, and
4264 // the semantic constraints are checked, at the point where the
4265 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00004266 ContextRAII SavedContext(*this, FD);
Nico Weber08e41a62010-11-29 18:19:25 +00004267 Result = SubstExpr(UninstExpr, ArgList);
4268 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004269 if (Result.isInvalid())
4270 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004271
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004272 // Check the expression as an initializer for the parameter.
4273 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004274 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004275 InitializationKind Kind
4276 = InitializationKind::CreateCopy(Param->getLocation(),
4277 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4278 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00004279
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004280 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4281 Result = InitSeq.Perform(*this, Entity, Kind,
4282 MultiExprArg(*this, &ResultE, 1));
4283 if (Result.isInvalid())
4284 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004285
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004286 // Build the default argument expression.
4287 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4288 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004289 }
4290
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004291 // If the default expression creates temporaries, we need to
4292 // push them to the current stack of expression temporaries so they'll
4293 // be properly destroyed.
4294 // FIXME: We should really be rebuilding the default argument with new
4295 // bound temporaries; see the comment in PR5810.
Douglas Gregor5833b0b2010-09-14 22:55:20 +00004296 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4297 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4298 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4299 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4300 ExprTemporaries.push_back(Temporary);
4301 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004302
4303 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00004304 // Just mark all of the declarations in this potentially-evaluated expression
4305 // as being "referenced".
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004306 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor036aed12009-12-23 23:03:06 +00004307 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004308}
4309
Douglas Gregor88a35142008-12-22 05:46:06 +00004310/// ConvertArgumentsForCall - Converts the arguments specified in
4311/// Args/NumArgs to the parameter types of the function FDecl with
4312/// function prototype Proto. Call is the call expression itself, and
4313/// Fn is the function expression. For a C++ member function, this
4314/// routine does not attempt to convert the object argument. Returns
4315/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004316bool
4317Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00004318 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00004319 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00004320 Expr **Args, unsigned NumArgs,
4321 SourceLocation RParenLoc) {
John McCall8e10f3b2011-02-26 05:39:39 +00004322 // Bail out early if calling a builtin with custom typechecking.
4323 // We don't need to do this in the
4324 if (FDecl)
4325 if (unsigned ID = FDecl->getBuiltinID())
4326 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4327 return false;
4328
Mike Stumpeed9cac2009-02-19 03:04:26 +00004329 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00004330 // assignment, to the types of the corresponding parameter, ...
4331 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004332 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004333
Douglas Gregor88a35142008-12-22 05:46:06 +00004334 // If too few arguments are available (and we don't have default
4335 // arguments for the remaining parameters), don't make the call.
4336 if (NumArgs < NumArgsInProto) {
4337 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4338 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004339 << Fn->getType()->isBlockPointerType()
Eric Christopherd77b9a22010-04-16 04:48:22 +00004340 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00004341 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00004342 }
4343
4344 // If too many are passed and not variadic, error on the extras and drop
4345 // them.
4346 if (NumArgs > NumArgsInProto) {
4347 if (!Proto->isVariadic()) {
4348 Diag(Args[NumArgsInProto]->getLocStart(),
4349 diag::err_typecheck_call_too_many_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004350 << Fn->getType()->isBlockPointerType()
Eric Christopherccfa9632010-04-16 04:56:46 +00004351 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00004352 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4353 Args[NumArgs-1]->getLocEnd());
4354 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004355 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004356 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004357 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004358 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004359 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004360 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004361 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4362 if (Fn->getType()->isBlockPointerType())
4363 CallType = VariadicBlock; // Block
4364 else if (isa<MemberExpr>(Fn))
4365 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004366 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004367 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004368 if (Invalid)
4369 return true;
4370 unsigned TotalNumArgs = AllArgs.size();
4371 for (unsigned i = 0; i < TotalNumArgs; ++i)
4372 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004373
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004374 return false;
4375}
Mike Stumpeed9cac2009-02-19 03:04:26 +00004376
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004377bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4378 FunctionDecl *FDecl,
4379 const FunctionProtoType *Proto,
4380 unsigned FirstProtoArg,
4381 Expr **Args, unsigned NumArgs,
4382 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004383 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004384 unsigned NumArgsInProto = Proto->getNumArgs();
4385 unsigned NumArgsToCheck = NumArgs;
4386 bool Invalid = false;
4387 if (NumArgs != NumArgsInProto)
4388 // Use default arguments for missing arguments
4389 NumArgsToCheck = NumArgsInProto;
4390 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00004391 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004392 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004393 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004394
Douglas Gregor88a35142008-12-22 05:46:06 +00004395 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004396 if (ArgIx < NumArgs) {
4397 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004398
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004399 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4400 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00004401 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004402 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004403 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004404
Douglas Gregora188ff22009-12-22 16:09:06 +00004405 // Pass the argument
4406 ParmVarDecl *Param = 0;
4407 if (FDecl && i < FDecl->getNumParams())
4408 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00004409
Douglas Gregora188ff22009-12-22 16:09:06 +00004410 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004411 Param? InitializedEntity::InitializeParameter(Context, Param)
4412 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCall60d7b3a2010-08-24 06:29:42 +00004413 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00004414 SourceLocation(),
4415 Owned(Arg));
Douglas Gregora188ff22009-12-22 16:09:06 +00004416 if (ArgE.isInvalid())
4417 return true;
4418
4419 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004420 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00004421 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004422
John McCall60d7b3a2010-08-24 06:29:42 +00004423 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004424 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004425 if (ArgExpr.isInvalid())
4426 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004427
Anders Carlsson56c5e332009-08-25 03:49:14 +00004428 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004429 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004430 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00004431 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004432
Douglas Gregor88a35142008-12-22 05:46:06 +00004433 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004434 if (CallType != VariadicDoesNotApply) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004435 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner40378332010-05-16 04:01:30 +00004436 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004437 Expr *Arg = Args[i];
Chris Lattner40378332010-05-16 04:01:30 +00004438 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004439 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00004440 }
4441 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004442 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00004443}
4444
Steve Narofff69936d2007-09-16 03:34:24 +00004445/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00004446/// This provides the location of the left/right parens and a list of comma
4447/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00004448ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004449Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004450 MultiExprArg args, SourceLocation RParenLoc,
4451 Expr *ExecConfig) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00004452 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00004453
4454 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004455 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00004456 if (Result.isInvalid()) return ExprError();
4457 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00004458
John McCall9ae2f072010-08-23 23:25:46 +00004459 Expr **Args = args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004460
Douglas Gregor88a35142008-12-22 05:46:06 +00004461 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00004462 // If this is a pseudo-destructor expression, build the call immediately.
4463 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4464 if (NumArgs > 0) {
4465 // Pseudo-destructor calls should not have any arguments.
4466 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00004467 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00004468 SourceRange(Args[0]->getLocStart(),
4469 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00004470
Douglas Gregora71d8192009-09-04 17:36:40 +00004471 NumArgs = 0;
4472 }
Mike Stump1eb44332009-09-09 15:08:12 +00004473
Douglas Gregora71d8192009-09-04 17:36:40 +00004474 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00004475 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00004476 }
Mike Stump1eb44332009-09-09 15:08:12 +00004477
Douglas Gregor17330012009-02-04 15:01:18 +00004478 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00004479 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00004480 // FIXME: Will need to cache the results of name lookup (including ADL) in
4481 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00004482 bool Dependent = false;
4483 if (Fn->isTypeDependent())
4484 Dependent = true;
4485 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4486 Dependent = true;
4487
Peter Collingbournee08ce652011-02-09 21:07:24 +00004488 if (Dependent) {
4489 if (ExecConfig) {
4490 return Owned(new (Context) CUDAKernelCallExpr(
4491 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4492 Context.DependentTy, VK_RValue, RParenLoc));
4493 } else {
4494 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4495 Context.DependentTy, VK_RValue,
4496 RParenLoc));
4497 }
4498 }
Douglas Gregor17330012009-02-04 15:01:18 +00004499
4500 // Determine whether this is a call to an object (C++ [over.call.object]).
4501 if (Fn->getType()->isRecordType())
4502 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004503 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00004504
John McCall129e2df2009-11-30 22:42:35 +00004505 Expr *NakedFn = Fn->IgnoreParens();
4506
4507 // Determine whether this is a call to an unresolved member function.
4508 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4509 // If lookup was unresolved but not dependent (i.e. didn't find
4510 // an unresolved using declaration), it has to be an overloaded
4511 // function set, which means it must contain either multiple
4512 // declarations (all methods or method templates) or a single
4513 // method template.
4514 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor2b147f02010-04-25 21:15:30 +00004515 isa<FunctionTemplateDecl>(
4516 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor958aeb02009-12-01 03:34:29 +00004517 (void)MemE;
John McCall129e2df2009-11-30 22:42:35 +00004518
John McCallaa81e162009-12-01 22:10:20 +00004519 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004520 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00004521 }
4522
Douglas Gregorfa047642009-02-04 00:32:51 +00004523 // Determine whether this is a call to a member function.
John McCall129e2df2009-11-30 22:42:35 +00004524 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00004525 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall129e2df2009-11-30 22:42:35 +00004526 if (isa<CXXMethodDecl>(MemDecl))
John McCallaa81e162009-12-01 22:10:20 +00004527 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004528 RParenLoc);
Douglas Gregore53060f2009-06-25 22:08:12 +00004529 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004530
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004531 // Determine whether this is a call to a pointer-to-member function.
John McCall129e2df2009-11-30 22:42:35 +00004532 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
John McCall2de56d12010-08-25 11:45:40 +00004533 if (BO->getOpcode() == BO_PtrMemD ||
4534 BO->getOpcode() == BO_PtrMemI) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00004535 if (const FunctionProtoType *FPT
4536 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004537 QualType ResultTy = FPT->getCallResultType(Context);
John McCallf89e55a2010-11-18 06:31:45 +00004538 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004539
Douglas Gregorfdc13a02011-02-04 12:57:49 +00004540 // Check that the object type isn't more qualified than the
4541 // member function we're calling.
4542 Qualifiers FuncQuals = Qualifiers::fromCVRMask(FPT->getTypeQuals());
4543 Qualifiers ObjectQuals
4544 = BO->getOpcode() == BO_PtrMemD
4545 ? BO->getLHS()->getType().getQualifiers()
4546 : BO->getLHS()->getType()->getAs<PointerType>()
4547 ->getPointeeType().getQualifiers();
4548
4549 Qualifiers Difference = ObjectQuals - FuncQuals;
4550 Difference.removeObjCGCAttr();
4551 Difference.removeAddressSpace();
4552 if (Difference) {
4553 std::string QualsString = Difference.getAsString();
4554 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
4555 << BO->getType().getUnqualifiedType()
4556 << QualsString
4557 << (QualsString.find(' ') == std::string::npos? 1 : 2);
4558 }
4559
John McCall9ae2f072010-08-23 23:25:46 +00004560 CXXMemberCallExpr *TheCall
Abramo Bagnara6c572f12010-12-03 21:39:42 +00004561 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
John McCallf89e55a2010-11-18 06:31:45 +00004562 NumArgs, ResultTy, VK,
John McCall9ae2f072010-08-23 23:25:46 +00004563 RParenLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004564
4565 if (CheckCallReturnType(FPT->getResultType(),
4566 BO->getRHS()->getSourceRange().getBegin(),
John McCall9ae2f072010-08-23 23:25:46 +00004567 TheCall, 0))
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004568 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00004569
John McCall9ae2f072010-08-23 23:25:46 +00004570 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004571 RParenLoc))
4572 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004573
John McCall9ae2f072010-08-23 23:25:46 +00004574 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004575 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004576 return ExprError(Diag(Fn->getLocStart(),
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004577 diag::err_typecheck_call_not_function)
4578 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004579 }
4580 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004581 }
4582
Douglas Gregorfa047642009-02-04 00:32:51 +00004583 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00004584 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004585 // lookup and whether there were any explicitly-specified template arguments.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004586
Eli Friedmanefa42f72009-12-26 03:35:45 +00004587 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00004588 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4589 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4590 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004591 RParenLoc, ExecConfig);
Douglas Gregoref9b1492010-11-09 20:03:54 +00004592 }
4593
John McCall3b4294e2009-12-16 12:17:52 +00004594 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00004595 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4596 if (UnOp->getOpcode() == UO_AddrOf)
4597 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4598
John McCall3b4294e2009-12-16 12:17:52 +00004599 if (isa<DeclRefExpr>(NakedFn))
4600 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4601
Peter Collingbournee08ce652011-02-09 21:07:24 +00004602 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
4603 ExecConfig);
4604}
4605
4606ExprResult
4607Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4608 MultiExprArg execConfig, SourceLocation GGGLoc) {
4609 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4610 if (!ConfigDecl)
4611 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4612 << "cudaConfigureCall");
4613 QualType ConfigQTy = ConfigDecl->getType();
4614
4615 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4616 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
4617
4618 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCallaa81e162009-12-01 22:10:20 +00004619}
4620
John McCall3b4294e2009-12-16 12:17:52 +00004621/// BuildResolvedCallExpr - Build a call to a resolved expression,
4622/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00004623/// unary-convert to an expression of function-pointer or
4624/// block-pointer type.
4625///
4626/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00004627ExprResult
John McCallaa81e162009-12-01 22:10:20 +00004628Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4629 SourceLocation LParenLoc,
4630 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004631 SourceLocation RParenLoc,
4632 Expr *Config) {
John McCallaa81e162009-12-01 22:10:20 +00004633 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4634
Chris Lattner04421082008-04-08 04:40:51 +00004635 // Promote the function operand.
4636 UsualUnaryConversions(Fn);
4637
Chris Lattner925e60d2007-12-28 05:29:59 +00004638 // Make the call expr early, before semantic checks. This guarantees cleanup
4639 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00004640 CallExpr *TheCall;
4641 if (Config) {
4642 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4643 cast<CallExpr>(Config),
4644 Args, NumArgs,
4645 Context.BoolTy,
4646 VK_RValue,
4647 RParenLoc);
4648 } else {
4649 TheCall = new (Context) CallExpr(Context, Fn,
4650 Args, NumArgs,
4651 Context.BoolTy,
4652 VK_RValue,
4653 RParenLoc);
4654 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004655
John McCall8e10f3b2011-02-26 05:39:39 +00004656 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4657
4658 // Bail out early if calling a builtin with custom typechecking.
4659 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4660 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4661
Steve Naroffdd972f22008-09-05 22:11:13 +00004662 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00004663 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00004664 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4665 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00004666 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00004667 if (FuncT == 0)
4668 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4669 << Fn->getType() << Fn->getSourceRange());
4670 } else if (const BlockPointerType *BPT =
4671 Fn->getType()->getAs<BlockPointerType>()) {
4672 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4673 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00004674 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4675 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00004676 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004677
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004678 if (getLangOptions().CUDA) {
4679 if (Config) {
4680 // CUDA: Kernel calls must be to global functions
4681 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4682 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4683 << FDecl->getName() << Fn->getSourceRange());
4684
4685 // CUDA: Kernel function must have 'void' return type
4686 if (!FuncT->getResultType()->isVoidType())
4687 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4688 << Fn->getType() << Fn->getSourceRange());
4689 }
4690 }
4691
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004692 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004693 if (CheckCallReturnType(FuncT->getResultType(),
John McCall9ae2f072010-08-23 23:25:46 +00004694 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004695 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004696 return ExprError();
4697
Chris Lattner925e60d2007-12-28 05:29:59 +00004698 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004699 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00004700 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00004701
Douglas Gregor72564e72009-02-26 23:50:07 +00004702 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00004703 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00004704 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00004705 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00004706 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004707 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00004708
Douglas Gregor74734d52009-04-02 15:37:10 +00004709 if (FDecl) {
4710 // Check if we have too few/too many template arguments, based
4711 // on our knowledge of the function definition.
4712 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00004713 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004714 const FunctionProtoType *Proto
4715 = Def->getType()->getAs<FunctionProtoType>();
4716 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004717 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4718 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004719 }
Douglas Gregor46542412010-10-25 20:39:23 +00004720
4721 // If the function we're calling isn't a function prototype, but we have
4722 // a function prototype from a prior declaratiom, use that prototype.
4723 if (!FDecl->hasPrototype())
4724 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00004725 }
4726
Steve Naroffb291ab62007-08-28 23:30:39 +00004727 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00004728 for (unsigned i = 0; i != NumArgs; i++) {
4729 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00004730
4731 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004732 InitializedEntity Entity
4733 = InitializedEntity::InitializeParameter(Context,
4734 Proto->getArgType(i));
4735 ExprResult ArgE = PerformCopyInitialization(Entity,
4736 SourceLocation(),
4737 Owned(Arg));
4738 if (ArgE.isInvalid())
4739 return true;
4740
4741 Arg = ArgE.takeAs<Expr>();
4742
4743 } else {
4744 DefaultArgumentPromotion(Arg);
Douglas Gregor46542412010-10-25 20:39:23 +00004745 }
4746
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004747 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4748 Arg->getType(),
4749 PDiag(diag::err_call_incomplete_argument)
4750 << Arg->getSourceRange()))
4751 return ExprError();
4752
Chris Lattner925e60d2007-12-28 05:29:59 +00004753 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00004754 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004755 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004756
Douglas Gregor88a35142008-12-22 05:46:06 +00004757 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4758 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004759 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4760 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00004761
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00004762 // Check for sentinels
4763 if (NDecl)
4764 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00004765
Chris Lattner59907c42007-08-10 20:18:51 +00004766 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00004767 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00004768 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00004769 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004770
John McCall8e10f3b2011-02-26 05:39:39 +00004771 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00004772 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00004773 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00004774 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00004775 return ExprError();
4776 }
Chris Lattner59907c42007-08-10 20:18:51 +00004777
John McCall9ae2f072010-08-23 23:25:46 +00004778 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00004779}
4780
John McCall60d7b3a2010-08-24 06:29:42 +00004781ExprResult
John McCallb3d87482010-08-24 05:47:05 +00004782Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004783 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00004784 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00004785 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00004786 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00004787
4788 TypeSourceInfo *TInfo;
4789 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4790 if (!TInfo)
4791 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4792
John McCall9ae2f072010-08-23 23:25:46 +00004793 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00004794}
4795
John McCall60d7b3a2010-08-24 06:29:42 +00004796ExprResult
John McCall42f56b52010-01-18 19:35:47 +00004797Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCall9ae2f072010-08-23 23:25:46 +00004798 SourceLocation RParenLoc, Expr *literalExpr) {
John McCall42f56b52010-01-18 19:35:47 +00004799 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00004800
Eli Friedman6223c222008-05-20 05:22:08 +00004801 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004802 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4803 PDiag(diag::err_illegal_decl_array_incomplete_type)
4804 << SourceRange(LParenLoc,
4805 literalExpr->getSourceRange().getEnd())))
4806 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004807 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004808 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4809 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004810 } else if (!literalType->isDependentType() &&
4811 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00004812 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00004813 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00004814 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004815 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00004816
Douglas Gregor99a2e602009-12-16 01:38:02 +00004817 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00004818 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004819 InitializationKind Kind
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004820 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor99a2e602009-12-16 01:38:02 +00004821 /*IsCStyleCast=*/true);
Eli Friedman08544622009-12-22 02:35:53 +00004822 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00004823 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00004824 MultiExprArg(*this, &literalExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00004825 &literalType);
4826 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004827 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00004828 literalExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00004829
Chris Lattner371f2582008-12-04 23:50:19 +00004830 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00004831 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00004832 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004833 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00004834 }
Eli Friedman08544622009-12-22 02:35:53 +00004835
John McCallf89e55a2010-11-18 06:31:45 +00004836 // In C, compound literals are l-values for some reason.
4837 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
4838
John McCall1d7d8d62010-01-19 22:33:45 +00004839 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCallf89e55a2010-11-18 06:31:45 +00004840 VK, literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00004841}
4842
John McCall60d7b3a2010-08-24 06:29:42 +00004843ExprResult
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004844Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004845 SourceLocation RBraceLoc) {
4846 unsigned NumInit = initlist.size();
John McCall9ae2f072010-08-23 23:25:46 +00004847 Expr **InitList = initlist.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00004848
Steve Naroff08d92e42007-09-15 18:49:24 +00004849 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00004850 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004851
Ted Kremenek709210f2010-04-13 23:39:13 +00004852 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4853 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00004854 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004855 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00004856}
4857
John McCallf3ea8cf2010-11-14 08:17:51 +00004858/// Prepares for a scalar cast, performing all the necessary stages
4859/// except the final cast and returning the kind required.
4860static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
4861 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4862 // Also, callers should have filtered out the invalid cases with
4863 // pointers. Everything else should be possible.
4864
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004865 QualType SrcTy = Src->getType();
John McCallf3ea8cf2010-11-14 08:17:51 +00004866 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00004867 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00004868
John McCalldaa8e4e2010-11-15 09:13:47 +00004869 switch (SrcTy->getScalarTypeKind()) {
4870 case Type::STK_MemberPointer:
4871 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004872
John McCalldaa8e4e2010-11-15 09:13:47 +00004873 case Type::STK_Pointer:
4874 switch (DestTy->getScalarTypeKind()) {
4875 case Type::STK_Pointer:
4876 return DestTy->isObjCObjectPointerType() ?
John McCallf3ea8cf2010-11-14 08:17:51 +00004877 CK_AnyPointerToObjCPointerCast :
4878 CK_BitCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004879 case Type::STK_Bool:
4880 return CK_PointerToBoolean;
4881 case Type::STK_Integral:
4882 return CK_PointerToIntegral;
4883 case Type::STK_Floating:
4884 case Type::STK_FloatingComplex:
4885 case Type::STK_IntegralComplex:
4886 case Type::STK_MemberPointer:
4887 llvm_unreachable("illegal cast from pointer");
4888 }
4889 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004890
John McCalldaa8e4e2010-11-15 09:13:47 +00004891 case Type::STK_Bool: // casting from bool is like casting from an integer
4892 case Type::STK_Integral:
4893 switch (DestTy->getScalarTypeKind()) {
4894 case Type::STK_Pointer:
John McCallf3ea8cf2010-11-14 08:17:51 +00004895 if (Src->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00004896 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00004897 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00004898 case Type::STK_Bool:
4899 return CK_IntegralToBoolean;
4900 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00004901 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004902 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004903 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004904 case Type::STK_IntegralComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004905 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCall8786da72010-12-14 17:51:41 +00004906 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004907 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004908 case Type::STK_FloatingComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004909 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004910 CK_IntegralToFloating);
4911 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004912 case Type::STK_MemberPointer:
4913 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004914 }
4915 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004916
John McCalldaa8e4e2010-11-15 09:13:47 +00004917 case Type::STK_Floating:
4918 switch (DestTy->getScalarTypeKind()) {
4919 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004920 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004921 case Type::STK_Bool:
4922 return CK_FloatingToBoolean;
4923 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00004924 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004925 case Type::STK_FloatingComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004926 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCall8786da72010-12-14 17:51:41 +00004927 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004928 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004929 case Type::STK_IntegralComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004930 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004931 CK_FloatingToIntegral);
4932 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004933 case Type::STK_Pointer:
4934 llvm_unreachable("valid float->pointer cast?");
4935 case Type::STK_MemberPointer:
4936 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004937 }
4938 break;
4939
John McCalldaa8e4e2010-11-15 09:13:47 +00004940 case Type::STK_FloatingComplex:
4941 switch (DestTy->getScalarTypeKind()) {
4942 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004943 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004944 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004945 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00004946 case Type::STK_Floating: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004947 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00004948 if (S.Context.hasSameType(ET, DestTy))
4949 return CK_FloatingComplexToReal;
4950 S.ImpCastExprToType(Src, ET, CK_FloatingComplexToReal);
4951 return CK_FloatingCast;
4952 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004953 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004954 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004955 case Type::STK_Integral:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004956 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004957 CK_FloatingComplexToReal);
4958 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004959 case Type::STK_Pointer:
4960 llvm_unreachable("valid complex float->pointer cast?");
4961 case Type::STK_MemberPointer:
4962 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004963 }
4964 break;
4965
John McCalldaa8e4e2010-11-15 09:13:47 +00004966 case Type::STK_IntegralComplex:
4967 switch (DestTy->getScalarTypeKind()) {
4968 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004969 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004970 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004971 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00004972 case Type::STK_Integral: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004973 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00004974 if (S.Context.hasSameType(ET, DestTy))
4975 return CK_IntegralComplexToReal;
4976 S.ImpCastExprToType(Src, ET, CK_IntegralComplexToReal);
4977 return CK_IntegralCast;
4978 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004979 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004980 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004981 case Type::STK_Floating:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004982 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004983 CK_IntegralComplexToReal);
4984 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004985 case Type::STK_Pointer:
4986 llvm_unreachable("valid complex int->pointer cast?");
4987 case Type::STK_MemberPointer:
4988 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004989 }
4990 break;
Anders Carlsson82debc72009-10-18 18:12:03 +00004991 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004992
John McCallf3ea8cf2010-11-14 08:17:51 +00004993 llvm_unreachable("Unhandled scalar cast");
4994 return CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00004995}
4996
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004997/// CheckCastTypes - Check type constraints for casting between types.
John McCallf89e55a2010-11-18 06:31:45 +00004998bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
4999 Expr *&castExpr, CastKind& Kind, ExprValueKind &VK,
5000 CXXCastPath &BasePath, bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00005001 if (getLangOptions().CPlusPlus)
Douglas Gregor40749ee2010-11-03 00:35:38 +00005002 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
5003 castExpr->getLocEnd()),
John McCallf89e55a2010-11-18 06:31:45 +00005004 castType, VK, castExpr, Kind, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005005 FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00005006
John McCallf89e55a2010-11-18 06:31:45 +00005007 // We only support r-value casts in C.
5008 VK = VK_RValue;
5009
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005010 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
5011 // type needs to be scalar.
5012 if (castType->isVoidType()) {
John McCallf6a16482010-12-04 03:47:34 +00005013 // We don't necessarily do lvalue-to-rvalue conversions on this.
5014 IgnoredValueConversions(castExpr);
5015
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005016 // Cast to void allows any expr type.
John McCall2de56d12010-08-25 11:45:40 +00005017 Kind = CK_ToVoid;
Anders Carlssonebeaf202009-10-16 02:35:04 +00005018 return false;
5019 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005020
John McCallf6a16482010-12-04 03:47:34 +00005021 DefaultFunctionArrayLvalueConversion(castExpr);
5022
Eli Friedman8d438082010-07-17 20:43:49 +00005023 if (RequireCompleteType(TyR.getBegin(), castType,
5024 diag::err_typecheck_cast_to_incomplete))
5025 return true;
5026
Anders Carlssonebeaf202009-10-16 02:35:04 +00005027 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00005028 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005029 (castType->isStructureType() || castType->isUnionType())) {
5030 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005031 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005032 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
5033 << castType << castExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005034 Kind = CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00005035 return false;
5036 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005037
Anders Carlssonc3516322009-10-16 02:48:28 +00005038 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005039 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00005040 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005041 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005042 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005043 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005044 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara8c4bfe52010-10-07 21:20:44 +00005045 castExpr->getType()) &&
5046 !Field->isUnnamedBitfield()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005047 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
5048 << castExpr->getSourceRange();
5049 break;
5050 }
5051 }
5052 if (Field == FieldEnd)
5053 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
5054 << castExpr->getType() << castExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005055 Kind = CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00005056 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005057 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005058
Anders Carlssonc3516322009-10-16 02:48:28 +00005059 // Reject any other conversions to non-scalar types.
5060 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
5061 << castType << castExpr->getSourceRange();
5062 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005063
John McCallf3ea8cf2010-11-14 08:17:51 +00005064 // The type we're casting to is known to be a scalar or vector.
5065
5066 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005067 if (!castExpr->getType()->isScalarType() &&
Anders Carlssonc3516322009-10-16 02:48:28 +00005068 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005069 return Diag(castExpr->getLocStart(),
5070 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00005071 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00005072 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005073
5074 if (castType->isExtVectorType())
Anders Carlsson16a89042009-10-16 05:23:41 +00005075 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005076
Anders Carlssonc3516322009-10-16 02:48:28 +00005077 if (castType->isVectorType())
5078 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
5079 if (castExpr->getType()->isVectorType())
5080 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
5081
John McCallf3ea8cf2010-11-14 08:17:51 +00005082 // The source and target types are both scalars, i.e.
5083 // - arithmetic types (fundamental, enum, and complex)
5084 // - all kinds of pointers
5085 // Note that member pointers were filtered out with C++, above.
5086
Anders Carlsson16a89042009-10-16 05:23:41 +00005087 if (isa<ObjCSelectorExpr>(castExpr))
5088 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005089
John McCallf3ea8cf2010-11-14 08:17:51 +00005090 // If either type is a pointer, the other type has to be either an
5091 // integer or a pointer.
Anders Carlssonc3516322009-10-16 02:48:28 +00005092 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00005093 QualType castExprType = castExpr->getType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00005094 if (!castExprType->isIntegralType(Context) &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00005095 castExprType->isArithmeticType())
Eli Friedman41826bb2009-05-01 02:23:58 +00005096 return Diag(castExpr->getLocStart(),
5097 diag::err_cast_pointer_from_non_pointer_int)
5098 << castExprType << castExpr->getSourceRange();
5099 } else if (!castExpr->getType()->isArithmeticType()) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00005100 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
Eli Friedman41826bb2009-05-01 02:23:58 +00005101 return Diag(castExpr->getLocStart(),
5102 diag::err_cast_pointer_to_non_pointer_int)
5103 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005104 }
Anders Carlsson82debc72009-10-18 18:12:03 +00005105
John McCallf3ea8cf2010-11-14 08:17:51 +00005106 Kind = PrepareScalarCast(*this, castExpr, castType);
John McCallb7f4ffe2010-08-12 21:44:57 +00005107
John McCallf3ea8cf2010-11-14 08:17:51 +00005108 if (Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +00005109 CheckCastAlign(castExpr, castType, TyR);
5110
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005111 return false;
5112}
5113
Anders Carlssonc3516322009-10-16 02:48:28 +00005114bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00005115 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00005116 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005117
Anders Carlssona64db8f2007-11-27 05:51:55 +00005118 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00005119 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00005120 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00005121 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00005122 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005123 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00005124 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00005125 } else
5126 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005127 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00005128 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005129
John McCall2de56d12010-08-25 11:45:40 +00005130 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00005131 return false;
5132}
5133
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005134bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
John McCall2de56d12010-08-25 11:45:40 +00005135 CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00005136 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005137
Anders Carlsson16a89042009-10-16 05:23:41 +00005138 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005139
Nate Begeman9b10da62009-06-27 22:05:55 +00005140 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5141 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00005142 if (SrcTy->isVectorType()) {
5143 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
5144 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5145 << DestTy << SrcTy << R;
John McCall2de56d12010-08-25 11:45:40 +00005146 Kind = CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00005147 return false;
5148 }
5149
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005150 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00005151 // conversion will take place first from scalar to elt type, and then
5152 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005153 if (SrcTy->isPointerType())
5154 return Diag(R.getBegin(),
5155 diag::err_invalid_conversion_between_vector_and_scalar)
5156 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00005157
5158 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5159 ImpCastExprToType(CastExpr, DestElemTy,
John McCallf3ea8cf2010-11-14 08:17:51 +00005160 PrepareScalarCast(*this, CastExpr, DestElemTy));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005161
John McCall2de56d12010-08-25 11:45:40 +00005162 Kind = CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00005163 return false;
5164}
5165
John McCall60d7b3a2010-08-24 06:29:42 +00005166ExprResult
John McCallb3d87482010-08-24 05:47:05 +00005167Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005168 SourceLocation RParenLoc, Expr *castExpr) {
5169 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005170 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00005171
John McCall9d125032010-01-15 18:39:57 +00005172 TypeSourceInfo *castTInfo;
5173 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5174 if (!castTInfo)
John McCall42f56b52010-01-18 19:35:47 +00005175 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump1eb44332009-09-09 15:08:12 +00005176
Nate Begeman2ef13e52009-08-10 23:49:36 +00005177 // If the Expr being casted is a ParenListExpr, handle it specially.
5178 if (isa<ParenListExpr>(castExpr))
John McCall9ae2f072010-08-23 23:25:46 +00005179 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCall42f56b52010-01-18 19:35:47 +00005180 castTInfo);
John McCallb042fdf2010-01-15 18:56:44 +00005181
John McCall9ae2f072010-08-23 23:25:46 +00005182 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallb042fdf2010-01-15 18:56:44 +00005183}
5184
John McCall60d7b3a2010-08-24 06:29:42 +00005185ExprResult
John McCallb042fdf2010-01-15 18:56:44 +00005186Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005187 SourceLocation RParenLoc, Expr *castExpr) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005188 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +00005189 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +00005190 CXXCastPath BasePath;
John McCallb042fdf2010-01-15 18:56:44 +00005191 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
John McCallf89e55a2010-11-18 06:31:45 +00005192 Kind, VK, BasePath))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005193 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00005194
John McCallf871d0c2010-08-07 06:22:56 +00005195 return Owned(CStyleCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +00005196 Ty->getType().getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +00005197 VK, Kind, castExpr, &BasePath, Ty,
John McCallf871d0c2010-08-07 06:22:56 +00005198 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00005199}
5200
Nate Begeman2ef13e52009-08-10 23:49:36 +00005201/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5202/// of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00005203ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005204Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005205 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5206 if (!E)
5207 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00005208
John McCall60d7b3a2010-08-24 06:29:42 +00005209 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00005210
Nate Begeman2ef13e52009-08-10 23:49:36 +00005211 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00005212 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5213 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00005214
John McCall9ae2f072010-08-23 23:25:46 +00005215 if (Result.isInvalid()) return ExprError();
5216
5217 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00005218}
5219
John McCall60d7b3a2010-08-24 06:29:42 +00005220ExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00005221Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00005222 SourceLocation RParenLoc, Expr *Op,
John McCall42f56b52010-01-18 19:35:47 +00005223 TypeSourceInfo *TInfo) {
John McCall9ae2f072010-08-23 23:25:46 +00005224 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCall42f56b52010-01-18 19:35:47 +00005225 QualType Ty = TInfo->getType();
John Thompson8bb59a82010-06-30 22:55:51 +00005226 bool isAltiVecLiteral = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005227
John Thompson8bb59a82010-06-30 22:55:51 +00005228 // Check for an altivec literal,
5229 // i.e. all the elements are integer constants.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005230 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5231 if (PE->getNumExprs() == 0) {
5232 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5233 return ExprError();
5234 }
John Thompson8bb59a82010-06-30 22:55:51 +00005235 if (PE->getNumExprs() == 1) {
5236 if (!PE->getExpr(0)->getType()->isVectorType())
5237 isAltiVecLiteral = true;
5238 }
5239 else
5240 isAltiVecLiteral = true;
5241 }
Nate Begeman2ef13e52009-08-10 23:49:36 +00005242
John Thompson8bb59a82010-06-30 22:55:51 +00005243 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
5244 // then handle it as such.
5245 if (isAltiVecLiteral) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005246 llvm::SmallVector<Expr *, 8> initExprs;
5247 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5248 initExprs.push_back(PE->getExpr(i));
5249
5250 // FIXME: This means that pretty-printing the final AST will produce curly
5251 // braces instead of the original commas.
Ted Kremenek709210f2010-04-13 23:39:13 +00005252 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5253 &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00005254 initExprs.size(), RParenLoc);
5255 E->setType(Ty);
John McCall9ae2f072010-08-23 23:25:46 +00005256 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman2ef13e52009-08-10 23:49:36 +00005257 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00005258 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00005259 // sequence of BinOp comma operators.
John McCall60d7b3a2010-08-24 06:29:42 +00005260 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCall9ae2f072010-08-23 23:25:46 +00005261 if (Result.isInvalid()) return ExprError();
5262 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman2ef13e52009-08-10 23:49:36 +00005263 }
5264}
5265
John McCall60d7b3a2010-08-24 06:29:42 +00005266ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00005267 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00005268 MultiExprArg Val,
John McCallb3d87482010-08-24 05:47:05 +00005269 ParsedType TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005270 unsigned nexprs = Val.size();
5271 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00005272 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5273 Expr *expr;
5274 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5275 expr = new (Context) ParenExpr(L, R, exprs[0]);
5276 else
5277 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00005278 return Owned(expr);
5279}
5280
Chandler Carruth82214a82011-02-18 23:54:50 +00005281/// \brief Emit a specialized diagnostic when one expression is a null pointer
5282/// constant and the other is not a pointer.
5283bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5284 SourceLocation QuestionLoc) {
5285 Expr *NullExpr = LHS;
5286 Expr *NonPointerExpr = RHS;
5287 Expr::NullPointerConstantKind NullKind =
5288 NullExpr->isNullPointerConstant(Context,
5289 Expr::NPC_ValueDependentIsNotNull);
5290
5291 if (NullKind == Expr::NPCK_NotNull) {
5292 NullExpr = RHS;
5293 NonPointerExpr = LHS;
5294 NullKind =
5295 NullExpr->isNullPointerConstant(Context,
5296 Expr::NPC_ValueDependentIsNotNull);
5297 }
5298
5299 if (NullKind == Expr::NPCK_NotNull)
5300 return false;
5301
5302 if (NullKind == Expr::NPCK_ZeroInteger) {
5303 // In this case, check to make sure that we got here from a "NULL"
5304 // string in the source code.
5305 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00005306 SourceLocation loc = NullExpr->getExprLoc();
5307 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00005308 return false;
5309 }
5310
5311 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5312 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5313 << NonPointerExpr->getType() << DiagType
5314 << NonPointerExpr->getSourceRange();
5315 return true;
5316}
5317
Sebastian Redl28507842009-02-26 14:39:58 +00005318/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5319/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00005320/// C99 6.5.15
5321QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005322 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00005323 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00005324
5325 // If either LHS or RHS are overloaded functions, try to resolve them.
5326 if (LHS->getType() == Context.OverloadTy ||
5327 RHS->getType() == Context.OverloadTy) {
Douglas Gregor7ad5d422010-11-09 21:07:58 +00005328 ExprResult LHSResult = CheckPlaceholderExpr(LHS, QuestionLoc);
5329 if (LHSResult.isInvalid())
5330 return QualType();
5331
5332 ExprResult RHSResult = CheckPlaceholderExpr(RHS, QuestionLoc);
5333 if (RHSResult.isInvalid())
5334 return QualType();
5335
5336 LHS = LHSResult.take();
5337 RHS = RHSResult.take();
5338 }
5339
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005340 // C++ is sufficiently different to merit its own checker.
5341 if (getLangOptions().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00005342 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00005343
5344 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005345 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005346
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005347 UsualUnaryConversions(Cond);
John McCall56ca35d2011-02-17 10:25:35 +00005348 UsualUnaryConversions(LHS);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005349 UsualUnaryConversions(RHS);
5350 QualType CondTy = Cond->getType();
5351 QualType LHSTy = LHS->getType();
5352 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005353
Reid Spencer5f016e22007-07-11 17:01:13 +00005354 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005355 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begeman6155d732010-09-20 22:41:17 +00005356 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5357 // Throw an error if its not either.
5358 if (getLangOptions().OpenCL) {
5359 if (!CondTy->isVectorType()) {
5360 Diag(Cond->getLocStart(),
5361 diag::err_typecheck_cond_expect_scalar_or_vector)
5362 << CondTy;
5363 return QualType();
5364 }
5365 }
5366 else {
5367 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5368 << CondTy;
5369 return QualType();
5370 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005371 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005372
Chris Lattner70d67a92008-01-06 22:42:25 +00005373 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005374 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5375 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00005376
Nate Begeman6155d732010-09-20 22:41:17 +00005377 // OpenCL: If the condition is a vector, and both operands are scalar,
5378 // attempt to implicity convert them to the vector type to act like the
5379 // built in select.
5380 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5381 // Both operands should be of scalar type.
5382 if (!LHSTy->isScalarType()) {
5383 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5384 << CondTy;
5385 return QualType();
5386 }
5387 if (!RHSTy->isScalarType()) {
5388 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5389 << CondTy;
5390 return QualType();
5391 }
5392 // Implicity convert these scalars to the type of the condition.
5393 ImpCastExprToType(LHS, CondTy, CK_IntegralCast);
5394 ImpCastExprToType(RHS, CondTy, CK_IntegralCast);
5395 }
5396
Chris Lattner70d67a92008-01-06 22:42:25 +00005397 // If both operands have arithmetic type, do the usual arithmetic conversions
5398 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005399 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5400 UsualArithmeticConversions(LHS, RHS);
5401 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00005402 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005403
Chris Lattner70d67a92008-01-06 22:42:25 +00005404 // If both operands are the same structure or union type, the result is that
5405 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005406 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5407 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00005408 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005409 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00005410 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005411 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005412 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00005413 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005414
Chris Lattner70d67a92008-01-06 22:42:25 +00005415 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00005416 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005417 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5418 if (!LHSTy->isVoidType())
5419 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5420 << RHS->getSourceRange();
5421 if (!RHSTy->isVoidType())
5422 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5423 << LHS->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005424 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid);
5425 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00005426 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00005427 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00005428 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5429 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005430 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005431 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005432 // promote the null to a pointer.
John McCalldaa8e4e2010-11-15 09:13:47 +00005433 ImpCastExprToType(RHS, LHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005434 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00005435 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005436 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005437 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005438 ImpCastExprToType(LHS, RHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005439 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00005440 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005441
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005442 // All objective-c pointer type analysis is done here.
5443 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5444 QuestionLoc);
5445 if (!compositeType.isNull())
5446 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005447
5448
Steve Naroff7154a772009-07-01 14:36:47 +00005449 // Handle block pointer types.
5450 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5451 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5452 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5453 QualType destType = Context.getPointerType(Context.VoidTy);
John McCall2de56d12010-08-25 11:45:40 +00005454 ImpCastExprToType(LHS, destType, CK_BitCast);
5455 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005456 return destType;
5457 }
5458 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005459 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00005460 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00005461 }
Steve Naroff7154a772009-07-01 14:36:47 +00005462 // We have 2 block pointer types.
5463 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5464 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005465 return LHSTy;
5466 }
Steve Naroff7154a772009-07-01 14:36:47 +00005467 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00005468 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5469 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005470
Steve Naroff7154a772009-07-01 14:36:47 +00005471 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5472 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00005473 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005474 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00005475 // In this situation, we assume void* type. No especially good
5476 // reason, but this is what gcc does, and we do have to pick
5477 // to get a consistent AST.
5478 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCall2de56d12010-08-25 11:45:40 +00005479 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5480 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00005481 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005482 }
Steve Naroff7154a772009-07-01 14:36:47 +00005483 // The block pointer types are compatible.
John McCall2de56d12010-08-25 11:45:40 +00005484 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5485 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00005486 return LHSTy;
5487 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005488
Steve Naroff7154a772009-07-01 14:36:47 +00005489 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5490 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5491 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00005492 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5493 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00005494
5495 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5496 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5497 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00005498 QualType destPointee
5499 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00005500 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005501 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005502 ImpCastExprToType(LHS, destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005503 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005504 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005505 return destType;
5506 }
5507 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00005508 QualType destPointee
5509 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00005510 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005511 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005512 ImpCastExprToType(RHS, destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005513 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005514 ImpCastExprToType(LHS, destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005515 return destType;
5516 }
5517
5518 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5519 // Two identical pointer types are always compatible.
5520 return LHSTy;
5521 }
5522 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5523 rhptee.getUnqualifiedType())) {
5524 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5525 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5526 // In this situation, we assume void* type. No especially good
5527 // reason, but this is what gcc does, and we do have to pick
5528 // to get a consistent AST.
5529 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCall2de56d12010-08-25 11:45:40 +00005530 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5531 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005532 return incompatTy;
5533 }
5534 // The pointer types are compatible.
5535 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5536 // differently qualified versions of compatible types, the result type is
5537 // a pointer to an appropriately qualified version of the *composite*
5538 // type.
5539 // FIXME: Need to calculate the composite type.
5540 // FIXME: Need to add qualifiers
John McCall2de56d12010-08-25 11:45:40 +00005541 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5542 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005543 return LHSTy;
5544 }
Mike Stump1eb44332009-09-09 15:08:12 +00005545
John McCall404cd162010-11-13 01:35:44 +00005546 // GCC compatibility: soften pointer/integer mismatch. Note that
5547 // null pointers have been filtered out by this point.
Steve Naroff7154a772009-07-01 14:36:47 +00005548 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5549 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5550 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005551 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00005552 return RHSTy;
5553 }
5554 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5555 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5556 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005557 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00005558 return LHSTy;
5559 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00005560
Chandler Carruth82214a82011-02-18 23:54:50 +00005561 // Emit a better diagnostic if one of the expressions is a null pointer
5562 // constant and the other is not a pointer type. In this case, the user most
5563 // likely forgot to take the address of the other expression.
5564 if (DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
5565 return QualType();
5566
Chris Lattner70d67a92008-01-06 22:42:25 +00005567 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005568 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5569 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005570 return QualType();
5571}
5572
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005573/// FindCompositeObjCPointerType - Helper method to find composite type of
5574/// two objective-c pointer types of the two input expressions.
5575QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
5576 SourceLocation QuestionLoc) {
5577 QualType LHSTy = LHS->getType();
5578 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005579
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005580 // Handle things like Class and struct objc_class*. Here we case the result
5581 // to the pseudo-builtin, because that will be implicitly cast back to the
5582 // redefinition type if an attempt is made to access its fields.
5583 if (LHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005584 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005585 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005586 return LHSTy;
5587 }
5588 if (RHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005589 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005590 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005591 return RHSTy;
5592 }
5593 // And the same for struct objc_object* / id
5594 if (LHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005595 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005596 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005597 return LHSTy;
5598 }
5599 if (RHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005600 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005601 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005602 return RHSTy;
5603 }
5604 // And the same for struct objc_selector* / SEL
5605 if (Context.isObjCSelType(LHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00005606 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005607 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005608 return LHSTy;
5609 }
5610 if (Context.isObjCSelType(RHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00005611 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005612 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005613 return RHSTy;
5614 }
5615 // Check constraints for Objective-C object pointers types.
5616 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005617
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005618 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5619 // Two identical object pointer types are always compatible.
5620 return LHSTy;
5621 }
5622 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5623 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5624 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005625
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005626 // If both operands are interfaces and either operand can be
5627 // assigned to the other, use that type as the composite
5628 // type. This allows
5629 // xxx ? (A*) a : (B*) b
5630 // where B is a subclass of A.
5631 //
5632 // Additionally, as for assignment, if either type is 'id'
5633 // allow silent coercion. Finally, if the types are
5634 // incompatible then make sure to use 'id' as the composite
5635 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005636
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005637 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5638 // It could return the composite type.
5639 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5640 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5641 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5642 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5643 } else if ((LHSTy->isObjCQualifiedIdType() ||
5644 RHSTy->isObjCQualifiedIdType()) &&
5645 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5646 // Need to handle "id<xx>" explicitly.
5647 // GCC allows qualified id and any Objective-C type to devolve to
5648 // id. Currently localizing to here until clear this should be
5649 // part of ObjCQualifiedIdTypesAreCompatible.
5650 compositeType = Context.getObjCIdType();
5651 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5652 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005653 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005654 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5655 ;
5656 else {
5657 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5658 << LHSTy << RHSTy
5659 << LHS->getSourceRange() << RHS->getSourceRange();
5660 QualType incompatTy = Context.getObjCIdType();
John McCall2de56d12010-08-25 11:45:40 +00005661 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5662 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005663 return incompatTy;
5664 }
5665 // The object pointer types are compatible.
John McCall2de56d12010-08-25 11:45:40 +00005666 ImpCastExprToType(LHS, compositeType, CK_BitCast);
5667 ImpCastExprToType(RHS, compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005668 return compositeType;
5669 }
5670 // Check Objective-C object pointer types and 'void *'
5671 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5672 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5673 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5674 QualType destPointee
5675 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5676 QualType destType = Context.getPointerType(destPointee);
5677 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005678 ImpCastExprToType(LHS, destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005679 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005680 ImpCastExprToType(RHS, destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005681 return destType;
5682 }
5683 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5684 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5685 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5686 QualType destPointee
5687 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5688 QualType destType = Context.getPointerType(destPointee);
5689 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005690 ImpCastExprToType(RHS, destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005691 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005692 ImpCastExprToType(LHS, destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005693 return destType;
5694 }
5695 return QualType();
5696}
5697
Steve Narofff69936d2007-09-16 03:34:24 +00005698/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005699/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005700ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00005701 SourceLocation ColonLoc,
5702 Expr *CondExpr, Expr *LHSExpr,
5703 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005704 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5705 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00005706 OpaqueValueExpr *opaqueValue = 0;
5707 Expr *commonExpr = 0;
5708 if (LHSExpr == 0) {
5709 commonExpr = CondExpr;
5710
5711 // We usually want to apply unary conversions *before* saving, except
5712 // in the special case of a C++ l-value conditional.
5713 if (!(getLangOptions().CPlusPlus
5714 && !commonExpr->isTypeDependent()
5715 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5716 && commonExpr->isGLValue()
5717 && commonExpr->isOrdinaryOrBitFieldObject()
5718 && RHSExpr->isOrdinaryOrBitFieldObject()
5719 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5720 UsualUnaryConversions(commonExpr);
5721 }
5722
5723 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5724 commonExpr->getType(),
5725 commonExpr->getValueKind(),
5726 commonExpr->getObjectKind());
5727 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005728 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005729
John McCallf89e55a2010-11-18 06:31:45 +00005730 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005731 ExprObjectKind OK = OK_Ordinary;
Fariborz Jahanian1fb019b2010-09-18 19:38:38 +00005732 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr,
John McCall56ca35d2011-02-17 10:25:35 +00005733 VK, OK, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00005734 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005735 return ExprError();
5736
John McCall56ca35d2011-02-17 10:25:35 +00005737 if (!commonExpr)
5738 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
5739 LHSExpr, ColonLoc,
5740 RHSExpr, result, VK, OK));
5741
5742 return Owned(new (Context)
5743 BinaryConditionalOperator(commonExpr, opaqueValue, CondExpr, LHSExpr,
5744 RHSExpr, QuestionLoc, ColonLoc, result, VK, OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005745}
5746
John McCalle4be87e2011-01-31 23:13:11 +00005747// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005748// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005749// routine is it effectively iqnores the qualifiers on the top level pointee.
5750// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5751// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005752static Sema::AssignConvertType
5753checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5754 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5755 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005756
Reid Spencer5f016e22007-07-11 17:01:13 +00005757 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005758 const Type *lhptee, *rhptee;
5759 Qualifiers lhq, rhq;
5760 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5761 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005762
John McCalle4be87e2011-01-31 23:13:11 +00005763 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005764
5765 // C99 6.5.16.1p1: This following citation is common to constraints
5766 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5767 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005768 Qualifiers lq;
5769
5770 if (!lhq.compatiblyIncludes(rhq)) {
5771 // Treat address-space mismatches as fatal. TODO: address subspaces
5772 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5773 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5774
5775 // For GCC compatibility, other qualifier mismatches are treated
5776 // as still compatible in C.
5777 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5778 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005779
Mike Stumpeed9cac2009-02-19 03:04:26 +00005780 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5781 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005782 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005783 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005784 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005785 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005786
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005787 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005788 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005789 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005790 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005791
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005792 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005793 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005794 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005795
5796 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005797 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005798 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005799 }
John McCall86c05f32011-02-01 00:10:29 +00005800
Mike Stumpeed9cac2009-02-19 03:04:26 +00005801 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005802 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005803 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5804 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005805 // Check if the pointee types are compatible ignoring the sign.
5806 // We explicitly check for char so that we catch "char" vs
5807 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005808 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005809 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005810 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005811 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005812
Chris Lattner6a2b9262009-10-17 20:33:28 +00005813 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005814 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005815 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005816 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005817
John McCall86c05f32011-02-01 00:10:29 +00005818 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005819 // Types are compatible ignoring the sign. Qualifier incompatibility
5820 // takes priority over sign incompatibility because the sign
5821 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005822 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005823 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005824
John McCalle4be87e2011-01-31 23:13:11 +00005825 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005826 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005827
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005828 // If we are a multi-level pointer, it's possible that our issue is simply
5829 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5830 // the eventual target type is the same and the pointers have the same
5831 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005832 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005833 do {
John McCall86c05f32011-02-01 00:10:29 +00005834 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5835 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005836 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005837
John McCall86c05f32011-02-01 00:10:29 +00005838 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005839 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005840 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005841
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005842 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005843 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005844 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005845 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005846}
5847
John McCalle4be87e2011-01-31 23:13:11 +00005848/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005849/// block pointer types are compatible or whether a block and normal pointer
5850/// are compatible. It is more restrict than comparing two function pointer
5851// types.
John McCalle4be87e2011-01-31 23:13:11 +00005852static Sema::AssignConvertType
5853checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5854 QualType rhsType) {
5855 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5856 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5857
Steve Naroff1c7d0672008-09-04 15:10:53 +00005858 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005859
Steve Naroff1c7d0672008-09-04 15:10:53 +00005860 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCalle4be87e2011-01-31 23:13:11 +00005861 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5862 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005863
John McCalle4be87e2011-01-31 23:13:11 +00005864 // In C++, the types have to match exactly.
5865 if (S.getLangOptions().CPlusPlus)
5866 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005867
John McCalle4be87e2011-01-31 23:13:11 +00005868 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005869
Steve Naroff1c7d0672008-09-04 15:10:53 +00005870 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005871 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5872 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005873
John McCalle4be87e2011-01-31 23:13:11 +00005874 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5875 return Sema::IncompatibleBlockPointer;
5876
Steve Naroff1c7d0672008-09-04 15:10:53 +00005877 return ConvTy;
5878}
5879
John McCalle4be87e2011-01-31 23:13:11 +00005880/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005881/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005882static Sema::AssignConvertType
5883checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5884 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5885 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5886
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005887 if (lhsType->isObjCBuiltinType()) {
5888 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00005889 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5890 !rhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005891 return Sema::IncompatiblePointer;
5892 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005893 }
5894 if (rhsType->isObjCBuiltinType()) {
5895 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00005896 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5897 !lhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005898 return Sema::IncompatiblePointer;
5899 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005900 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005901 QualType lhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005902 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005903 QualType rhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005904 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005905
John McCalle4be87e2011-01-31 23:13:11 +00005906 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5907 return Sema::CompatiblePointerDiscardsQualifiers;
5908
5909 if (S.Context.typesAreCompatible(lhsType, rhsType))
5910 return Sema::Compatible;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005911 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005912 return Sema::IncompatibleObjCQualifiedId;
5913 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005914}
5915
John McCall1c23e912010-11-16 02:32:08 +00005916Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005917Sema::CheckAssignmentConstraints(SourceLocation Loc,
5918 QualType lhsType, QualType rhsType) {
John McCall1c23e912010-11-16 02:32:08 +00005919 // Fake up an opaque expression. We don't actually care about what
5920 // cast operations are required, so if CheckAssignmentConstraints
5921 // adds casts to this they'll be wasted, but fortunately that doesn't
5922 // usually happen on valid code.
Douglas Gregorb608b982011-01-28 02:26:04 +00005923 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John McCall1c23e912010-11-16 02:32:08 +00005924 Expr *rhsPtr = &rhs;
5925 CastKind K = CK_Invalid;
5926
5927 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5928}
5929
Mike Stumpeed9cac2009-02-19 03:04:26 +00005930/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5931/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005932/// pointers. Here are some objectionable examples that GCC considers warnings:
5933///
5934/// int a, *pint;
5935/// short *pshort;
5936/// struct foo *pfoo;
5937///
5938/// pint = pshort; // warning: assignment from incompatible pointer type
5939/// a = pint; // warning: assignment makes integer from pointer without a cast
5940/// pint = a; // warning: assignment makes pointer from integer without a cast
5941/// pint = pfoo; // warning: assignment from incompatible pointer type
5942///
5943/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005944/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005945///
John McCalldaa8e4e2010-11-15 09:13:47 +00005946/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005947Sema::AssignConvertType
John McCall1c23e912010-11-16 02:32:08 +00005948Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs,
John McCalldaa8e4e2010-11-15 09:13:47 +00005949 CastKind &Kind) {
John McCall1c23e912010-11-16 02:32:08 +00005950 QualType rhsType = rhs->getType();
5951
Chris Lattnerfc144e22008-01-04 23:18:45 +00005952 // Get canonical types. We're not formatting these types, just comparing
5953 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00005954 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5955 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005956
John McCallb6cfa242011-01-31 22:28:28 +00005957 // Common case: no conversion required.
John McCalldaa8e4e2010-11-15 09:13:47 +00005958 if (lhsType == rhsType) {
5959 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005960 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005961 }
5962
Douglas Gregor9d293df2008-10-28 00:22:11 +00005963 // If the left-hand side is a reference type, then we are in a
5964 // (rare!) case where we've allowed the use of references in C,
5965 // e.g., as a parameter type in a built-in function. In this case,
5966 // just make sure that the type referenced is compatible with the
5967 // right-hand side type. The caller is responsible for adjusting
5968 // lhsType so that the resulting expression does not have reference
5969 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005970 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005971 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5972 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005973 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005974 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005975 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005976 }
John McCallb6cfa242011-01-31 22:28:28 +00005977
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005978 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5979 // to the same ExtVector type.
5980 if (lhsType->isExtVectorType()) {
5981 if (rhsType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005982 return Incompatible;
5983 if (rhsType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005984 // CK_VectorSplat does T -> vector T, so first cast to the
5985 // element type.
5986 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5987 if (elType != rhsType) {
5988 Kind = PrepareScalarCast(*this, rhs, elType);
5989 ImpCastExprToType(rhs, elType, Kind);
5990 }
5991 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005992 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005993 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005994 }
Mike Stump1eb44332009-09-09 15:08:12 +00005995
John McCallb6cfa242011-01-31 22:28:28 +00005996 // Conversions to or from vector type.
Nate Begemanbe2341d2008-07-14 18:02:46 +00005997 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor255210e2010-08-06 10:14:59 +00005998 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005999 // Allow assignments of an AltiVec vector type to an equivalent GCC
6000 // vector type and vice versa
6001 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
6002 Kind = CK_BitCast;
6003 return Compatible;
6004 }
6005
Douglas Gregor255210e2010-08-06 10:14:59 +00006006 // If we are allowing lax vector conversions, and LHS and RHS are both
6007 // vectors, the total size only needs to be the same. This is a bitcast;
6008 // no bits are changed but the result type is different.
6009 if (getLangOptions().LaxVectorConversions &&
John McCalldaa8e4e2010-11-15 09:13:47 +00006010 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00006011 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006012 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00006013 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00006014 }
6015 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006016 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006017
John McCallb6cfa242011-01-31 22:28:28 +00006018 // Arithmetic conversions.
Douglas Gregor88623ad2010-05-23 21:53:47 +00006019 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00006020 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall1c23e912010-11-16 02:32:08 +00006021 Kind = PrepareScalarCast(*this, rhs, lhsType);
Reid Spencer5f016e22007-07-11 17:01:13 +00006022 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006023 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006024
John McCallb6cfa242011-01-31 22:28:28 +00006025 // Conversions to normal pointers.
6026 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
6027 // U* -> T*
John McCalldaa8e4e2010-11-15 09:13:47 +00006028 if (isa<PointerType>(rhsType)) {
6029 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00006030 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006031 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006032
John McCallb6cfa242011-01-31 22:28:28 +00006033 // int -> T*
6034 if (rhsType->isIntegerType()) {
6035 Kind = CK_IntegralToPointer; // FIXME: null?
6036 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00006037 }
John McCallb6cfa242011-01-31 22:28:28 +00006038
6039 // C pointers are not compatible with ObjC object pointers,
6040 // with two exceptions:
6041 if (isa<ObjCObjectPointerType>(rhsType)) {
6042 // - conversions to void*
6043 if (lhsPointer->getPointeeType()->isVoidType()) {
6044 Kind = CK_AnyPointerToObjCPointerCast;
6045 return Compatible;
6046 }
6047
6048 // - conversions from 'Class' to the redefinition type
6049 if (rhsType->isObjCClassType() &&
6050 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006051 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00006052 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006053 }
Steve Naroffb4406862008-09-29 18:10:17 +00006054
John McCallb6cfa242011-01-31 22:28:28 +00006055 Kind = CK_BitCast;
6056 return IncompatiblePointer;
6057 }
6058
6059 // U^ -> void*
6060 if (rhsType->getAs<BlockPointerType>()) {
6061 if (lhsPointer->getPointeeType()->isVoidType()) {
6062 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00006063 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006064 }
Steve Naroffb4406862008-09-29 18:10:17 +00006065 }
John McCallb6cfa242011-01-31 22:28:28 +00006066
Steve Naroff1c7d0672008-09-04 15:10:53 +00006067 return Incompatible;
6068 }
6069
John McCallb6cfa242011-01-31 22:28:28 +00006070 // Conversions to block pointers.
Steve Naroff1c7d0672008-09-04 15:10:53 +00006071 if (isa<BlockPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006072 // U^ -> T^
6073 if (rhsType->isBlockPointerType()) {
6074 Kind = CK_AnyPointerToBlockPointerCast;
John McCalle4be87e2011-01-31 23:13:11 +00006075 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00006076 }
6077
6078 // int or null -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00006079 if (rhsType->isIntegerType()) {
6080 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00006081 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00006082 }
6083
John McCallb6cfa242011-01-31 22:28:28 +00006084 // id -> T^
6085 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6086 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00006087 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006088 }
Steve Naroffb4406862008-09-29 18:10:17 +00006089
John McCallb6cfa242011-01-31 22:28:28 +00006090 // void* -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00006091 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00006092 if (RHSPT->getPointeeType()->isVoidType()) {
6093 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00006094 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006095 }
John McCalldaa8e4e2010-11-15 09:13:47 +00006096
Chris Lattnerfc144e22008-01-04 23:18:45 +00006097 return Incompatible;
6098 }
6099
John McCallb6cfa242011-01-31 22:28:28 +00006100 // Conversions to Objective-C pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00006101 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006102 // A* -> B*
6103 if (rhsType->isObjCObjectPointerType()) {
6104 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00006105 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00006106 }
6107
6108 // int or null -> A*
John McCalldaa8e4e2010-11-15 09:13:47 +00006109 if (rhsType->isIntegerType()) {
6110 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00006111 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00006112 }
6113
John McCallb6cfa242011-01-31 22:28:28 +00006114 // In general, C pointers are not compatible with ObjC object pointers,
6115 // with two exceptions:
Steve Naroff14108da2009-07-10 23:34:53 +00006116 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006117 // - conversions from 'void*'
6118 if (rhsType->isVoidPointerType()) {
6119 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00006120 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006121 }
6122
6123 // - conversions to 'Class' from its redefinition type
6124 if (lhsType->isObjCClassType() &&
6125 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6126 Kind = CK_BitCast;
6127 return Compatible;
6128 }
6129
6130 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00006131 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00006132 }
John McCallb6cfa242011-01-31 22:28:28 +00006133
6134 // T^ -> A*
6135 if (rhsType->isBlockPointerType()) {
6136 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00006137 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006138 }
6139
Steve Naroff14108da2009-07-10 23:34:53 +00006140 return Incompatible;
6141 }
John McCallb6cfa242011-01-31 22:28:28 +00006142
6143 // Conversions from pointers that are not covered by the above.
Chris Lattner78eca282008-04-07 06:49:41 +00006144 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006145 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00006146 if (lhsType == Context.BoolTy) {
6147 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006148 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006149 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006150
John McCallb6cfa242011-01-31 22:28:28 +00006151 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00006152 if (lhsType->isIntegerType()) {
6153 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006154 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00006155 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006156
Chris Lattnerfc144e22008-01-04 23:18:45 +00006157 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00006158 }
John McCallb6cfa242011-01-31 22:28:28 +00006159
6160 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff14108da2009-07-10 23:34:53 +00006161 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006162 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00006163 if (lhsType == Context.BoolTy) {
6164 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00006165 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006166 }
Steve Naroff14108da2009-07-10 23:34:53 +00006167
John McCallb6cfa242011-01-31 22:28:28 +00006168 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00006169 if (lhsType->isIntegerType()) {
6170 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00006171 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00006172 }
6173
Steve Naroff14108da2009-07-10 23:34:53 +00006174 return Incompatible;
6175 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006176
John McCallb6cfa242011-01-31 22:28:28 +00006177 // struct A -> struct B
Chris Lattnerfc144e22008-01-04 23:18:45 +00006178 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006179 if (Context.typesAreCompatible(lhsType, rhsType)) {
6180 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00006181 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006182 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006183 }
John McCallb6cfa242011-01-31 22:28:28 +00006184
Reid Spencer5f016e22007-07-11 17:01:13 +00006185 return Incompatible;
6186}
6187
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006188/// \brief Constructs a transparent union from an expression that is
6189/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00006190static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006191 QualType UnionType, FieldDecl *Field) {
6192 // Build an initializer list that designates the appropriate member
6193 // of the transparent union.
Ted Kremenek709210f2010-04-13 23:39:13 +00006194 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00006195 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006196 SourceLocation());
6197 Initializer->setType(UnionType);
6198 Initializer->setInitializedFieldInUnion(Field);
6199
6200 // Build a compound literal constructing a value of the transparent
6201 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00006202 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall1d7d8d62010-01-19 22:33:45 +00006203 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCallf89e55a2010-11-18 06:31:45 +00006204 VK_RValue, Initializer, false);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006205}
6206
6207Sema::AssignConvertType
6208Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
6209 QualType FromType = rExpr->getType();
6210
Mike Stump1eb44332009-09-09 15:08:12 +00006211 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006212 // transparent_union GCC extension.
6213 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006214 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006215 return Incompatible;
6216
6217 // The field to initialize within the transparent union.
6218 RecordDecl *UD = UT->getDecl();
6219 FieldDecl *InitField = 0;
6220 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006221 for (RecordDecl::field_iterator it = UD->field_begin(),
6222 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006223 it != itend; ++it) {
6224 if (it->getType()->isPointerType()) {
6225 // If the transparent union contains a pointer type, we allow:
6226 // 1) void pointer
6227 // 2) null pointer constant
6228 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00006229 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John McCall2de56d12010-08-25 11:45:40 +00006230 ImpCastExprToType(rExpr, it->getType(), CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006231 InitField = *it;
6232 break;
6233 }
Mike Stump1eb44332009-09-09 15:08:12 +00006234
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006235 if (rExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006236 Expr::NPC_ValueDependentIsNull)) {
John McCall404cd162010-11-13 01:35:44 +00006237 ImpCastExprToType(rExpr, it->getType(), CK_NullToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006238 InitField = *it;
6239 break;
6240 }
6241 }
6242
John McCall1c23e912010-11-16 02:32:08 +00006243 Expr *rhs = rExpr;
John McCalldaa8e4e2010-11-15 09:13:47 +00006244 CastKind Kind = CK_Invalid;
John McCall1c23e912010-11-16 02:32:08 +00006245 if (CheckAssignmentConstraints(it->getType(), rhs, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006246 == Compatible) {
John McCall1c23e912010-11-16 02:32:08 +00006247 ImpCastExprToType(rhs, it->getType(), Kind);
6248 rExpr = rhs;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006249 InitField = *it;
6250 break;
6251 }
6252 }
6253
6254 if (!InitField)
6255 return Incompatible;
6256
6257 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
6258 return Compatible;
6259}
6260
Chris Lattner5cf216b2008-01-04 18:04:52 +00006261Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00006262Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00006263 if (getLangOptions().CPlusPlus) {
6264 if (!lhsType->isRecordType()) {
6265 // C++ 5.17p3: If the left operand is not of class type, the
6266 // expression is implicitly converted (C++ 4) to the
6267 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00006268 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor68647482009-12-16 03:45:30 +00006269 AA_Assigning))
Douglas Gregor98cd5992008-10-21 23:43:52 +00006270 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00006271 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00006272 }
6273
6274 // FIXME: Currently, we fall through and treat C++ classes like C
6275 // structures.
John McCallf6a16482010-12-04 03:47:34 +00006276 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00006277
Steve Naroff529a4ad2007-11-27 17:58:44 +00006278 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6279 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00006280 if ((lhsType->isPointerType() ||
6281 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00006282 lhsType->isBlockPointerType())
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006283 && rExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006284 Expr::NPC_ValueDependentIsNull)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006285 ImpCastExprToType(rExpr, lhsType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00006286 return Compatible;
6287 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006288
Chris Lattner943140e2007-10-16 02:55:40 +00006289 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00006290 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00006291 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00006292 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00006293 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00006294 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00006295 if (!lhsType->isReferenceType())
Douglas Gregora873dfc2010-02-03 00:27:59 +00006296 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00006297
John McCalldaa8e4e2010-11-15 09:13:47 +00006298 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006299 Sema::AssignConvertType result =
John McCall1c23e912010-11-16 02:32:08 +00006300 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006301
Steve Narofff1120de2007-08-24 22:33:52 +00006302 // C99 6.5.16.1p2: The value of the right operand is converted to the
6303 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00006304 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6305 // so that we can use references in built-in functions even in C.
6306 // The getNonReferenceType() call makes sure that the resulting expression
6307 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006308 if (result != Incompatible && rExpr->getType() != lhsType)
John McCalldaa8e4e2010-11-15 09:13:47 +00006309 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00006310 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00006311}
6312
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006313QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006314 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00006315 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006316 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorfadb53b2011-03-12 01:48:56 +00006317 if (lex->getType() == Context.OverloadTy)
6318 NoteAllOverloadCandidates(lex);
6319 if (rex->getType() == Context.OverloadTy)
6320 NoteAllOverloadCandidates(rex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00006321 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006322}
6323
Chris Lattner7ef655a2010-01-12 21:23:57 +00006324QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00006325 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006326 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00006327 QualType lhsType =
6328 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
6329 QualType rhsType =
6330 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006331
Nate Begemanbe2341d2008-07-14 18:02:46 +00006332 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006333 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00006334 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00006335
Nate Begemanbe2341d2008-07-14 18:02:46 +00006336 // Handle the case of a vector & extvector type of the same size and element
6337 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006338 if (getLangOptions().LaxVectorConversions) {
John McCall183700f2009-09-21 23:43:11 +00006339 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth629f9e42010-08-30 07:36:24 +00006340 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00006341 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006342 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregor26bcf672010-05-19 03:21:00 +00006343 if (lhsType->isExtVectorType()) {
John McCall2de56d12010-08-25 11:45:40 +00006344 ImpCastExprToType(rex, lhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006345 return lhsType;
6346 }
6347
John McCall2de56d12010-08-25 11:45:40 +00006348 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006349 return rhsType;
Eric Christophere84f9eb2010-08-26 00:42:16 +00006350 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6351 // If we are allowing lax vector conversions, and LHS and RHS are both
6352 // vectors, the total size only needs to be the same. This is a
6353 // bitcast; no bits are changed but the result type is different.
6354 ImpCastExprToType(rex, lhsType, CK_BitCast);
6355 return lhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006356 }
Eric Christophere84f9eb2010-08-26 00:42:16 +00006357 }
Chandler Carruth629f9e42010-08-30 07:36:24 +00006358 }
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006359 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006360
Douglas Gregor255210e2010-08-06 10:14:59 +00006361 // Handle the case of equivalent AltiVec and GCC vector types
6362 if (lhsType->isVectorType() && rhsType->isVectorType() &&
6363 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John McCall2de56d12010-08-25 11:45:40 +00006364 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor255210e2010-08-06 10:14:59 +00006365 return rhsType;
6366 }
6367
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006368 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6369 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6370 bool swapped = false;
6371 if (rhsType->isExtVectorType()) {
6372 swapped = true;
6373 std::swap(rex, lex);
6374 std::swap(rhsType, lhsType);
6375 }
Mike Stump1eb44332009-09-09 15:08:12 +00006376
Nate Begemandde25982009-06-28 19:12:57 +00006377 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00006378 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006379 QualType EltTy = LV->getElementType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00006380 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006381 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6382 if (order > 0)
6383 ImpCastExprToType(rex, EltTy, CK_IntegralCast);
6384 if (order >= 0) {
6385 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006386 if (swapped) std::swap(rex, lex);
6387 return lhsType;
6388 }
6389 }
6390 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6391 rhsType->isRealFloatingType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006392 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6393 if (order > 0)
6394 ImpCastExprToType(rex, EltTy, CK_FloatingCast);
6395 if (order >= 0) {
6396 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006397 if (swapped) std::swap(rex, lex);
6398 return lhsType;
6399 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00006400 }
6401 }
Mike Stump1eb44332009-09-09 15:08:12 +00006402
Nate Begemandde25982009-06-28 19:12:57 +00006403 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006404 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00006405 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006406 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006407 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00006408}
6409
Chris Lattner7ef655a2010-01-12 21:23:57 +00006410QualType Sema::CheckMultiplyDivideOperands(
6411 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00006412 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006413 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006414
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006415 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006416
Chris Lattner7ef655a2010-01-12 21:23:57 +00006417 if (!lex->getType()->isArithmeticType() ||
6418 !rex->getType()->isArithmeticType())
6419 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006420
Chris Lattner7ef655a2010-01-12 21:23:57 +00006421 // Check for division by zero.
6422 if (isDiv &&
6423 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Ted Kremenek762696f2011-02-23 01:51:43 +00006424 DiagRuntimeBehavior(Loc, rex, PDiag(diag::warn_division_by_zero)
6425 << rex->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006426
Chris Lattner7ef655a2010-01-12 21:23:57 +00006427 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006428}
6429
Chris Lattner7ef655a2010-01-12 21:23:57 +00006430QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00006431 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00006432 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
Douglas Gregorf6094622010-07-23 15:58:24 +00006433 if (lex->getType()->hasIntegerRepresentation() &&
6434 rex->getType()->hasIntegerRepresentation())
Daniel Dunbar523aa602009-01-05 22:55:36 +00006435 return CheckVectorOperands(Loc, lex, rex);
6436 return InvalidOperands(Loc, lex, rex);
6437 }
Steve Naroff90045e82007-07-13 23:32:42 +00006438
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006439 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006440
Chris Lattner7ef655a2010-01-12 21:23:57 +00006441 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
6442 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006443
Chris Lattner7ef655a2010-01-12 21:23:57 +00006444 // Check for remainder by zero.
6445 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Ted Kremenek762696f2011-02-23 01:51:43 +00006446 DiagRuntimeBehavior(Loc, rex, PDiag(diag::warn_remainder_by_zero)
6447 << rex->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006448
Chris Lattner7ef655a2010-01-12 21:23:57 +00006449 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006450}
6451
Chris Lattner7ef655a2010-01-12 21:23:57 +00006452QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00006453 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006454 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6455 QualType compType = CheckVectorOperands(Loc, lex, rex);
6456 if (CompLHSTy) *CompLHSTy = compType;
6457 return compType;
6458 }
Steve Naroff49b45262007-07-13 16:58:59 +00006459
Eli Friedmanab3a8522009-03-28 01:22:36 +00006460 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00006461
Reid Spencer5f016e22007-07-11 17:01:13 +00006462 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00006463 if (lex->getType()->isArithmeticType() &&
6464 rex->getType()->isArithmeticType()) {
6465 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006466 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006467 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006468
Eli Friedmand72d16e2008-05-18 18:08:51 +00006469 // Put any potential pointer into PExp
6470 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006471 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00006472 std::swap(PExp, IExp);
6473
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006474 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006475
Eli Friedmand72d16e2008-05-18 18:08:51 +00006476 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00006477 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00006478
Chris Lattnerb5f15622009-04-24 23:50:08 +00006479 // Check for arithmetic on pointers to incomplete types.
6480 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006481 if (getLangOptions().CPlusPlus) {
6482 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006483 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006484 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006485 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006486
6487 // GNU extension: arithmetic on pointer to void
6488 Diag(Loc, diag::ext_gnu_void_ptr)
6489 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00006490 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006491 if (getLangOptions().CPlusPlus) {
6492 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6493 << lex->getType() << lex->getSourceRange();
6494 return QualType();
6495 }
6496
6497 // GNU extension: arithmetic on pointer to function
6498 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6499 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00006500 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00006501 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00006502 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00006503 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00006504 PExp->getType()->isObjCObjectPointerType()) &&
6505 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00006506 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6507 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00006508 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00006509 return QualType();
6510 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00006511 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00006512 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00006513 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6514 << PointeeTy << PExp->getSourceRange();
6515 return QualType();
6516 }
Mike Stump1eb44332009-09-09 15:08:12 +00006517
Eli Friedmanab3a8522009-03-28 01:22:36 +00006518 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00006519 QualType LHSTy = Context.isPromotableBitField(lex);
6520 if (LHSTy.isNull()) {
6521 LHSTy = lex->getType();
6522 if (LHSTy->isPromotableIntegerType())
6523 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00006524 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00006525 *CompLHSTy = LHSTy;
6526 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00006527 return PExp->getType();
6528 }
6529 }
6530
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006531 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006532}
6533
Chris Lattnereca7be62008-04-07 05:30:13 +00006534// C99 6.5.6
6535QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00006536 SourceLocation Loc, QualType* CompLHSTy) {
6537 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6538 QualType compType = CheckVectorOperands(Loc, lex, rex);
6539 if (CompLHSTy) *CompLHSTy = compType;
6540 return compType;
6541 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006542
Eli Friedmanab3a8522009-03-28 01:22:36 +00006543 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006544
Chris Lattner6e4ab612007-12-09 21:53:25 +00006545 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006546
Chris Lattner6e4ab612007-12-09 21:53:25 +00006547 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00006548 if (lex->getType()->isArithmeticType()
6549 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006550 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006551 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006552 }
Mike Stump1eb44332009-09-09 15:08:12 +00006553
Chris Lattner6e4ab612007-12-09 21:53:25 +00006554 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006555 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00006556 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006557
Douglas Gregore7450f52009-03-24 19:52:54 +00006558 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00006559
Douglas Gregore7450f52009-03-24 19:52:54 +00006560 bool ComplainAboutVoid = false;
6561 Expr *ComplainAboutFunc = 0;
6562 if (lpointee->isVoidType()) {
6563 if (getLangOptions().CPlusPlus) {
6564 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6565 << lex->getSourceRange() << rex->getSourceRange();
6566 return QualType();
6567 }
6568
6569 // GNU C extension: arithmetic on pointer to void
6570 ComplainAboutVoid = true;
6571 } else if (lpointee->isFunctionType()) {
6572 if (getLangOptions().CPlusPlus) {
6573 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00006574 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006575 return QualType();
6576 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006577
6578 // GNU C extension: arithmetic on pointer to function
6579 ComplainAboutFunc = lex;
6580 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00006581 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00006582 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00006583 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00006584 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00006585 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006586
Chris Lattnerb5f15622009-04-24 23:50:08 +00006587 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00006588 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00006589 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6590 << lpointee << lex->getSourceRange();
6591 return QualType();
6592 }
Mike Stump1eb44332009-09-09 15:08:12 +00006593
Chris Lattner6e4ab612007-12-09 21:53:25 +00006594 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00006595 if (rex->getType()->isIntegerType()) {
6596 if (ComplainAboutVoid)
6597 Diag(Loc, diag::ext_gnu_void_ptr)
6598 << lex->getSourceRange() << rex->getSourceRange();
6599 if (ComplainAboutFunc)
6600 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00006601 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00006602 << ComplainAboutFunc->getSourceRange();
6603
Eli Friedmanab3a8522009-03-28 01:22:36 +00006604 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006605 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006606 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006607
Chris Lattner6e4ab612007-12-09 21:53:25 +00006608 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006609 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006610 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006611
Douglas Gregore7450f52009-03-24 19:52:54 +00006612 // RHS must be a completely-type object type.
6613 // Handle the GNU void* extension.
6614 if (rpointee->isVoidType()) {
6615 if (getLangOptions().CPlusPlus) {
6616 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6617 << lex->getSourceRange() << rex->getSourceRange();
6618 return QualType();
6619 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006620
Douglas Gregore7450f52009-03-24 19:52:54 +00006621 ComplainAboutVoid = true;
6622 } else if (rpointee->isFunctionType()) {
6623 if (getLangOptions().CPlusPlus) {
6624 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00006625 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006626 return QualType();
6627 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006628
6629 // GNU extension: arithmetic on pointer to function
6630 if (!ComplainAboutFunc)
6631 ComplainAboutFunc = rex;
6632 } else if (!rpointee->isDependentType() &&
6633 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00006634 PDiag(diag::err_typecheck_sub_ptr_object)
6635 << rex->getSourceRange()
6636 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00006637 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006638
Eli Friedman88d936b2009-05-16 13:54:38 +00006639 if (getLangOptions().CPlusPlus) {
6640 // Pointee types must be the same: C++ [expr.add]
6641 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6642 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6643 << lex->getType() << rex->getType()
6644 << lex->getSourceRange() << rex->getSourceRange();
6645 return QualType();
6646 }
6647 } else {
6648 // Pointee types must be compatible C99 6.5.6p3
6649 if (!Context.typesAreCompatible(
6650 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6651 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6652 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6653 << lex->getType() << rex->getType()
6654 << lex->getSourceRange() << rex->getSourceRange();
6655 return QualType();
6656 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006657 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006658
Douglas Gregore7450f52009-03-24 19:52:54 +00006659 if (ComplainAboutVoid)
6660 Diag(Loc, diag::ext_gnu_void_ptr)
6661 << lex->getSourceRange() << rex->getSourceRange();
6662 if (ComplainAboutFunc)
6663 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00006664 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00006665 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006666
6667 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006668 return Context.getPointerDiffType();
6669 }
6670 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006671
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006672 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006673}
6674
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006675static bool isScopedEnumerationType(QualType T) {
6676 if (const EnumType *ET = dyn_cast<EnumType>(T))
6677 return ET->getDecl()->isScoped();
6678 return false;
6679}
6680
Chandler Carruth21206d52011-02-23 23:34:11 +00006681static void DiagnoseBadShiftValues(Sema& S, Expr *&lex, Expr *&rex,
6682 SourceLocation Loc, unsigned Opc,
6683 QualType LHSTy) {
6684 llvm::APSInt Right;
6685 // Check right/shifter operand
6686 if (rex->isValueDependent() || !rex->isIntegerConstantExpr(Right, S.Context))
6687 return;
6688
6689 if (Right.isNegative()) {
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006690 S.DiagRuntimeBehavior(Loc, rex,
6691 S.PDiag(diag::warn_shift_negative)
6692 << rex->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006693 return;
6694 }
6695 llvm::APInt LeftBits(Right.getBitWidth(),
6696 S.Context.getTypeSize(lex->getType()));
6697 if (Right.uge(LeftBits)) {
Ted Kremenek425a31e2011-03-01 19:13:22 +00006698 S.DiagRuntimeBehavior(Loc, rex,
6699 S.PDiag(diag::warn_shift_gt_typewidth)
6700 << rex->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006701 return;
6702 }
6703 if (Opc != BO_Shl)
6704 return;
6705
6706 // When left shifting an ICE which is signed, we can check for overflow which
6707 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6708 // integers have defined behavior modulo one more than the maximum value
6709 // representable in the result type, so never warn for those.
6710 llvm::APSInt Left;
Chandler Carruth6c3c3f52011-02-24 00:03:53 +00006711 if (lex->isValueDependent() || !lex->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth21206d52011-02-23 23:34:11 +00006712 LHSTy->hasUnsignedIntegerRepresentation())
6713 return;
6714 llvm::APInt ResultBits =
6715 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6716 if (LeftBits.uge(ResultBits))
6717 return;
6718 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6719 Result = Result.shl(Right);
6720
6721 // If we are only missing a sign bit, this is less likely to result in actual
6722 // bugs -- if the result is cast back to an unsigned type, it will have the
6723 // expected value. Thus we place this behind a different warning that can be
6724 // turned off separately if needed.
6725 if (LeftBits == ResultBits - 1) {
6726 S.Diag(Loc, diag::warn_shift_result_overrides_sign_bit)
6727 << Result.toString(10) << LHSTy
6728 << lex->getSourceRange() << rex->getSourceRange();
6729 return;
6730 }
6731
6732 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
6733 << Result.toString(10) << Result.getMinSignedBits() << LHSTy
6734 << Left.getBitWidth() << lex->getSourceRange() << rex->getSourceRange();
6735}
6736
Chris Lattnereca7be62008-04-07 05:30:13 +00006737// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006738QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chandler Carruth21206d52011-02-23 23:34:11 +00006739 unsigned Opc, bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00006740 // C99 6.5.7p2: Each of the operands shall have integer type.
Douglas Gregorf6094622010-07-23 15:58:24 +00006741 if (!lex->getType()->hasIntegerRepresentation() ||
6742 !rex->getType()->hasIntegerRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006743 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006744
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006745 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6746 // hasIntegerRepresentation() above instead of this.
6747 if (isScopedEnumerationType(lex->getType()) ||
6748 isScopedEnumerationType(rex->getType())) {
6749 return InvalidOperands(Loc, lex, rex);
6750 }
6751
Nate Begeman2207d792009-10-25 02:26:48 +00006752 // Vector shifts promote their scalar inputs to vector type.
6753 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6754 return CheckVectorOperands(Loc, lex, rex);
6755
Chris Lattnerca5eede2007-12-12 05:47:28 +00006756 // Shifts don't perform usual arithmetic conversions, they just do integer
6757 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006758
John McCall1bc80af2010-12-16 19:28:59 +00006759 // For the LHS, do usual unary conversions, but then reset them away
6760 // if this is a compound assignment.
6761 Expr *old_lex = lex;
6762 UsualUnaryConversions(lex);
6763 QualType LHSTy = lex->getType();
6764 if (isCompAssign) lex = old_lex;
6765
6766 // The RHS is simpler.
Chris Lattnerca5eede2007-12-12 05:47:28 +00006767 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006768
Ryan Flynnd0439682009-08-07 16:20:20 +00006769 // Sanity-check shift operands
Chandler Carruth21206d52011-02-23 23:34:11 +00006770 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnd0439682009-08-07 16:20:20 +00006771
Chris Lattnerca5eede2007-12-12 05:47:28 +00006772 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00006773 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006774}
6775
Chandler Carruth99919472010-07-10 12:30:03 +00006776static bool IsWithinTemplateSpecialization(Decl *D) {
6777 if (DeclContext *DC = D->getDeclContext()) {
6778 if (isa<ClassTemplateSpecializationDecl>(DC))
6779 return true;
6780 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6781 return FD->isFunctionTemplateSpecialization();
6782 }
6783 return false;
6784}
6785
Douglas Gregor0c6db942009-05-04 06:07:12 +00006786// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006787QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00006788 unsigned OpaqueOpc, bool isRelational) {
John McCall2de56d12010-08-25 11:45:40 +00006789 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006790
Chris Lattner02dd4b12009-12-05 05:40:13 +00006791 // Handle vector comparisons separately.
Nate Begemanbe2341d2008-07-14 18:02:46 +00006792 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006793 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006794
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006795 QualType lType = lex->getType();
6796 QualType rType = rex->getType();
Douglas Gregorfadb53b2011-03-12 01:48:56 +00006797
Chandler Carruth543cb652011-02-17 08:37:06 +00006798 Expr *LHSStripped = lex->IgnoreParenImpCasts();
6799 Expr *RHSStripped = rex->IgnoreParenImpCasts();
6800 QualType LHSStrippedType = LHSStripped->getType();
6801 QualType RHSStrippedType = RHSStripped->getType();
6802
Douglas Gregorfadb53b2011-03-12 01:48:56 +00006803
6804
Chandler Carruth543cb652011-02-17 08:37:06 +00006805 // Two different enums will raise a warning when compared.
6806 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
6807 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
6808 if (LHSEnumType->getDecl()->getIdentifier() &&
6809 RHSEnumType->getDecl()->getIdentifier() &&
6810 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
6811 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6812 << LHSStrippedType << RHSStrippedType
6813 << lex->getSourceRange() << rex->getSourceRange();
6814 }
6815 }
6816 }
6817
Douglas Gregor8eee1192010-06-22 22:12:46 +00006818 if (!lType->hasFloatingRepresentation() &&
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006819 !(lType->isBlockPointerType() && isRelational) &&
6820 !lex->getLocStart().isMacroID() &&
6821 !rex->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006822 // For non-floating point types, check for self-comparisons of the form
6823 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6824 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006825 //
6826 // NOTE: Don't warn about comparison expressions resulting from macro
6827 // expansion. Also don't warn about comparisons which are only self
6828 // comparisons within a template specialization. The warnings should catch
6829 // obvious cases in the definition of the template anyways. The idea is to
6830 // warn when the typed comparison operator will always evaluate to the same
6831 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006832 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006833 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006834 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006835 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00006836 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006837 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006838 << (Opc == BO_EQ
6839 || Opc == BO_LE
6840 || Opc == BO_GE));
Douglas Gregord64fdd02010-06-08 19:50:34 +00006841 } else if (lType->isArrayType() && rType->isArrayType() &&
6842 !DRL->getDecl()->getType()->isReferenceType() &&
6843 !DRR->getDecl()->getType()->isReferenceType()) {
6844 // what is it always going to eval to?
6845 char always_evals_to;
6846 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006847 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006848 always_evals_to = 0; // false
6849 break;
John McCall2de56d12010-08-25 11:45:40 +00006850 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006851 always_evals_to = 1; // true
6852 break;
6853 default:
6854 // best we can say is 'a constant'
6855 always_evals_to = 2; // e.g. array1 <= array2
6856 break;
6857 }
Ted Kremenek351ba912011-02-23 01:52:04 +00006858 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006859 << 1 // array
6860 << always_evals_to);
6861 }
6862 }
Chandler Carruth99919472010-07-10 12:30:03 +00006863 }
Mike Stump1eb44332009-09-09 15:08:12 +00006864
Chris Lattner55660a72009-03-08 19:39:53 +00006865 if (isa<CastExpr>(LHSStripped))
6866 LHSStripped = LHSStripped->IgnoreParenCasts();
6867 if (isa<CastExpr>(RHSStripped))
6868 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006869
Chris Lattner55660a72009-03-08 19:39:53 +00006870 // Warn about comparisons against a string constant (unless the other
6871 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00006872 Expr *literalString = 0;
6873 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00006874 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006875 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006876 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00006877 literalString = lex;
6878 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006879 } else if ((isa<StringLiteral>(RHSStripped) ||
6880 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006881 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006882 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00006883 literalString = rex;
6884 literalStringStripped = RHSStripped;
6885 }
6886
6887 if (literalString) {
6888 std::string resultComparison;
6889 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006890 case BO_LT: resultComparison = ") < 0"; break;
6891 case BO_GT: resultComparison = ") > 0"; break;
6892 case BO_LE: resultComparison = ") <= 0"; break;
6893 case BO_GE: resultComparison = ") >= 0"; break;
6894 case BO_EQ: resultComparison = ") == 0"; break;
6895 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregora86b8322009-04-06 18:45:53 +00006896 default: assert(false && "Invalid comparison operator");
6897 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006898
Ted Kremenek351ba912011-02-23 01:52:04 +00006899 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00006900 PDiag(diag::warn_stringcompare)
6901 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00006902 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00006903 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00006904 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006905
Douglas Gregord64fdd02010-06-08 19:50:34 +00006906 // C99 6.5.8p3 / C99 6.5.9p4
6907 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
6908 UsualArithmeticConversions(lex, rex);
6909 else {
6910 UsualUnaryConversions(lex);
6911 UsualUnaryConversions(rex);
6912 }
6913
6914 lType = lex->getType();
6915 rType = rex->getType();
6916
Douglas Gregor447b69e2008-11-19 03:25:36 +00006917 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00006918 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00006919
Chris Lattnera5937dd2007-08-26 01:18:55 +00006920 if (isRelational) {
6921 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006922 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006923 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00006924 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006925 if (lType->hasFloatingRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006926 CheckFloatComparison(Loc,lex,rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006927
Chris Lattnera5937dd2007-08-26 01:18:55 +00006928 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006929 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006930 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006931
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006932 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006933 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006934 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006935 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006936
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006937 // All of the following pointer-related warnings are GCC extensions, except
6938 // when handling null pointer constants.
Steve Naroff77878cc2007-08-27 04:08:11 +00006939 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00006940 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00006941 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00006942 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00006943 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006944
Douglas Gregor0c6db942009-05-04 06:07:12 +00006945 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00006946 if (LCanPointeeTy == RCanPointeeTy)
6947 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006948 if (!isRelational &&
6949 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6950 // Valid unless comparison between non-null pointer and function pointer
6951 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006952 // In a SFINAE context, we treat this as a hard error to maintain
6953 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006954 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6955 && !LHSIsNull && !RHSIsNull) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006956 Diag(Loc,
6957 isSFINAEContext()?
6958 diag::err_typecheck_comparison_of_fptr_to_void
6959 : diag::ext_typecheck_comparison_of_fptr_to_void)
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006960 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006961
6962 if (isSFINAEContext())
6963 return QualType();
6964
John McCall2de56d12010-08-25 11:45:40 +00006965 ImpCastExprToType(rex, lType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006966 return ResultTy;
6967 }
6968 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006969
Douglas Gregor0c6db942009-05-04 06:07:12 +00006970 // C++ [expr.rel]p2:
6971 // [...] Pointer conversions (4.10) and qualification
6972 // conversions (4.4) are performed on pointer operands (or on
6973 // a pointer operand and a null pointer constant) to bring
6974 // them to their composite pointer type. [...]
6975 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00006976 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00006977 // comparisons of pointers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006978 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00006979 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006980 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor0c6db942009-05-04 06:07:12 +00006981 if (T.isNull()) {
6982 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6983 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6984 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006985 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006986 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006987 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006988 << lType << rType << T
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006989 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00006990 }
6991
John McCall2de56d12010-08-25 11:45:40 +00006992 ImpCastExprToType(lex, T, CK_BitCast);
6993 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00006994 return ResultTy;
6995 }
Eli Friedman3075e762009-08-23 00:27:47 +00006996 // C99 6.5.9p2 and C99 6.5.8p2
6997 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6998 RCanPointeeTy.getUnqualifiedType())) {
6999 // Valid unless a relational comparison of function pointers
7000 if (isRelational && LCanPointeeTy->isFunctionType()) {
7001 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7002 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
7003 }
7004 } else if (!isRelational &&
7005 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7006 // Valid unless comparison between non-null pointer and function pointer
7007 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7008 && !LHSIsNull && !RHSIsNull) {
7009 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
7010 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
7011 }
7012 } else {
7013 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007014 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00007015 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007016 }
John McCall34d6f932011-03-11 04:25:25 +00007017 if (LCanPointeeTy != RCanPointeeTy) {
7018 if (LHSIsNull && !RHSIsNull)
7019 ImpCastExprToType(lex, rType, CK_BitCast);
7020 else
7021 ImpCastExprToType(rex, lType, CK_BitCast);
7022 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00007023 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00007024 }
Mike Stump1eb44332009-09-09 15:08:12 +00007025
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007026 if (getLangOptions().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007027 // Comparison of nullptr_t with itself.
7028 if (lType->isNullPtrType() && rType->isNullPtrType())
7029 return ResultTy;
7030
Mike Stump1eb44332009-09-09 15:08:12 +00007031 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00007032 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00007033 if (RHSIsNull &&
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007034 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregor20b3e992009-08-24 17:42:35 +00007035 (!isRelational && lType->isMemberPointerType()))) {
Douglas Gregor443c2122010-08-07 13:36:37 +00007036 ImpCastExprToType(rex, lType,
7037 lType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007038 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007039 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007040 return ResultTy;
7041 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007042 if (LHSIsNull &&
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007043 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregor20b3e992009-08-24 17:42:35 +00007044 (!isRelational && rType->isMemberPointerType()))) {
Douglas Gregor443c2122010-08-07 13:36:37 +00007045 ImpCastExprToType(lex, rType,
7046 rType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007047 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007048 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007049 return ResultTy;
7050 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007051
7052 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00007053 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00007054 lType->isMemberPointerType() && rType->isMemberPointerType()) {
7055 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00007056 // In addition, pointers to members can be compared, or a pointer to
7057 // member and a null pointer constant. Pointer to member conversions
7058 // (4.11) and qualification conversions (4.4) are performed to bring
7059 // them to a common type. If one operand is a null pointer constant,
7060 // the common type is the type of the other operand. Otherwise, the
7061 // common type is a pointer to member type similar (4.4) to the type
7062 // of one of the operands, with a cv-qualification signature (4.4)
7063 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00007064 // types.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007065 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00007066 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007067 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor20b3e992009-08-24 17:42:35 +00007068 if (T.isNull()) {
7069 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007070 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00007071 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007072 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007073 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007074 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007075 << lType << rType << T
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007076 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00007077 }
Mike Stump1eb44332009-09-09 15:08:12 +00007078
John McCall2de56d12010-08-25 11:45:40 +00007079 ImpCastExprToType(lex, T, CK_BitCast);
7080 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00007081 return ResultTy;
7082 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007083
7084 // Handle scoped enumeration types specifically, since they don't promote
7085 // to integers.
7086 if (lex->getType()->isEnumeralType() &&
7087 Context.hasSameUnqualifiedType(lex->getType(), rex->getType()))
7088 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007089 }
Mike Stump1eb44332009-09-09 15:08:12 +00007090
Steve Naroff1c7d0672008-09-04 15:10:53 +00007091 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00007092 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00007093 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
7094 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007095
Steve Naroff1c7d0672008-09-04 15:10:53 +00007096 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00007097 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007098 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00007099 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00007100 }
John McCall2de56d12010-08-25 11:45:40 +00007101 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007102 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007103 }
Steve Naroff59f53942008-09-28 01:11:11 +00007104 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00007105 if (!isRelational
7106 && ((lType->isBlockPointerType() && rType->isPointerType())
7107 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00007108 if (!LHSIsNull && !RHSIsNull) {
John McCall34d6f932011-03-11 04:25:25 +00007109 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007110 ->getPointeeType()->isVoidType())
John McCall34d6f932011-03-11 04:25:25 +00007111 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007112 ->getPointeeType()->isVoidType())))
7113 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7114 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00007115 }
John McCall34d6f932011-03-11 04:25:25 +00007116 if (LHSIsNull && !RHSIsNull)
7117 ImpCastExprToType(lex, rType, CK_BitCast);
7118 else
7119 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007120 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00007121 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00007122
John McCall34d6f932011-03-11 04:25:25 +00007123 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
7124 const PointerType *LPT = lType->getAs<PointerType>();
7125 const PointerType *RPT = rType->getAs<PointerType>();
7126 if (LPT || RPT) {
7127 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7128 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007129
Steve Naroffa8069f12008-11-17 19:49:16 +00007130 if (!LPtrToVoid && !RPtrToVoid &&
7131 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007132 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00007133 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00007134 }
John McCall34d6f932011-03-11 04:25:25 +00007135 if (LHSIsNull && !RHSIsNull)
7136 ImpCastExprToType(lex, rType, CK_BitCast);
7137 else
7138 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007139 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00007140 }
Steve Naroff14108da2009-07-10 23:34:53 +00007141 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007142 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00007143 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
7144 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
John McCall34d6f932011-03-11 04:25:25 +00007145 if (LHSIsNull && !RHSIsNull)
7146 ImpCastExprToType(lex, rType, CK_BitCast);
7147 else
7148 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007149 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00007150 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00007151 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007152 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7153 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007154 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007155 bool isError = false;
7156 if ((LHSIsNull && lType->isIntegerType()) ||
7157 (RHSIsNull && rType->isIntegerType())) {
7158 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007159 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007160 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007161 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007162 else if (getLangOptions().CPlusPlus) {
7163 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7164 isError = true;
7165 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007166 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00007167
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007168 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007169 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00007170 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007171 if (isError)
7172 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00007173 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007174
7175 if (lType->isIntegerType())
John McCall404cd162010-11-13 01:35:44 +00007176 ImpCastExprToType(lex, rType,
7177 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007178 else
John McCall404cd162010-11-13 01:35:44 +00007179 ImpCastExprToType(rex, lType,
7180 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007181 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007182 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007183
Steve Naroff39218df2008-09-04 16:56:14 +00007184 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00007185 if (!isRelational && RHSIsNull
7186 && lType->isBlockPointerType() && rType->isIntegerType()) {
John McCall404cd162010-11-13 01:35:44 +00007187 ImpCastExprToType(rex, lType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007188 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007189 }
Mike Stumpaf199f32009-05-07 18:43:07 +00007190 if (!isRelational && LHSIsNull
7191 && lType->isIntegerType() && rType->isBlockPointerType()) {
John McCall404cd162010-11-13 01:35:44 +00007192 ImpCastExprToType(lex, rType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007193 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007194 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007195
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007196 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007197}
7198
Nate Begemanbe2341d2008-07-14 18:02:46 +00007199/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00007200/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007201/// like a scalar comparison, a vector comparison produces a vector of integer
7202/// types.
7203QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007204 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007205 bool isRelational) {
7206 // Check to make sure we're operating on vectors of the same type and width,
7207 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007208 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007209 if (vType.isNull())
7210 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007211
Anton Yartsevaa4fe052010-11-18 03:19:30 +00007212 // If AltiVec, the comparison results in a numeric type, i.e.
7213 // bool for C++, int for C
7214 if (getLangOptions().AltiVec)
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00007215 return Context.getLogicalOperationType();
Anton Yartsevaa4fe052010-11-18 03:19:30 +00007216
Nate Begemanbe2341d2008-07-14 18:02:46 +00007217 QualType lType = lex->getType();
7218 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007219
Nate Begemanbe2341d2008-07-14 18:02:46 +00007220 // For non-floating point types, check for self-comparisons of the form
7221 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7222 // often indicate logic errors in the program.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007223 if (!lType->hasFloatingRepresentation()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00007224 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
7225 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
7226 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00007227 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00007228 PDiag(diag::warn_comparison_always)
7229 << 0 // self-
7230 << 2 // "a constant"
7231 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00007232 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007233
Nate Begemanbe2341d2008-07-14 18:02:46 +00007234 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007235 if (!isRelational && lType->hasFloatingRepresentation()) {
7236 assert (rType->hasFloatingRepresentation());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007237 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007238 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007239
Nate Begemanbe2341d2008-07-14 18:02:46 +00007240 // Return the type for the comparison, which is the same as vector type for
7241 // integer vectors, or an integer type of identical size and number of
7242 // elements for floating point vectors.
Douglas Gregorf6094622010-07-23 15:58:24 +00007243 if (lType->hasIntegerRepresentation())
Nate Begemanbe2341d2008-07-14 18:02:46 +00007244 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007245
John McCall183700f2009-09-21 23:43:11 +00007246 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00007247 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00007248 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007249 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00007250 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00007251 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7252
Mike Stumpeed9cac2009-02-19 03:04:26 +00007253 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00007254 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00007255 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7256}
7257
Reid Spencer5f016e22007-07-11 17:01:13 +00007258inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00007259 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Douglas Gregorf6094622010-07-23 15:58:24 +00007260 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
7261 if (lex->getType()->hasIntegerRepresentation() &&
7262 rex->getType()->hasIntegerRepresentation())
7263 return CheckVectorOperands(Loc, lex, rex);
7264
7265 return InvalidOperands(Loc, lex, rex);
7266 }
Steve Naroff90045e82007-07-13 23:32:42 +00007267
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007268 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007269
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007270 if (lex->getType()->isIntegralOrUnscopedEnumerationType() &&
7271 rex->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007272 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007273 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007274}
7275
7276inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner90a8f272010-07-13 19:41:32 +00007277 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
7278
7279 // Diagnose cases where the user write a logical and/or but probably meant a
7280 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7281 // is a constant.
7282 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
Eli Friedman787b0942010-07-27 19:14:53 +00007283 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
Chris Lattner23ef3e42010-07-15 00:26:43 +00007284 // Don't warn in macros.
Chris Lattnerb7690b42010-07-24 01:10:11 +00007285 !Loc.isMacroID()) {
7286 // If the RHS can be constant folded, and if it constant folds to something
7287 // that isn't 0 or 1 (which indicate a potential logical operation that
7288 // happened to fold to true/false) then warn.
7289 Expr::EvalResult Result;
7290 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
7291 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
7292 Diag(Loc, diag::warn_logical_instead_of_bitwise)
7293 << rex->getSourceRange()
John McCall2de56d12010-08-25 11:45:40 +00007294 << (Opc == BO_LAnd ? "&&" : "||")
7295 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattnerb7690b42010-07-24 01:10:11 +00007296 }
7297 }
Chris Lattner90a8f272010-07-13 19:41:32 +00007298
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007299 if (!Context.getLangOptions().CPlusPlus) {
7300 UsualUnaryConversions(lex);
7301 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007302
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007303 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
7304 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007305
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007306 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00007307 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007308
John McCall75f7c0f2010-06-04 00:29:51 +00007309 // The following is safe because we only use this method for
7310 // non-overloadable operands.
7311
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007312 // C++ [expr.log.and]p1
7313 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007314 // The operands are both contextually converted to type bool.
7315 if (PerformContextuallyConvertToBool(lex) ||
7316 PerformContextuallyConvertToBool(rex))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007317 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007318
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007319 // C++ [expr.log.and]p2
7320 // C++ [expr.log.or]p2
7321 // The result is a bool.
7322 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007323}
7324
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007325/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7326/// is a read-only property; return true if so. A readonly property expression
7327/// depends on various declarations and thus must be treated specially.
7328///
Mike Stump1eb44332009-09-09 15:08:12 +00007329static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007330 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7331 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCall12f78a62010-12-02 01:19:52 +00007332 if (PropExpr->isImplicitProperty()) return false;
7333
7334 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7335 QualType BaseType = PropExpr->isSuperReceiver() ?
7336 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007337 PropExpr->getBase()->getType();
7338
John McCall12f78a62010-12-02 01:19:52 +00007339 if (const ObjCObjectPointerType *OPT =
7340 BaseType->getAsObjCInterfacePointerType())
7341 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7342 if (S.isPropertyReadonly(PDecl, IFace))
7343 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007344 }
7345 return false;
7346}
7347
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007348/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7349/// emit an error and return true. If so, return false.
7350static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007351 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007352 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007353 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007354 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7355 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007356 if (IsLV == Expr::MLV_Valid)
7357 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007358
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007359 unsigned Diag = 0;
7360 bool NeedType = false;
7361 switch (IsLV) { // C99 6.5.16p2
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007362 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007363 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007364 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7365 NeedType = true;
7366 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007367 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007368 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7369 NeedType = true;
7370 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007371 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007372 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7373 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007374 case Expr::MLV_Valid:
7375 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007376 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007377 case Expr::MLV_MemberFunction:
7378 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007379 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7380 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007381 case Expr::MLV_IncompleteType:
7382 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007383 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007384 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00007385 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00007386 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007387 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7388 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00007389 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007390 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7391 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007392 case Expr::MLV_ReadonlyProperty:
7393 Diag = diag::error_readonly_property_assignment;
7394 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007395 case Expr::MLV_NoSetterProperty:
7396 Diag = diag::error_nosetter_property_assignment;
7397 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007398 case Expr::MLV_SubObjCPropertySetting:
7399 Diag = diag::error_no_subobject_property_setting;
7400 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007401 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007402
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007403 SourceRange Assign;
7404 if (Loc != OrigLoc)
7405 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007406 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007407 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007408 else
Mike Stump1eb44332009-09-09 15:08:12 +00007409 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007410 return true;
7411}
7412
7413
7414
7415// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007416QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
7417 SourceLocation Loc,
7418 QualType CompoundType) {
7419 // Verify that LHS is a modifiable lvalue, and emit error if not.
7420 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007421 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007422
7423 QualType LHSType = LHS->getType();
7424 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007425 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007426 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007427 QualType LHSTy(LHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007428 // Simple assignment "x = y".
John McCallf6a16482010-12-04 03:47:34 +00007429 if (LHS->getObjectKind() == OK_ObjCProperty)
7430 ConvertPropertyForLValue(LHS, RHS, LHSTy);
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007431 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007432 // Special case of NSObject attributes on c-style pointer types.
7433 if (ConvTy == IncompatiblePointer &&
7434 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007435 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007436 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007437 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007438 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007439
John McCallf89e55a2010-11-18 06:31:45 +00007440 if (ConvTy == Compatible &&
7441 getLangOptions().ObjCNonFragileABI &&
7442 LHSType->isObjCObjectType())
7443 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7444 << LHSType;
7445
Chris Lattner2c156472008-08-21 18:04:13 +00007446 // If the RHS is a unary plus or minus, check to see if they = and + are
7447 // right next to each other. If so, the user may have typo'd "x =+ 4"
7448 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007449 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00007450 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7451 RHSCheck = ICE->getSubExpr();
7452 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007453 if ((UO->getOpcode() == UO_Plus ||
7454 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007455 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007456 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00007457 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7458 // And there is a space or other character before the subexpr of the
7459 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00007460 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7461 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007462 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007463 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007464 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007465 }
Chris Lattner2c156472008-08-21 18:04:13 +00007466 }
7467 } else {
7468 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007469 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007470 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007471
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007472 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor68647482009-12-16 03:45:30 +00007473 RHS, AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007474 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007475
Chris Lattner8b5dec32010-07-07 06:14:23 +00007476
7477 // Check to see if the destination operand is a dereferenced null pointer. If
7478 // so, and if not volatile-qualified, this is undefined behavior that the
7479 // optimizer will delete, so warn about it. People sometimes try to use this
7480 // to get a deterministic trap and are surprised by clang's behavior. This
7481 // only handles the pattern "*null = whatever", which is a very syntactic
7482 // check.
7483 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
John McCall2de56d12010-08-25 11:45:40 +00007484 if (UO->getOpcode() == UO_Deref &&
Chris Lattner8b5dec32010-07-07 06:14:23 +00007485 UO->getSubExpr()->IgnoreParenCasts()->
7486 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
7487 !UO->getType().isVolatileQualified()) {
Ted Kremenek351ba912011-02-23 01:52:04 +00007488 DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7489 PDiag(diag::warn_indirection_through_null)
7490 << UO->getSubExpr()->getSourceRange());
7491 DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7492 PDiag(diag::note_indirection_through_null));
Chris Lattner8b5dec32010-07-07 06:14:23 +00007493 }
7494
Ted Kremeneka0125d82011-02-16 01:57:07 +00007495 // Check for trivial buffer overflows.
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007496 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremeneka0125d82011-02-16 01:57:07 +00007497
Reid Spencer5f016e22007-07-11 17:01:13 +00007498 // C99 6.5.16p3: The type of an assignment expression is the type of the
7499 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007500 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007501 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7502 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007503 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007504 // operand.
John McCall2bf6f492010-10-12 02:19:57 +00007505 return (getLangOptions().CPlusPlus
7506 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007507}
7508
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007509// C99 6.5.17
John McCallf6a16482010-12-04 03:47:34 +00007510static QualType CheckCommaOperands(Sema &S, Expr *&LHS, Expr *&RHS,
John McCall09431682010-11-18 19:01:18 +00007511 SourceLocation Loc) {
7512 S.DiagnoseUnusedExprResult(LHS);
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00007513
John McCall09431682010-11-18 19:01:18 +00007514 ExprResult LHSResult = S.CheckPlaceholderExpr(LHS, Loc);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007515 if (LHSResult.isInvalid())
7516 return QualType();
7517
John McCall09431682010-11-18 19:01:18 +00007518 ExprResult RHSResult = S.CheckPlaceholderExpr(RHS, Loc);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007519 if (RHSResult.isInvalid())
7520 return QualType();
7521 RHS = RHSResult.take();
7522
John McCallcf2e5062010-10-12 07:14:40 +00007523 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7524 // operands, but not unary promotions.
7525 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007526
John McCallf6a16482010-12-04 03:47:34 +00007527 // So we treat the LHS as a ignored value, and in C++ we allow the
7528 // containing site to determine what should be done with the RHS.
7529 S.IgnoredValueConversions(LHS);
7530
7531 if (!S.getLangOptions().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007532 S.DefaultFunctionArrayLvalueConversion(RHS);
John McCallcf2e5062010-10-12 07:14:40 +00007533 if (!RHS->getType()->isVoidType())
John McCall09431682010-11-18 19:01:18 +00007534 S.RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007535 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007536
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007537 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007538}
7539
Steve Naroff49b45262007-07-13 16:58:59 +00007540/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7541/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007542static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7543 ExprValueKind &VK,
7544 SourceLocation OpLoc,
7545 bool isInc, bool isPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007546 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007547 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007548
Chris Lattner3528d352008-11-21 07:05:48 +00007549 QualType ResType = Op->getType();
7550 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007551
John McCall09431682010-11-18 19:01:18 +00007552 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007553 // Decrement of bool is not allowed.
7554 if (!isInc) {
John McCall09431682010-11-18 19:01:18 +00007555 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007556 return QualType();
7557 }
7558 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007559 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007560 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007561 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00007562 } else if (ResType->isAnyPointerType()) {
7563 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00007564
Chris Lattner3528d352008-11-21 07:05:48 +00007565 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00007566 if (PointeeTy->isVoidType()) {
John McCall09431682010-11-18 19:01:18 +00007567 if (S.getLangOptions().CPlusPlus) {
7568 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00007569 << Op->getSourceRange();
7570 return QualType();
7571 }
7572
7573 // Pointer to void is a GNU extension in C.
John McCall09431682010-11-18 19:01:18 +00007574 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00007575 } else if (PointeeTy->isFunctionType()) {
John McCall09431682010-11-18 19:01:18 +00007576 if (S.getLangOptions().CPlusPlus) {
7577 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00007578 << Op->getType() << Op->getSourceRange();
7579 return QualType();
7580 }
7581
John McCall09431682010-11-18 19:01:18 +00007582 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00007583 << ResType << Op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007584 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
7585 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00007586 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00007587 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007588 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007589 // Diagnose bad cases where we step over interface counts.
John McCall09431682010-11-18 19:01:18 +00007590 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7591 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007592 << PointeeTy << Op->getSourceRange();
7593 return QualType();
7594 }
Eli Friedman5b088a12010-01-03 00:20:48 +00007595 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007596 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007597 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007598 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007599 } else if (ResType->isPlaceholderType()) {
John McCall09431682010-11-18 19:01:18 +00007600 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007601 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007602 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7603 isInc, isPrefix);
Anton Yartsev683564a2011-02-07 02:17:30 +00007604 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7605 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007606 } else {
John McCall09431682010-11-18 19:01:18 +00007607 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00007608 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007609 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007610 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007611 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007612 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007613 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007614 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007615 // In C++, a prefix increment is the same type as the operand. Otherwise
7616 // (in C or with postfix), the increment is the unqualified type of the
7617 // operand.
John McCall09431682010-11-18 19:01:18 +00007618 if (isPrefix && S.getLangOptions().CPlusPlus) {
7619 VK = VK_LValue;
7620 return ResType;
7621 } else {
7622 VK = VK_RValue;
7623 return ResType.getUnqualifiedType();
7624 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007625}
7626
John McCallf6a16482010-12-04 03:47:34 +00007627void Sema::ConvertPropertyForRValue(Expr *&E) {
7628 assert(E->getValueKind() == VK_LValue &&
7629 E->getObjectKind() == OK_ObjCProperty);
7630 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7631
7632 ExprValueKind VK = VK_RValue;
7633 if (PRE->isImplicitProperty()) {
Fariborz Jahanian99130e52010-12-22 19:46:35 +00007634 if (const ObjCMethodDecl *GetterMethod =
7635 PRE->getImplicitPropertyGetter()) {
7636 QualType Result = GetterMethod->getResultType();
7637 VK = Expr::getValueKindForType(Result);
7638 }
7639 else {
7640 Diag(PRE->getLocation(), diag::err_getter_not_found)
7641 << PRE->getBase()->getType();
7642 }
John McCallf6a16482010-12-04 03:47:34 +00007643 }
7644
7645 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
7646 E, 0, VK);
John McCalldb67e2f2010-12-10 01:49:45 +00007647
7648 ExprResult Result = MaybeBindToTemporary(E);
7649 if (!Result.isInvalid())
7650 E = Result.take();
John McCallf6a16482010-12-04 03:47:34 +00007651}
7652
7653void Sema::ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType &LHSTy) {
7654 assert(LHS->getValueKind() == VK_LValue &&
7655 LHS->getObjectKind() == OK_ObjCProperty);
7656 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7657
7658 if (PRE->isImplicitProperty()) {
7659 // If using property-dot syntax notation for assignment, and there is a
7660 // setter, RHS expression is being passed to the setter argument. So,
7661 // type conversion (and comparison) is RHS to setter's argument type.
7662 if (const ObjCMethodDecl *SetterMD = PRE->getImplicitPropertySetter()) {
7663 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7664 LHSTy = (*P)->getType();
7665
7666 // Otherwise, if the getter returns an l-value, just call that.
7667 } else {
7668 QualType Result = PRE->getImplicitPropertyGetter()->getResultType();
7669 ExprValueKind VK = Expr::getValueKindForType(Result);
7670 if (VK == VK_LValue) {
7671 LHS = ImplicitCastExpr::Create(Context, LHS->getType(),
7672 CK_GetObjCProperty, LHS, 0, VK);
7673 return;
John McCall12f78a62010-12-02 01:19:52 +00007674 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007675 }
John McCallf6a16482010-12-04 03:47:34 +00007676 }
7677
7678 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007679 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007680 InitializedEntity::InitializeParameter(Context, LHSTy);
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007681 Expr *Arg = RHS;
7682 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(),
7683 Owned(Arg));
7684 if (!ArgE.isInvalid())
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007685 RHS = ArgE.takeAs<Expr>();
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007686 }
7687}
7688
7689
Anders Carlsson369dee42008-02-01 07:15:58 +00007690/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007691/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007692/// where the declaration is needed for type checking. We only need to
7693/// handle cases when the expression references a function designator
7694/// or is an lvalue. Here are some examples:
7695/// - &(x) => x
7696/// - &*****f => f for f a function designator.
7697/// - &s.xx => s
7698/// - &s.zz[1].yy -> s, if zz is an array
7699/// - *(x + 1) -> x, if x is an array
7700/// - &"123"[2] -> 0
7701/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007702static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007703 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007704 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007705 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007706 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007707 // If this is an arrow operator, the address is an offset from
7708 // the base's value, so the object the base refers to is
7709 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007710 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007711 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007712 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007713 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007714 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007715 // FIXME: This code shouldn't be necessary! We should catch the implicit
7716 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007717 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7718 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7719 if (ICE->getSubExpr()->getType()->isArrayType())
7720 return getPrimaryDecl(ICE->getSubExpr());
7721 }
7722 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007723 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007724 case Stmt::UnaryOperatorClass: {
7725 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007726
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007727 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007728 case UO_Real:
7729 case UO_Imag:
7730 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007731 return getPrimaryDecl(UO->getSubExpr());
7732 default:
7733 return 0;
7734 }
7735 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007736 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007737 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007738 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007739 // If the result of an implicit cast is an l-value, we care about
7740 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007741 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007742 default:
7743 return 0;
7744 }
7745}
7746
7747/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007748/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007749/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007750/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007751/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007752/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007753/// we allow the '&' but retain the overloaded-function type.
John McCall09431682010-11-18 19:01:18 +00007754static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7755 SourceLocation OpLoc) {
John McCall9c72c602010-08-27 09:08:28 +00007756 if (OrigOp->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007757 return S.Context.DependentTy;
7758 if (OrigOp->getType() == S.Context.OverloadTy)
7759 return S.Context.OverloadTy;
John McCall9c72c602010-08-27 09:08:28 +00007760
John McCall09431682010-11-18 19:01:18 +00007761 ExprResult PR = S.CheckPlaceholderExpr(OrigOp, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007762 if (PR.isInvalid()) return QualType();
7763 OrigOp = PR.take();
7764
John McCall9c72c602010-08-27 09:08:28 +00007765 // Make sure to ignore parentheses in subsequent checks
7766 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00007767
John McCall09431682010-11-18 19:01:18 +00007768 if (S.getLangOptions().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00007769 // Implement C99-only parts of addressof rules.
7770 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00007771 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00007772 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7773 // (assuming the deref expression is valid).
7774 return uOp->getSubExpr()->getType();
7775 }
7776 // Technically, there should be a check for array subscript
7777 // expressions here, but the result of one is always an lvalue anyway.
7778 }
John McCall5808ce42011-02-03 08:15:49 +00007779 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00007780 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00007781
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007782 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00007783 bool sfinae = S.isSFINAEContext();
7784 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7785 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00007786 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007787 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00007788 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00007789 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007790 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00007791 } else if (lval == Expr::LV_MemberFunction) {
7792 // If it's an instance method, make a member pointer.
7793 // The expression must have exactly the form &A::foo.
7794
7795 // If the underlying expression isn't a decl ref, give up.
7796 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007797 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007798 << OrigOp->getSourceRange();
7799 return QualType();
7800 }
7801 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7802 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7803
7804 // The id-expression was parenthesized.
7805 if (OrigOp != DRE) {
John McCall09431682010-11-18 19:01:18 +00007806 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007807 << OrigOp->getSourceRange();
7808
7809 // The method was named without a qualifier.
7810 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00007811 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007812 << op->getSourceRange();
7813 }
7814
John McCall09431682010-11-18 19:01:18 +00007815 return S.Context.getMemberPointerType(op->getType(),
7816 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00007817 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00007818 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007819 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00007820 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00007821 // FIXME: emit more specific diag...
John McCall09431682010-11-18 19:01:18 +00007822 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00007823 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007824 return QualType();
7825 }
John McCall7eb0a9e2010-11-24 05:12:34 +00007826 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007827 // The operand cannot be a bit-field
John McCall09431682010-11-18 19:01:18 +00007828 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman23d58ce2009-04-20 08:23:18 +00007829 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00007830 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00007831 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00007832 // The operand cannot be an element of a vector
John McCall09431682010-11-18 19:01:18 +00007833 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00007834 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00007835 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00007836 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007837 // cannot take address of a property expression.
John McCall09431682010-11-18 19:01:18 +00007838 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007839 << "property expression" << op->getSourceRange();
7840 return QualType();
Steve Naroffbcb2b612008-02-29 23:30:25 +00007841 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00007842 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00007843 // with the register storage-class specifier.
7844 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00007845 // in C++ it is not error to take address of a register
7846 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00007847 if (vd->getStorageClass() == SC_Register &&
John McCall09431682010-11-18 19:01:18 +00007848 !S.getLangOptions().CPlusPlus) {
7849 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007850 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007851 return QualType();
7852 }
John McCallba135432009-11-21 08:51:07 +00007853 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00007854 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00007855 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00007856 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00007857 // Could be a pointer to member, though, if there is an explicit
7858 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00007859 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00007860 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007861 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00007862 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00007863 S.Diag(OpLoc,
7864 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00007865 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007866 return QualType();
7867 }
Mike Stump1eb44332009-09-09 15:08:12 +00007868
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00007869 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7870 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00007871 return S.Context.getMemberPointerType(op->getType(),
7872 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007873 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00007874 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00007875 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00007876 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00007877 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00007878
Eli Friedman441cf102009-05-16 23:27:50 +00007879 if (lval == Expr::LV_IncompleteVoidType) {
7880 // Taking the address of a void variable is technically illegal, but we
7881 // allow it in cases which are otherwise valid.
7882 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00007883 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00007884 }
7885
Reid Spencer5f016e22007-07-11 17:01:13 +00007886 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00007887 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00007888 return S.Context.getObjCObjectPointerType(op->getType());
7889 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007890}
7891
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007892/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00007893static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7894 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00007895 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007896 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007897
John McCall09431682010-11-18 19:01:18 +00007898 S.UsualUnaryConversions(Op);
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007899 QualType OpTy = Op->getType();
7900 QualType Result;
7901
7902 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7903 // is an incomplete type or void. It would be possible to warn about
7904 // dereferencing a void pointer, but it's completely well-defined, and such a
7905 // warning is unlikely to catch any mistakes.
7906 if (const PointerType *PT = OpTy->getAs<PointerType>())
7907 Result = PT->getPointeeType();
7908 else if (const ObjCObjectPointerType *OPT =
7909 OpTy->getAs<ObjCObjectPointerType>())
7910 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00007911 else {
John McCall09431682010-11-18 19:01:18 +00007912 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007913 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007914 if (PR.take() != Op)
7915 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007916 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007917
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007918 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00007919 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007920 << OpTy << Op->getSourceRange();
7921 return QualType();
7922 }
John McCall09431682010-11-18 19:01:18 +00007923
7924 // Dereferences are usually l-values...
7925 VK = VK_LValue;
7926
7927 // ...except that certain expressions are never l-values in C.
7928 if (!S.getLangOptions().CPlusPlus &&
7929 IsCForbiddenLValueType(S.Context, Result))
7930 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007931
7932 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00007933}
7934
John McCall2de56d12010-08-25 11:45:40 +00007935static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007936 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007937 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007938 switch (Kind) {
7939 default: assert(0 && "Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00007940 case tok::periodstar: Opc = BO_PtrMemD; break;
7941 case tok::arrowstar: Opc = BO_PtrMemI; break;
7942 case tok::star: Opc = BO_Mul; break;
7943 case tok::slash: Opc = BO_Div; break;
7944 case tok::percent: Opc = BO_Rem; break;
7945 case tok::plus: Opc = BO_Add; break;
7946 case tok::minus: Opc = BO_Sub; break;
7947 case tok::lessless: Opc = BO_Shl; break;
7948 case tok::greatergreater: Opc = BO_Shr; break;
7949 case tok::lessequal: Opc = BO_LE; break;
7950 case tok::less: Opc = BO_LT; break;
7951 case tok::greaterequal: Opc = BO_GE; break;
7952 case tok::greater: Opc = BO_GT; break;
7953 case tok::exclaimequal: Opc = BO_NE; break;
7954 case tok::equalequal: Opc = BO_EQ; break;
7955 case tok::amp: Opc = BO_And; break;
7956 case tok::caret: Opc = BO_Xor; break;
7957 case tok::pipe: Opc = BO_Or; break;
7958 case tok::ampamp: Opc = BO_LAnd; break;
7959 case tok::pipepipe: Opc = BO_LOr; break;
7960 case tok::equal: Opc = BO_Assign; break;
7961 case tok::starequal: Opc = BO_MulAssign; break;
7962 case tok::slashequal: Opc = BO_DivAssign; break;
7963 case tok::percentequal: Opc = BO_RemAssign; break;
7964 case tok::plusequal: Opc = BO_AddAssign; break;
7965 case tok::minusequal: Opc = BO_SubAssign; break;
7966 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7967 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7968 case tok::ampequal: Opc = BO_AndAssign; break;
7969 case tok::caretequal: Opc = BO_XorAssign; break;
7970 case tok::pipeequal: Opc = BO_OrAssign; break;
7971 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007972 }
7973 return Opc;
7974}
7975
John McCall2de56d12010-08-25 11:45:40 +00007976static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007977 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007978 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007979 switch (Kind) {
7980 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00007981 case tok::plusplus: Opc = UO_PreInc; break;
7982 case tok::minusminus: Opc = UO_PreDec; break;
7983 case tok::amp: Opc = UO_AddrOf; break;
7984 case tok::star: Opc = UO_Deref; break;
7985 case tok::plus: Opc = UO_Plus; break;
7986 case tok::minus: Opc = UO_Minus; break;
7987 case tok::tilde: Opc = UO_Not; break;
7988 case tok::exclaim: Opc = UO_LNot; break;
7989 case tok::kw___real: Opc = UO_Real; break;
7990 case tok::kw___imag: Opc = UO_Imag; break;
7991 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007992 }
7993 return Opc;
7994}
7995
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007996/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7997/// This warning is only emitted for builtin assignment operations. It is also
7998/// suppressed in the event of macro expansions.
7999static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
8000 SourceLocation OpLoc) {
8001 if (!S.ActiveTemplateInstantiations.empty())
8002 return;
8003 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8004 return;
8005 lhs = lhs->IgnoreParenImpCasts();
8006 rhs = rhs->IgnoreParenImpCasts();
8007 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
8008 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
8009 if (!LeftDeclRef || !RightDeclRef ||
8010 LeftDeclRef->getLocation().isMacroID() ||
8011 RightDeclRef->getLocation().isMacroID())
8012 return;
8013 const ValueDecl *LeftDecl =
8014 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
8015 const ValueDecl *RightDecl =
8016 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
8017 if (LeftDecl != RightDecl)
8018 return;
8019 if (LeftDecl->getType().isVolatileQualified())
8020 return;
8021 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
8022 if (RefTy->getPointeeType().isVolatileQualified())
8023 return;
8024
8025 S.Diag(OpLoc, diag::warn_self_assignment)
8026 << LeftDeclRef->getType()
8027 << lhs->getSourceRange() << rhs->getSourceRange();
8028}
8029
Douglas Gregoreaebc752008-11-06 23:29:22 +00008030/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8031/// operator @p Opc at location @c TokLoc. This routine only supports
8032/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00008033ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008034 BinaryOperatorKind Opc,
John McCall2de56d12010-08-25 11:45:40 +00008035 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00008036 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00008037 // The following two variables are used for compound assignment operators
8038 QualType CompLHSTy; // Type of LHS after promotions for computation
8039 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00008040 ExprValueKind VK = VK_RValue;
8041 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00008042
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008043 // Check if a 'foo<int>' involved in a binary op, identifies a single
8044 // function unambiguously (i.e. an lvalue ala 13.4)
8045 // But since an assignment can trigger target based overload, exclude it in
8046 // our blind search. i.e:
8047 // template<class T> void f(); template<class T, class U> void f(U);
8048 // f<int> == 0; // resolve f<int> blindly
8049 // void (*p)(int); p = f<int>; // resolve f<int> using target
8050 if (Opc != BO_Assign) {
8051 if (lhs->getType() == Context.OverloadTy) {
8052 ExprResult resolvedLHS =
8053 ResolveAndFixSingleFunctionTemplateSpecialization(lhs);
8054 if (resolvedLHS.isUsable()) lhs = resolvedLHS.release();
8055 }
8056 if (rhs->getType() == Context.OverloadTy) {
8057 ExprResult resolvedRHS =
8058 ResolveAndFixSingleFunctionTemplateSpecialization(rhs);
8059 if (resolvedRHS.isUsable()) rhs = resolvedRHS.release();
8060 }
8061 }
8062
Douglas Gregoreaebc752008-11-06 23:29:22 +00008063 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008064 case BO_Assign:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008065 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
John McCallf6a16482010-12-04 03:47:34 +00008066 if (getLangOptions().CPlusPlus &&
8067 lhs->getObjectKind() != OK_ObjCProperty) {
John McCall09431682010-11-18 19:01:18 +00008068 VK = lhs->getValueKind();
8069 OK = lhs->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008070 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008071 if (!ResultTy.isNull())
8072 DiagnoseSelfAssignment(*this, lhs, rhs, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008073 break;
John McCall2de56d12010-08-25 11:45:40 +00008074 case BO_PtrMemD:
8075 case BO_PtrMemI:
John McCallf89e55a2010-11-18 06:31:45 +00008076 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008077 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00008078 break;
John McCall2de56d12010-08-25 11:45:40 +00008079 case BO_Mul:
8080 case BO_Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00008081 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00008082 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008083 break;
John McCall2de56d12010-08-25 11:45:40 +00008084 case BO_Rem:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008085 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
8086 break;
John McCall2de56d12010-08-25 11:45:40 +00008087 case BO_Add:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008088 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
8089 break;
John McCall2de56d12010-08-25 11:45:40 +00008090 case BO_Sub:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008091 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
8092 break;
John McCall2de56d12010-08-25 11:45:40 +00008093 case BO_Shl:
8094 case BO_Shr:
Chandler Carruth21206d52011-02-23 23:34:11 +00008095 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008096 break;
John McCall2de56d12010-08-25 11:45:40 +00008097 case BO_LE:
8098 case BO_LT:
8099 case BO_GE:
8100 case BO_GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00008101 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008102 break;
John McCall2de56d12010-08-25 11:45:40 +00008103 case BO_EQ:
8104 case BO_NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00008105 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008106 break;
John McCall2de56d12010-08-25 11:45:40 +00008107 case BO_And:
8108 case BO_Xor:
8109 case BO_Or:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008110 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
8111 break;
John McCall2de56d12010-08-25 11:45:40 +00008112 case BO_LAnd:
8113 case BO_LOr:
Chris Lattner90a8f272010-07-13 19:41:32 +00008114 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008115 break;
John McCall2de56d12010-08-25 11:45:40 +00008116 case BO_MulAssign:
8117 case BO_DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00008118 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00008119 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008120 CompLHSTy = CompResultTy;
8121 if (!CompResultTy.isNull())
8122 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008123 break;
John McCall2de56d12010-08-25 11:45:40 +00008124 case BO_RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008125 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
8126 CompLHSTy = CompResultTy;
8127 if (!CompResultTy.isNull())
8128 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008129 break;
John McCall2de56d12010-08-25 11:45:40 +00008130 case BO_AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008131 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
8132 if (!CompResultTy.isNull())
8133 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008134 break;
John McCall2de56d12010-08-25 11:45:40 +00008135 case BO_SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008136 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
8137 if (!CompResultTy.isNull())
8138 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008139 break;
John McCall2de56d12010-08-25 11:45:40 +00008140 case BO_ShlAssign:
8141 case BO_ShrAssign:
Chandler Carruth21206d52011-02-23 23:34:11 +00008142 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008143 CompLHSTy = CompResultTy;
8144 if (!CompResultTy.isNull())
8145 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008146 break;
John McCall2de56d12010-08-25 11:45:40 +00008147 case BO_AndAssign:
8148 case BO_XorAssign:
8149 case BO_OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008150 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
8151 CompLHSTy = CompResultTy;
8152 if (!CompResultTy.isNull())
8153 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008154 break;
John McCall2de56d12010-08-25 11:45:40 +00008155 case BO_Comma:
John McCall09431682010-11-18 19:01:18 +00008156 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John McCallf89e55a2010-11-18 06:31:45 +00008157 if (getLangOptions().CPlusPlus) {
8158 VK = rhs->getValueKind();
8159 OK = rhs->getObjectKind();
8160 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00008161 break;
8162 }
8163 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008164 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00008165 if (CompResultTy.isNull())
John McCallf89e55a2010-11-18 06:31:45 +00008166 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy,
8167 VK, OK, OpLoc));
8168
John McCallf6a16482010-12-04 03:47:34 +00008169 if (getLangOptions().CPlusPlus && lhs->getObjectKind() != OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00008170 VK = VK_LValue;
8171 OK = lhs->getObjectKind();
8172 }
8173 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
8174 VK, OK, CompLHSTy,
8175 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00008176}
8177
Sebastian Redlaee3c932009-10-27 12:10:02 +00008178/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
8179/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008180static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8181 const PartialDiagnostic &PD,
Douglas Gregor55b38842010-04-14 16:09:52 +00008182 const PartialDiagnostic &FirstNote,
8183 SourceRange FirstParenRange,
8184 const PartialDiagnostic &SecondNote,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008185 SourceRange SecondParenRange) {
Douglas Gregor55b38842010-04-14 16:09:52 +00008186 Self.Diag(Loc, PD);
8187
8188 if (!FirstNote.getDiagID())
8189 return;
8190
8191 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
8192 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8193 // We can't display the parentheses, so just return.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008194 return;
8195 }
8196
Douglas Gregor55b38842010-04-14 16:09:52 +00008197 Self.Diag(Loc, FirstNote)
8198 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregor849b2432010-03-31 17:46:05 +00008199 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008200
Douglas Gregor55b38842010-04-14 16:09:52 +00008201 if (!SecondNote.getDiagID())
Douglas Gregor827feec2010-01-08 00:20:23 +00008202 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008203
Douglas Gregor827feec2010-01-08 00:20:23 +00008204 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
8205 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8206 // We can't display the parentheses, so just dig the
8207 // warning/error and return.
Douglas Gregor55b38842010-04-14 16:09:52 +00008208 Self.Diag(Loc, SecondNote);
Douglas Gregor827feec2010-01-08 00:20:23 +00008209 return;
8210 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008211
Douglas Gregor55b38842010-04-14 16:09:52 +00008212 Self.Diag(Loc, SecondNote)
Douglas Gregor849b2432010-03-31 17:46:05 +00008213 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
8214 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008215}
8216
Sebastian Redlaee3c932009-10-27 12:10:02 +00008217/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8218/// operators are mixed in a way that suggests that the programmer forgot that
8219/// comparison operators have higher precedence. The most typical example of
8220/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00008221static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008222 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00008223 typedef BinaryOperator BinOp;
8224 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
8225 rhsopc = static_cast<BinOp::Opcode>(-1);
8226 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008227 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00008228 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008229 rhsopc = BO->getOpcode();
8230
8231 // Subs are not binary operators.
8232 if (lhsopc == -1 && rhsopc == -1)
8233 return;
8234
8235 // Bitwise operations are sometimes used as eager logical ops.
8236 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00008237 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
8238 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008239 return;
8240
Sebastian Redlaee3c932009-10-27 12:10:02 +00008241 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008242 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008243 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00008244 << SourceRange(lhs->getLocStart(), OpLoc)
8245 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008246 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00008247 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00008248 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
8249 Self.PDiag(diag::note_precedence_bitwise_silence)
8250 << BinOp::getOpcodeStr(lhsopc),
8251 lhs->getSourceRange());
Sebastian Redlaee3c932009-10-27 12:10:02 +00008252 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008253 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008254 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00008255 << SourceRange(OpLoc, rhs->getLocEnd())
8256 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008257 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00008258 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00008259 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
8260 Self.PDiag(diag::note_precedence_bitwise_silence)
8261 << BinOp::getOpcodeStr(rhsopc),
8262 rhs->getSourceRange());
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008263}
8264
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008265/// \brief It accepts a '&&' expr that is inside a '||' one.
8266/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8267/// in parentheses.
8268static void
8269EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8270 Expr *E) {
8271 assert(isa<BinaryOperator>(E) &&
8272 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
8273 SuggestParentheses(Self, OpLoc,
8274 Self.PDiag(diag::warn_logical_and_in_logical_or)
8275 << E->getSourceRange(),
8276 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
8277 E->getSourceRange(),
8278 Self.PDiag(0), SourceRange());
8279}
8280
8281/// \brief Returns true if the given expression can be evaluated as a constant
8282/// 'true'.
8283static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8284 bool Res;
8285 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8286}
8287
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008288/// \brief Returns true if the given expression can be evaluated as a constant
8289/// 'false'.
8290static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8291 bool Res;
8292 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8293}
8294
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008295/// \brief Look for '&&' in the left hand of a '||' expr.
8296static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008297 Expr *OrLHS, Expr *OrRHS) {
8298 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008299 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008300 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8301 if (EvaluatesAsFalse(S, OrRHS))
8302 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008303 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8304 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8305 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8306 } else if (Bop->getOpcode() == BO_LOr) {
8307 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8308 // If it's "a || b && 1 || c" we didn't warn earlier for
8309 // "a || b && 1", but warn now.
8310 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8311 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8312 }
8313 }
8314 }
8315}
8316
8317/// \brief Look for '&&' in the right hand of a '||' expr.
8318static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008319 Expr *OrLHS, Expr *OrRHS) {
8320 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008321 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008322 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8323 if (EvaluatesAsFalse(S, OrLHS))
8324 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008325 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8326 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8327 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008328 }
8329 }
8330}
8331
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008332/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008333/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008334static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008335 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008336 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008337 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008338 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
8339
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008340 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8341 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008342 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008343 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
8344 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008345 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008346}
8347
Reid Spencer5f016e22007-07-11 17:01:13 +00008348// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008349ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008350 tok::TokenKind Kind,
8351 Expr *lhs, Expr *rhs) {
8352 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Narofff69936d2007-09-16 03:34:24 +00008353 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8354 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008355
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008356 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8357 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8358
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008359 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8360}
8361
John McCall60d7b3a2010-08-24 06:29:42 +00008362ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008363 BinaryOperatorKind Opc,
8364 Expr *lhs, Expr *rhs) {
John McCall01b2e4e2010-12-06 05:26:58 +00008365 if (getLangOptions().CPlusPlus) {
8366 bool UseBuiltinOperator;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008367
John McCall01b2e4e2010-12-06 05:26:58 +00008368 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8369 UseBuiltinOperator = false;
8370 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8371 UseBuiltinOperator = true;
8372 } else {
8373 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8374 !rhs->getType()->isOverloadableType();
8375 }
8376
8377 if (!UseBuiltinOperator) {
8378 // Find all of the overloaded operators visible from this
8379 // point. We perform both an operator-name lookup from the local
8380 // scope and an argument-dependent lookup based on the types of
8381 // the arguments.
8382 UnresolvedSet<16> Functions;
8383 OverloadedOperatorKind OverOp
8384 = BinaryOperator::getOverloadedOperator(Opc);
8385 if (S && OverOp != OO_None)
8386 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8387 Functions);
8388
8389 // Build the (potentially-overloaded, potentially-dependent)
8390 // binary operation.
8391 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8392 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008393 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008394
Douglas Gregoreaebc752008-11-06 23:29:22 +00008395 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008396 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00008397}
8398
John McCall60d7b3a2010-08-24 06:29:42 +00008399ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008400 UnaryOperatorKind Opc,
John McCall2cd11fe2010-10-12 02:09:17 +00008401 Expr *Input) {
John McCallf89e55a2010-11-18 06:31:45 +00008402 ExprValueKind VK = VK_RValue;
8403 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008404 QualType resultType;
8405 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008406 case UO_PreInc:
8407 case UO_PreDec:
8408 case UO_PostInc:
8409 case UO_PostDec:
John McCall09431682010-11-18 19:01:18 +00008410 resultType = CheckIncrementDecrementOperand(*this, Input, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008411 Opc == UO_PreInc ||
8412 Opc == UO_PostInc,
8413 Opc == UO_PreInc ||
8414 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008415 break;
John McCall2de56d12010-08-25 11:45:40 +00008416 case UO_AddrOf:
John McCall09431682010-11-18 19:01:18 +00008417 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008418 break;
John McCall2de56d12010-08-25 11:45:40 +00008419 case UO_Deref:
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008420 if (Input->getType() == Context.OverloadTy ) {
8421 ExprResult er = ResolveAndFixSingleFunctionTemplateSpecialization(Input);
8422 if (er.isUsable())
8423 Input = er.release();
8424 }
Douglas Gregora873dfc2010-02-03 00:27:59 +00008425 DefaultFunctionArrayLvalueConversion(Input);
John McCall09431682010-11-18 19:01:18 +00008426 resultType = CheckIndirectionOperand(*this, Input, VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008427 break;
John McCall2de56d12010-08-25 11:45:40 +00008428 case UO_Plus:
8429 case UO_Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00008430 UsualUnaryConversions(Input);
8431 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008432 if (resultType->isDependentType())
8433 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008434 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8435 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008436 break;
8437 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8438 resultType->isEnumeralType())
8439 break;
8440 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008441 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008442 resultType->isPointerType())
8443 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008444 else if (resultType->isPlaceholderType()) {
8445 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8446 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008447 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008448 }
Douglas Gregor74253732008-11-19 15:42:04 +00008449
Sebastian Redl0eb23302009-01-19 00:08:26 +00008450 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8451 << resultType << Input->getSourceRange());
John McCall2de56d12010-08-25 11:45:40 +00008452 case UO_Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00008453 UsualUnaryConversions(Input);
8454 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008455 if (resultType->isDependentType())
8456 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008457 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8458 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8459 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008460 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00008461 << resultType << Input->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008462 else if (resultType->hasIntegerRepresentation())
8463 break;
8464 else if (resultType->isPlaceholderType()) {
8465 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8466 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008467 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008468 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008469 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8470 << resultType << Input->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008471 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008472 break;
John McCall2de56d12010-08-25 11:45:40 +00008473 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008474 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregora873dfc2010-02-03 00:27:59 +00008475 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroffc80b4ee2007-07-16 21:54:35 +00008476 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008477 if (resultType->isDependentType())
8478 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008479 if (resultType->isScalarType()) { // C99 6.5.3.3p1
8480 // ok, fallthrough
8481 } else if (resultType->isPlaceholderType()) {
8482 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8483 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008484 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008485 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008486 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8487 << resultType << Input->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008488 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008489
Reid Spencer5f016e22007-07-11 17:01:13 +00008490 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008491 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008492 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008493 break;
John McCall2de56d12010-08-25 11:45:40 +00008494 case UO_Real:
8495 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008496 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCallf89e55a2010-11-18 06:31:45 +00008497 // _Real and _Imag map ordinary l-values into ordinary l-values.
8498 if (Input->getValueKind() != VK_RValue &&
8499 Input->getObjectKind() == OK_Ordinary)
8500 VK = Input->getValueKind();
Chris Lattnerdbb36972007-08-24 21:16:53 +00008501 break;
John McCall2de56d12010-08-25 11:45:40 +00008502 case UO_Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00008503 resultType = Input->getType();
John McCallf89e55a2010-11-18 06:31:45 +00008504 VK = Input->getValueKind();
8505 OK = Input->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008506 break;
8507 }
8508 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008509 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008510
John McCallf89e55a2010-11-18 06:31:45 +00008511 return Owned(new (Context) UnaryOperator(Input, Opc, resultType,
8512 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008513}
8514
John McCall60d7b3a2010-08-24 06:29:42 +00008515ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008516 UnaryOperatorKind Opc,
8517 Expr *Input) {
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00008518 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman957c0942010-09-05 23:15:52 +00008519 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008520 // Find all of the overloaded operators visible from this
8521 // point. We perform both an operator-name lookup from the local
8522 // scope and an argument-dependent lookup based on the types of
8523 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008524 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008525 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008526 if (S && OverOp != OO_None)
8527 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8528 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008529
John McCall9ae2f072010-08-23 23:25:46 +00008530 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008531 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008532
John McCall9ae2f072010-08-23 23:25:46 +00008533 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008534}
8535
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008536// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008537ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008538 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008539 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008540}
8541
Steve Naroff1b273c42007-09-16 14:56:35 +00008542/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008543ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008544 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008545 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008546 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008547 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008548 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008549}
8550
John McCall60d7b3a2010-08-24 06:29:42 +00008551ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008552Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008553 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008554 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8555 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8556
Douglas Gregordd8f5692010-03-10 04:54:39 +00008557 bool isFileScope
8558 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00008559 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00008560 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00008561
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008562 // FIXME: there are a variety of strange constraints to enforce here, for
8563 // example, it is not possible to goto into a stmt expression apparently.
8564 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008565
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008566 // If there are sub stmts in the compound stmt, take the type of the last one
8567 // as the type of the stmtexpr.
8568 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008569 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008570 if (!Compound->body_empty()) {
8571 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008572 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008573 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008574 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8575 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008576 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008577 }
8578 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00008579 // Do function/array conversion on the last expression, but not
8580 // lvalue-to-rvalue. However, initialize an unqualified type.
8581 DefaultFunctionArrayConversion(LastExpr);
8582 Ty = LastExpr->getType().getUnqualifiedType();
8583
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008584 if (!Ty->isDependentType() && !LastExpr->isTypeDependent()) {
8585 ExprResult Res = PerformCopyInitialization(
8586 InitializedEntity::InitializeResult(LPLoc,
8587 Ty,
8588 false),
8589 SourceLocation(),
8590 Owned(LastExpr));
8591 if (Res.isInvalid())
8592 return ExprError();
8593 if ((LastExpr = Res.takeAs<Expr>())) {
8594 if (!LastLabelStmt)
8595 Compound->setLastStmt(LastExpr);
8596 else
8597 LastLabelStmt->setSubStmt(LastExpr);
8598 StmtExprMayBindToTemp = true;
8599 }
8600 }
8601 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00008602 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008603
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008604 // FIXME: Check that expression type is complete/non-abstract; statement
8605 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008606 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8607 if (StmtExprMayBindToTemp)
8608 return MaybeBindToTemporary(ResStmtExpr);
8609 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008610}
Steve Naroffd34e9152007-08-01 22:05:33 +00008611
John McCall60d7b3a2010-08-24 06:29:42 +00008612ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008613 TypeSourceInfo *TInfo,
8614 OffsetOfComponent *CompPtr,
8615 unsigned NumComponents,
8616 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008617 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008618 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008619 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008620
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008621 // We must have at least one component that refers to the type, and the first
8622 // one is known to be a field designator. Verify that the ArgTy represents
8623 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00008624 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008625 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8626 << ArgTy << TypeRange);
8627
8628 // Type must be complete per C99 7.17p3 because a declaring a variable
8629 // with an incomplete type would be ill-formed.
8630 if (!Dependent
8631 && RequireCompleteType(BuiltinLoc, ArgTy,
8632 PDiag(diag::err_offsetof_incomplete_type)
8633 << TypeRange))
8634 return ExprError();
8635
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008636 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8637 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00008638 // FIXME: This diagnostic isn't actually visible because the location is in
8639 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008640 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008641 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8642 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008643
8644 bool DidWarnAboutNonPOD = false;
8645 QualType CurrentType = ArgTy;
8646 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8647 llvm::SmallVector<OffsetOfNode, 4> Comps;
8648 llvm::SmallVector<Expr*, 4> Exprs;
8649 for (unsigned i = 0; i != NumComponents; ++i) {
8650 const OffsetOfComponent &OC = CompPtr[i];
8651 if (OC.isBrackets) {
8652 // Offset of an array sub-field. TODO: Should we allow vector elements?
8653 if (!CurrentType->isDependentType()) {
8654 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8655 if(!AT)
8656 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8657 << CurrentType);
8658 CurrentType = AT->getElementType();
8659 } else
8660 CurrentType = Context.DependentTy;
8661
8662 // The expression must be an integral expression.
8663 // FIXME: An integral constant expression?
8664 Expr *Idx = static_cast<Expr*>(OC.U.E);
8665 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8666 !Idx->getType()->isIntegerType())
8667 return ExprError(Diag(Idx->getLocStart(),
8668 diag::err_typecheck_subscript_not_integer)
8669 << Idx->getSourceRange());
8670
8671 // Record this array index.
8672 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8673 Exprs.push_back(Idx);
8674 continue;
8675 }
8676
8677 // Offset of a field.
8678 if (CurrentType->isDependentType()) {
8679 // We have the offset of a field, but we can't look into the dependent
8680 // type. Just record the identifier of the field.
8681 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8682 CurrentType = Context.DependentTy;
8683 continue;
8684 }
8685
8686 // We need to have a complete type to look into.
8687 if (RequireCompleteType(OC.LocStart, CurrentType,
8688 diag::err_offsetof_incomplete_type))
8689 return ExprError();
8690
8691 // Look for the designated field.
8692 const RecordType *RC = CurrentType->getAs<RecordType>();
8693 if (!RC)
8694 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8695 << CurrentType);
8696 RecordDecl *RD = RC->getDecl();
8697
8698 // C++ [lib.support.types]p5:
8699 // The macro offsetof accepts a restricted set of type arguments in this
8700 // International Standard. type shall be a POD structure or a POD union
8701 // (clause 9).
8702 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8703 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00008704 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008705 PDiag(diag::warn_offsetof_non_pod_type)
8706 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8707 << CurrentType))
8708 DidWarnAboutNonPOD = true;
8709 }
8710
8711 // Look for the field.
8712 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8713 LookupQualifiedName(R, RD);
8714 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00008715 IndirectFieldDecl *IndirectMemberDecl = 0;
8716 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00008717 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00008718 MemberDecl = IndirectMemberDecl->getAnonField();
8719 }
8720
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008721 if (!MemberDecl)
8722 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8723 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8724 OC.LocEnd));
8725
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00008726 // C99 7.17p3:
8727 // (If the specified member is a bit-field, the behavior is undefined.)
8728 //
8729 // We diagnose this as an error.
8730 if (MemberDecl->getBitWidth()) {
8731 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8732 << MemberDecl->getDeclName()
8733 << SourceRange(BuiltinLoc, RParenLoc);
8734 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8735 return ExprError();
8736 }
Eli Friedman19410a72010-08-05 10:11:36 +00008737
8738 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00008739 if (IndirectMemberDecl)
8740 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00008741
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008742 // If the member was found in a base class, introduce OffsetOfNodes for
8743 // the base class indirections.
8744 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8745 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00008746 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008747 CXXBasePath &Path = Paths.front();
8748 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8749 B != BEnd; ++B)
8750 Comps.push_back(OffsetOfNode(B->Base));
8751 }
Eli Friedman19410a72010-08-05 10:11:36 +00008752
Francois Pichet87c2e122010-11-21 06:08:52 +00008753 if (IndirectMemberDecl) {
8754 for (IndirectFieldDecl::chain_iterator FI =
8755 IndirectMemberDecl->chain_begin(),
8756 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8757 assert(isa<FieldDecl>(*FI));
8758 Comps.push_back(OffsetOfNode(OC.LocStart,
8759 cast<FieldDecl>(*FI), OC.LocEnd));
8760 }
8761 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008762 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00008763
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008764 CurrentType = MemberDecl->getType().getNonReferenceType();
8765 }
8766
8767 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8768 TInfo, Comps.data(), Comps.size(),
8769 Exprs.data(), Exprs.size(), RParenLoc));
8770}
Mike Stumpeed9cac2009-02-19 03:04:26 +00008771
John McCall60d7b3a2010-08-24 06:29:42 +00008772ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00008773 SourceLocation BuiltinLoc,
8774 SourceLocation TypeLoc,
8775 ParsedType argty,
8776 OffsetOfComponent *CompPtr,
8777 unsigned NumComponents,
8778 SourceLocation RPLoc) {
8779
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008780 TypeSourceInfo *ArgTInfo;
8781 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8782 if (ArgTy.isNull())
8783 return ExprError();
8784
Eli Friedman5a15dc12010-08-05 10:15:45 +00008785 if (!ArgTInfo)
8786 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8787
8788 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8789 RPLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008790}
8791
8792
John McCall60d7b3a2010-08-24 06:29:42 +00008793ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008794 Expr *CondExpr,
8795 Expr *LHSExpr, Expr *RHSExpr,
8796 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00008797 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8798
John McCallf89e55a2010-11-18 06:31:45 +00008799 ExprValueKind VK = VK_RValue;
8800 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00008801 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00008802 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00008803 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00008804 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00008805 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00008806 } else {
8807 // The conditional expression is required to be a constant expression.
8808 llvm::APSInt condEval(32);
8809 SourceLocation ExpLoc;
8810 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00008811 return ExprError(Diag(ExpLoc,
8812 diag::err_typecheck_choose_expr_requires_constant)
8813 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00008814
Sebastian Redl28507842009-02-26 14:39:58 +00008815 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00008816 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8817
8818 resType = ActiveExpr->getType();
8819 ValueDependent = ActiveExpr->isValueDependent();
8820 VK = ActiveExpr->getValueKind();
8821 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00008822 }
8823
Sebastian Redlf53597f2009-03-15 17:47:39 +00008824 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00008825 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00008826 resType->isDependentType(),
8827 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00008828}
8829
Steve Naroff4eb206b2008-09-03 18:15:37 +00008830//===----------------------------------------------------------------------===//
8831// Clang Extensions.
8832//===----------------------------------------------------------------------===//
8833
8834/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00008835void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008836 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8837 PushBlockScope(BlockScope, Block);
8838 CurContext->addDecl(Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008839 if (BlockScope)
8840 PushDeclContext(BlockScope, Block);
8841 else
8842 CurContext = Block;
Steve Naroff090276f2008-10-10 01:28:17 +00008843}
8844
Mike Stump98eb8a72009-02-04 22:31:32 +00008845void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00008846 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00008847 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008848 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008849
John McCallbf1a0282010-06-04 23:28:52 +00008850 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00008851 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00008852
John McCall711c52b2011-01-05 12:14:39 +00008853 // GetTypeForDeclarator always produces a function type for a block
8854 // literal signature. Furthermore, it is always a FunctionProtoType
8855 // unless the function was written with a typedef.
8856 assert(T->isFunctionType() &&
8857 "GetTypeForDeclarator made a non-function block signature");
8858
8859 // Look for an explicit signature in that function type.
8860 FunctionProtoTypeLoc ExplicitSignature;
8861
8862 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8863 if (isa<FunctionProtoTypeLoc>(tmp)) {
8864 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8865
8866 // Check whether that explicit signature was synthesized by
8867 // GetTypeForDeclarator. If so, don't save that as part of the
8868 // written signature.
8869 if (ExplicitSignature.getLParenLoc() ==
8870 ExplicitSignature.getRParenLoc()) {
8871 // This would be much cheaper if we stored TypeLocs instead of
8872 // TypeSourceInfos.
8873 TypeLoc Result = ExplicitSignature.getResultLoc();
8874 unsigned Size = Result.getFullDataSize();
8875 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8876 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8877
8878 ExplicitSignature = FunctionProtoTypeLoc();
8879 }
John McCall82dc0092010-06-04 11:21:44 +00008880 }
Mike Stump1eb44332009-09-09 15:08:12 +00008881
John McCall711c52b2011-01-05 12:14:39 +00008882 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8883 CurBlock->FunctionType = T;
8884
8885 const FunctionType *Fn = T->getAs<FunctionType>();
8886 QualType RetTy = Fn->getResultType();
8887 bool isVariadic =
8888 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8889
John McCallc71a4912010-06-04 19:02:56 +00008890 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00008891
John McCall82dc0092010-06-04 11:21:44 +00008892 // Don't allow returning a objc interface by value.
8893 if (RetTy->isObjCObjectType()) {
8894 Diag(ParamInfo.getSourceRange().getBegin(),
8895 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8896 return;
8897 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008898
John McCall82dc0092010-06-04 11:21:44 +00008899 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00008900 // return type. TODO: what should we do with declarators like:
8901 // ^ * { ... }
8902 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00008903 if (RetTy != Context.DependentTy)
8904 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008905
John McCall82dc0092010-06-04 11:21:44 +00008906 // Push block parameters from the declarator if we had them.
John McCallc71a4912010-06-04 19:02:56 +00008907 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00008908 if (ExplicitSignature) {
8909 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8910 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008911 if (Param->getIdentifier() == 0 &&
8912 !Param->isImplicit() &&
8913 !Param->isInvalidDecl() &&
8914 !getLangOptions().CPlusPlus)
8915 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00008916 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008917 }
John McCall82dc0092010-06-04 11:21:44 +00008918
8919 // Fake up parameter variables if we have a typedef, like
8920 // ^ fntype { ... }
8921 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8922 for (FunctionProtoType::arg_type_iterator
8923 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8924 ParmVarDecl *Param =
8925 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8926 ParamInfo.getSourceRange().getBegin(),
8927 *I);
John McCallc71a4912010-06-04 19:02:56 +00008928 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00008929 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008930 }
John McCall82dc0092010-06-04 11:21:44 +00008931
John McCallc71a4912010-06-04 19:02:56 +00008932 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00008933 if (!Params.empty()) {
John McCallc71a4912010-06-04 19:02:56 +00008934 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregor82aa7132010-11-01 18:37:59 +00008935 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8936 CurBlock->TheDecl->param_end(),
8937 /*CheckParameterNames=*/false);
8938 }
8939
John McCall82dc0092010-06-04 11:21:44 +00008940 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00008941 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00008942
John McCallc71a4912010-06-04 19:02:56 +00008943 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00008944 Diag(ParamInfo.getAttributes()->getLoc(),
8945 diag::warn_attribute_sentinel_not_variadic) << 1;
8946 // FIXME: remove the attribute.
8947 }
8948
8949 // Put the parameter variables in scope. We can bail out immediately
8950 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00008951 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00008952 return;
8953
Steve Naroff090276f2008-10-10 01:28:17 +00008954 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00008955 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8956 (*AI)->setOwningFunction(CurBlock->TheDecl);
8957
Steve Naroff090276f2008-10-10 01:28:17 +00008958 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00008959 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00008960 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00008961
Steve Naroff090276f2008-10-10 01:28:17 +00008962 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00008963 }
John McCall7a9813c2010-01-22 00:28:27 +00008964 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008965}
8966
8967/// ActOnBlockError - If there is an error parsing a block, this callback
8968/// is invoked to pop the information about the block from the action impl.
8969void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00008970 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00008971 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008972 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008973}
8974
8975/// ActOnBlockStmtExpr - This is called when the body of a block statement
8976/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00008977ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00008978 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00008979 // If blocks are disabled, emit an error.
8980 if (!LangOpts.Blocks)
8981 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00008982
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008983 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008984
Steve Naroff090276f2008-10-10 01:28:17 +00008985 PopDeclContext();
8986
Steve Naroff4eb206b2008-09-03 18:15:37 +00008987 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00008988 if (!BSI->ReturnType.isNull())
8989 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008990
Mike Stump56925862009-07-28 22:04:01 +00008991 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008992 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00008993
John McCall469a1eb2011-02-02 13:00:07 +00008994 // Set the captured variables on the block.
John McCall6b5a61b2011-02-07 10:33:21 +00008995 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8996 BSI->CapturesCXXThis);
John McCall469a1eb2011-02-02 13:00:07 +00008997
John McCallc71a4912010-06-04 19:02:56 +00008998 // If the user wrote a function type in some form, try to use that.
8999 if (!BSI->FunctionType.isNull()) {
9000 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9001
9002 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9003 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9004
9005 // Turn protoless block types into nullary block types.
9006 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00009007 FunctionProtoType::ExtProtoInfo EPI;
9008 EPI.ExtInfo = Ext;
9009 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009010
9011 // Otherwise, if we don't need to change anything about the function type,
9012 // preserve its sugar structure.
9013 } else if (FTy->getResultType() == RetTy &&
9014 (!NoReturn || FTy->getNoReturnAttr())) {
9015 BlockTy = BSI->FunctionType;
9016
9017 // Otherwise, make the minimal modifications to the function type.
9018 } else {
9019 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00009020 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9021 EPI.TypeQuals = 0; // FIXME: silently?
9022 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00009023 BlockTy = Context.getFunctionType(RetTy,
9024 FPT->arg_type_begin(),
9025 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00009026 EPI);
John McCallc71a4912010-06-04 19:02:56 +00009027 }
9028
9029 // If we don't have a function type, just build one from nothing.
9030 } else {
John McCalle23cf432010-12-14 08:05:40 +00009031 FunctionProtoType::ExtProtoInfo EPI;
9032 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, 0, CC_Default);
9033 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009034 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009035
John McCallc71a4912010-06-04 19:02:56 +00009036 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9037 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00009038 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009039
Chris Lattner17a78302009-04-19 05:28:12 +00009040 // If needed, diagnose invalid gotos and switches in the block.
John McCall781472f2010-08-25 08:40:02 +00009041 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00009042 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00009043
Chris Lattnere476bdc2011-02-17 23:58:47 +00009044 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009045
John McCall469a1eb2011-02-02 13:00:07 +00009046 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCalle0054f62010-08-25 05:56:39 +00009047
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00009048 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9049 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009050 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00009051}
9052
John McCall60d7b3a2010-08-24 06:29:42 +00009053ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallb3d87482010-08-24 05:47:05 +00009054 Expr *expr, ParsedType type,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009055 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009056 TypeSourceInfo *TInfo;
Jeffrey Yasskindec09842011-01-18 02:00:16 +00009057 GetTypeFromParser(type, &TInfo);
John McCall9ae2f072010-08-23 23:25:46 +00009058 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009059}
9060
John McCall60d7b3a2010-08-24 06:29:42 +00009061ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00009062 Expr *E, TypeSourceInfo *TInfo,
9063 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009064 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00009065
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009066 // Get the va_list type
9067 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009068 if (VaListType->isArrayType()) {
9069 // Deal with implicit array decay; for example, on x86-64,
9070 // va_list is an array, but it's supposed to decay to
9071 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009072 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00009073 // Make sure the input expression also decays appropriately.
9074 UsualUnaryConversions(E);
9075 } else {
9076 // Otherwise, the va_list argument must be an l-value because
9077 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00009078 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00009079 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00009080 return ExprError();
9081 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009082
Douglas Gregordd027302009-05-19 23:10:31 +00009083 if (!E->isTypeDependent() &&
9084 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00009085 return ExprError(Diag(E->getLocStart(),
9086 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009087 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00009088 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009089
Eli Friedmanb1d796d2009-03-23 00:24:07 +00009090 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00009091 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00009092
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009093 QualType T = TInfo->getType().getNonLValueExprType(Context);
9094 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00009095}
9096
John McCall60d7b3a2010-08-24 06:29:42 +00009097ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009098 // The type of __null will be int or long, depending on the size of
9099 // pointers on the target.
9100 QualType Ty;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009101 unsigned pw = Context.Target.getPointerWidth(0);
9102 if (pw == Context.Target.getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009103 Ty = Context.IntTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009104 else if (pw == Context.Target.getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009105 Ty = Context.LongTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009106 else if (pw == Context.Target.getLongLongWidth())
9107 Ty = Context.LongLongTy;
9108 else {
9109 assert(!"I don't know size of pointer!");
9110 Ty = Context.IntTy;
9111 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009112
Sebastian Redlf53597f2009-03-15 17:47:39 +00009113 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009114}
9115
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009116static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00009117 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009118 if (!SemaRef.getLangOptions().ObjC1)
9119 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009120
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009121 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9122 if (!PT)
9123 return;
9124
9125 // Check if the destination is of type 'id'.
9126 if (!PT->isObjCIdType()) {
9127 // Check if the destination is the 'NSString' interface.
9128 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9129 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9130 return;
9131 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009132
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009133 // Strip off any parens and casts.
9134 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
9135 if (!SL || SL->isWide())
9136 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009137
Douglas Gregor849b2432010-03-31 17:46:05 +00009138 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009139}
9140
Chris Lattner5cf216b2008-01-04 18:04:52 +00009141bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9142 SourceLocation Loc,
9143 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00009144 Expr *SrcExpr, AssignmentAction Action,
9145 bool *Complained) {
9146 if (Complained)
9147 *Complained = false;
9148
Chris Lattner5cf216b2008-01-04 18:04:52 +00009149 // Decode the result (notice that AST's are still created for extensions).
9150 bool isInvalid = false;
9151 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00009152 FixItHint Hint;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009153
Chris Lattner5cf216b2008-01-04 18:04:52 +00009154 switch (ConvTy) {
9155 default: assert(0 && "Unknown conversion type");
9156 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009157 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00009158 DiagKind = diag::ext_typecheck_convert_pointer_int;
9159 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009160 case IntToPointer:
9161 DiagKind = diag::ext_typecheck_convert_int_pointer;
9162 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009163 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00009164 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009165 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9166 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009167 case IncompatiblePointerSign:
9168 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9169 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009170 case FunctionVoidPointer:
9171 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9172 break;
John McCall86c05f32011-02-01 00:10:29 +00009173 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009174 // Perform array-to-pointer decay if necessary.
9175 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9176
John McCall86c05f32011-02-01 00:10:29 +00009177 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9178 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9179 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9180 DiagKind = diag::err_typecheck_incompatible_address_space;
9181 break;
9182 }
9183
9184 llvm_unreachable("unknown error case for discarding qualifiers!");
9185 // fallthrough
9186 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009187 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009188 // If the qualifiers lost were because we were applying the
9189 // (deprecated) C++ conversion from a string literal to a char*
9190 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9191 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009192 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009193 // bit of refactoring (so that the second argument is an
9194 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009195 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009196 // C++ semantics.
9197 if (getLangOptions().CPlusPlus &&
9198 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9199 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009200 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9201 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009202 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009203 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009204 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009205 case IntToBlockPointer:
9206 DiagKind = diag::err_int_to_block_pointer;
9207 break;
9208 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009209 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009210 break;
Steve Naroff39579072008-10-14 22:18:38 +00009211 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009212 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009213 // it can give a more specific diagnostic.
9214 DiagKind = diag::warn_incompatible_qualified_id;
9215 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009216 case IncompatibleVectors:
9217 DiagKind = diag::warn_incompatible_vectors;
9218 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009219 case Incompatible:
9220 DiagKind = diag::err_typecheck_convert_incompatible;
9221 isInvalid = true;
9222 break;
9223 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009224
Douglas Gregord4eea832010-04-09 00:35:39 +00009225 QualType FirstType, SecondType;
9226 switch (Action) {
9227 case AA_Assigning:
9228 case AA_Initializing:
9229 // The destination type comes first.
9230 FirstType = DstType;
9231 SecondType = SrcType;
9232 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009233
Douglas Gregord4eea832010-04-09 00:35:39 +00009234 case AA_Returning:
9235 case AA_Passing:
9236 case AA_Converting:
9237 case AA_Sending:
9238 case AA_Casting:
9239 // The source type comes first.
9240 FirstType = SrcType;
9241 SecondType = DstType;
9242 break;
9243 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009244
Douglas Gregord4eea832010-04-09 00:35:39 +00009245 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009246 << SrcExpr->getSourceRange() << Hint;
Douglas Gregora41a8c52010-04-22 00:20:18 +00009247 if (Complained)
9248 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009249 return isInvalid;
9250}
Anders Carlssone21555e2008-11-30 19:50:32 +00009251
Chris Lattner3bf68932009-04-25 21:59:05 +00009252bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009253 llvm::APSInt ICEResult;
9254 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9255 if (Result)
9256 *Result = ICEResult;
9257 return false;
9258 }
9259
Anders Carlssone21555e2008-11-30 19:50:32 +00009260 Expr::EvalResult EvalResult;
9261
Mike Stumpeed9cac2009-02-19 03:04:26 +00009262 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00009263 EvalResult.HasSideEffects) {
9264 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9265
9266 if (EvalResult.Diag) {
9267 // We only show the note if it's not the usual "invalid subexpression"
9268 // or if it's actually in a subexpression.
9269 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9270 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9271 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9272 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009273
Anders Carlssone21555e2008-11-30 19:50:32 +00009274 return true;
9275 }
9276
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009277 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9278 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00009279
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009280 if (EvalResult.Diag &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009281 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9282 != Diagnostic::Ignored)
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009283 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009284
Anders Carlssone21555e2008-11-30 19:50:32 +00009285 if (Result)
9286 *Result = EvalResult.Val.getInt();
9287 return false;
9288}
Douglas Gregore0762c92009-06-19 23:52:42 +00009289
Douglas Gregor2afce722009-11-26 00:44:06 +00009290void
Mike Stump1eb44332009-09-09 15:08:12 +00009291Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009292 ExprEvalContexts.push_back(
9293 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00009294}
9295
Mike Stump1eb44332009-09-09 15:08:12 +00009296void
Douglas Gregor2afce722009-11-26 00:44:06 +00009297Sema::PopExpressionEvaluationContext() {
9298 // Pop the current expression evaluation context off the stack.
9299 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9300 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009301
Douglas Gregor06d33692009-12-12 07:57:52 +00009302 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9303 if (Rec.PotentiallyReferenced) {
9304 // Mark any remaining declarations in the current position of the stack
9305 // as "referenced". If they were not meant to be referenced, semantic
9306 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009307 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00009308 I = Rec.PotentiallyReferenced->begin(),
9309 IEnd = Rec.PotentiallyReferenced->end();
9310 I != IEnd; ++I)
9311 MarkDeclarationReferenced(I->first, I->second);
9312 }
9313
9314 if (Rec.PotentiallyDiagnosed) {
9315 // Emit any pending diagnostics.
9316 for (PotentiallyEmittedDiagnostics::iterator
9317 I = Rec.PotentiallyDiagnosed->begin(),
9318 IEnd = Rec.PotentiallyDiagnosed->end();
9319 I != IEnd; ++I)
9320 Diag(I->first, I->second);
9321 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009322 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009323
9324 // When are coming out of an unevaluated context, clear out any
9325 // temporaries that we may have created as part of the evaluation of
9326 // the expression in that context: they aren't relevant because they
9327 // will never be constructed.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009328 if (Rec.Context == Unevaluated &&
Douglas Gregor2afce722009-11-26 00:44:06 +00009329 ExprTemporaries.size() > Rec.NumTemporaries)
9330 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9331 ExprTemporaries.end());
9332
9333 // Destroy the popped expression evaluation record.
9334 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009335}
Douglas Gregore0762c92009-06-19 23:52:42 +00009336
9337/// \brief Note that the given declaration was referenced in the source code.
9338///
9339/// This routine should be invoke whenever a given declaration is referenced
9340/// in the source code, and where that reference occurred. If this declaration
9341/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9342/// C99 6.9p3), then the declaration will be marked as used.
9343///
9344/// \param Loc the location where the declaration was referenced.
9345///
9346/// \param D the declaration that has been referenced by the source code.
9347void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9348 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00009349
Douglas Gregorc070cc62010-06-17 23:14:26 +00009350 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009351 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009352
Douglas Gregorb5352cf2009-10-08 21:35:42 +00009353 // Mark a parameter or variable declaration "used", regardless of whether we're in a
9354 // template or not. The reason for this is that unevaluated expressions
9355 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9356 // -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009357 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009358 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson2127ecc2010-10-22 23:37:08 +00009359 D->setUsed();
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009360 return;
9361 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009362
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009363 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9364 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009365
Douglas Gregore0762c92009-06-19 23:52:42 +00009366 // Do not mark anything as "used" within a dependent context; wait for
9367 // an instantiation.
9368 if (CurContext->isDependentContext())
9369 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009370
Douglas Gregor2afce722009-11-26 00:44:06 +00009371 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00009372 case Unevaluated:
9373 // We are in an expression that is not potentially evaluated; do nothing.
9374 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009375
Douglas Gregorac7610d2009-06-22 20:57:11 +00009376 case PotentiallyEvaluated:
9377 // We are in a potentially-evaluated expression, so this declaration is
9378 // "used"; handle this below.
9379 break;
Mike Stump1eb44332009-09-09 15:08:12 +00009380
Douglas Gregorac7610d2009-06-22 20:57:11 +00009381 case PotentiallyPotentiallyEvaluated:
9382 // We are in an expression that may be potentially evaluated; queue this
9383 // declaration reference until we know whether the expression is
9384 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00009385 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00009386 return;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009387
9388 case PotentiallyEvaluatedIfUsed:
9389 // Referenced declarations will only be used if the construct in the
9390 // containing expression is used.
9391 return;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009392 }
Mike Stump1eb44332009-09-09 15:08:12 +00009393
Douglas Gregore0762c92009-06-19 23:52:42 +00009394 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00009395 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009396 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00009397 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00009398 if (Constructor->getParent()->hasTrivialConstructor())
9399 return;
9400 if (!Constructor->isUsed(false))
9401 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00009402 } else if (Constructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00009403 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009404 if (!Constructor->isUsed(false))
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009405 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
9406 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009407
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009408 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009409 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009410 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009411 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009412 if (Destructor->isVirtual())
9413 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009414 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9415 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
9416 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009417 if (!MethodDecl->isUsed(false))
Douglas Gregor39957dc2010-05-01 15:04:51 +00009418 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009419 } else if (MethodDecl->isVirtual())
9420 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009421 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00009422 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall15e310a2011-02-19 02:53:41 +00009423 // Recursive functions should be marked when used from another function.
9424 if (CurContext == Function) return;
9425
Mike Stump1eb44332009-09-09 15:08:12 +00009426 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00009427 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00009428 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009429 bool AlreadyInstantiated = false;
9430 if (FunctionTemplateSpecializationInfo *SpecInfo
9431 = Function->getTemplateSpecializationInfo()) {
9432 if (SpecInfo->getPointOfInstantiation().isInvalid())
9433 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009434 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009435 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009436 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009437 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009438 = Function->getMemberSpecializationInfo()) {
9439 if (MSInfo->getPointOfInstantiation().isInvalid())
9440 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009441 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009442 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009443 AlreadyInstantiated = true;
9444 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009445
Douglas Gregor60406be2010-01-16 22:29:39 +00009446 if (!AlreadyInstantiated) {
9447 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9448 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9449 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9450 Loc));
9451 else
Chandler Carruth62c78d52010-08-25 08:44:16 +00009452 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor60406be2010-01-16 22:29:39 +00009453 }
John McCall15e310a2011-02-19 02:53:41 +00009454 } else {
9455 // Walk redefinitions, as some of them may be instantiable.
Gabor Greif40181c42010-08-28 00:16:06 +00009456 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9457 e(Function->redecls_end()); i != e; ++i) {
Gabor Greifbe9ebe32010-08-28 01:58:12 +00009458 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greif40181c42010-08-28 00:16:06 +00009459 MarkDeclarationReferenced(Loc, *i);
9460 }
John McCall15e310a2011-02-19 02:53:41 +00009461 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009462
John McCall15e310a2011-02-19 02:53:41 +00009463 // Keep track of used but undefined functions.
9464 if (!Function->isPure() && !Function->hasBody() &&
9465 Function->getLinkage() != ExternalLinkage) {
9466 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9467 if (old.isInvalid()) old = Loc;
9468 }
Argyrios Kyrtzidis58b52592010-08-25 10:34:54 +00009469
John McCall15e310a2011-02-19 02:53:41 +00009470 Function->setUsed(true);
Douglas Gregore0762c92009-06-19 23:52:42 +00009471 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009472 }
Mike Stump1eb44332009-09-09 15:08:12 +00009473
Douglas Gregore0762c92009-06-19 23:52:42 +00009474 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00009475 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00009476 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009477 Var->getInstantiatedFromStaticDataMember()) {
9478 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9479 assert(MSInfo && "Missing member specialization information?");
9480 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9481 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9482 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth62c78d52010-08-25 08:44:16 +00009483 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009484 }
9485 }
Mike Stump1eb44332009-09-09 15:08:12 +00009486
John McCall77efc682011-02-21 19:25:48 +00009487 // Keep track of used but undefined variables. We make a hole in
9488 // the warning for static const data members with in-line
9489 // initializers.
John McCall15e310a2011-02-19 02:53:41 +00009490 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall77efc682011-02-21 19:25:48 +00009491 && Var->getLinkage() != ExternalLinkage
9492 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall15e310a2011-02-19 02:53:41 +00009493 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9494 if (old.isInvalid()) old = Loc;
9495 }
Douglas Gregor7caa6822009-07-24 20:34:43 +00009496
Douglas Gregore0762c92009-06-19 23:52:42 +00009497 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00009498 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00009499 }
Douglas Gregore0762c92009-06-19 23:52:42 +00009500}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009501
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009502namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009503 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009504 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009505 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009506 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9507 Sema &S;
9508 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009509
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009510 public:
9511 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009512
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009513 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009514
9515 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9516 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009517 };
9518}
9519
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009520bool MarkReferencedDecls::TraverseTemplateArgument(
9521 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009522 if (Arg.getKind() == TemplateArgument::Declaration) {
9523 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9524 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009525
9526 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009527}
9528
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009529bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009530 if (ClassTemplateSpecializationDecl *Spec
9531 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9532 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +00009533 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009534 }
9535
Chandler Carruthe3e210c2010-06-10 10:31:57 +00009536 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009537}
9538
9539void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9540 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009541 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009542}
9543
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009544namespace {
9545 /// \brief Helper class that marks all of the declarations referenced by
9546 /// potentially-evaluated subexpressions as "referenced".
9547 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9548 Sema &S;
9549
9550 public:
9551 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9552
9553 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9554
9555 void VisitDeclRefExpr(DeclRefExpr *E) {
9556 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9557 }
9558
9559 void VisitMemberExpr(MemberExpr *E) {
9560 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009561 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009562 }
9563
9564 void VisitCXXNewExpr(CXXNewExpr *E) {
9565 if (E->getConstructor())
9566 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9567 if (E->getOperatorNew())
9568 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9569 if (E->getOperatorDelete())
9570 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009571 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009572 }
9573
9574 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9575 if (E->getOperatorDelete())
9576 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +00009577 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9578 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9579 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9580 S.MarkDeclarationReferenced(E->getLocStart(),
9581 S.LookupDestructor(Record));
9582 }
9583
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009584 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009585 }
9586
9587 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9588 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009589 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009590 }
9591
9592 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9593 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9594 }
Douglas Gregor102ff972010-10-19 17:17:35 +00009595
9596 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9597 Visit(E->getExpr());
9598 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009599 };
9600}
9601
9602/// \brief Mark any declarations that appear within this expression or any
9603/// potentially-evaluated subexpressions as "referenced".
9604void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9605 EvaluatedExprMarker(*this).Visit(E);
9606}
9607
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009608/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9609/// of the program being compiled.
9610///
9611/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009612/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009613/// possibility that the code will actually be executable. Code in sizeof()
9614/// expressions, code used only during overload resolution, etc., are not
9615/// potentially evaluated. This routine will suppress such diagnostics or,
9616/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009617/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009618/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009619///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009620/// This routine should be used for all diagnostics that describe the run-time
9621/// behavior of a program, such as passing a non-POD value through an ellipsis.
9622/// Failure to do so will likely result in spurious diagnostics or failures
9623/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek762696f2011-02-23 01:51:43 +00009624bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009625 const PartialDiagnostic &PD) {
9626 switch (ExprEvalContexts.back().Context ) {
9627 case Unevaluated:
9628 // The argument will never be evaluated, so don't complain.
9629 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009630
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009631 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009632 case PotentiallyEvaluatedIfUsed:
Ted Kremenek351ba912011-02-23 01:52:04 +00009633 if (stmt && getCurFunctionOrMethodDecl()) {
9634 FunctionScopes.back()->PossiblyUnreachableDiags.
9635 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9636 }
9637 else
9638 Diag(Loc, PD);
9639
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009640 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009641
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009642 case PotentiallyPotentiallyEvaluated:
9643 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9644 break;
9645 }
9646
9647 return false;
9648}
9649
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009650bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9651 CallExpr *CE, FunctionDecl *FD) {
9652 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9653 return false;
9654
9655 PartialDiagnostic Note =
9656 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9657 << FD->getDeclName() : PDiag();
9658 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009659
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009660 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009661 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009662 PDiag(diag::err_call_function_incomplete_return)
9663 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009664 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009665 << CE->getSourceRange(),
9666 std::make_pair(NoteLoc, Note)))
9667 return true;
9668
9669 return false;
9670}
9671
Douglas Gregor92c3a042011-01-19 16:50:08 +00009672// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +00009673// will prevent this condition from triggering, which is what we want.
9674void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9675 SourceLocation Loc;
9676
John McCalla52ef082009-11-11 02:41:58 +00009677 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +00009678 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +00009679
John McCall5a881bb2009-10-12 21:59:07 +00009680 if (isa<BinaryOperator>(E)) {
9681 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +00009682 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +00009683 return;
9684
Douglas Gregor92c3a042011-01-19 16:50:08 +00009685 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9686
John McCallc8d8ac52009-11-12 00:06:05 +00009687 // Greylist some idioms by putting them into a warning subcategory.
9688 if (ObjCMessageExpr *ME
9689 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9690 Selector Sel = ME->getSelector();
9691
John McCallc8d8ac52009-11-12 00:06:05 +00009692 // self = [<foo> init...]
Douglas Gregor813d8342011-02-18 22:29:55 +00009693 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +00009694 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9695
9696 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +00009697 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +00009698 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9699 }
John McCalla52ef082009-11-11 02:41:58 +00009700
John McCall5a881bb2009-10-12 21:59:07 +00009701 Loc = Op->getOperatorLoc();
9702 } else if (isa<CXXOperatorCallExpr>(E)) {
9703 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +00009704 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +00009705 return;
9706
Douglas Gregor92c3a042011-01-19 16:50:08 +00009707 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +00009708 Loc = Op->getOperatorLoc();
9709 } else {
9710 // Not an assignment.
9711 return;
9712 }
9713
John McCall5a881bb2009-10-12 21:59:07 +00009714 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00009715 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009716
Douglas Gregor55b38842010-04-14 16:09:52 +00009717 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +00009718
9719 if (IsOrAssign)
9720 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9721 << FixItHint::CreateReplacement(Loc, "!=");
9722 else
9723 Diag(Loc, diag::note_condition_assign_to_comparison)
9724 << FixItHint::CreateReplacement(Loc, "==");
9725
Douglas Gregor55b38842010-04-14 16:09:52 +00009726 Diag(Loc, diag::note_condition_assign_silence)
9727 << FixItHint::CreateInsertion(Open, "(")
9728 << FixItHint::CreateInsertion(Close, ")");
John McCall5a881bb2009-10-12 21:59:07 +00009729}
9730
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009731/// \brief Redundant parentheses over an equality comparison can indicate
9732/// that the user intended an assignment used as condition.
9733void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009734 // Don't warn if the parens came from a macro.
9735 SourceLocation parenLoc = parenE->getLocStart();
9736 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9737 return;
9738
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009739 Expr *E = parenE->IgnoreParens();
9740
9741 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +00009742 if (opE->getOpcode() == BO_EQ &&
9743 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9744 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009745 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +00009746
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009747 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
9748 Diag(Loc, diag::note_equality_comparison_to_assign)
9749 << FixItHint::CreateReplacement(Loc, "=");
9750 Diag(Loc, diag::note_equality_comparison_silence)
9751 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9752 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009753 }
9754}
9755
John McCall5a881bb2009-10-12 21:59:07 +00009756bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
9757 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009758 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9759 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +00009760
9761 if (!E->isTypeDependent()) {
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00009762 if (E->isBoundMemberFunction(Context))
9763 return Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9764 << E->getSourceRange();
9765
John McCallf6a16482010-12-04 03:47:34 +00009766 if (getLangOptions().CPlusPlus)
9767 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9768
9769 DefaultFunctionArrayLvalueConversion(E);
John McCallabc56c72010-12-04 06:09:13 +00009770
9771 QualType T = E->getType();
John McCallf6a16482010-12-04 03:47:34 +00009772 if (!T->isScalarType()) // C99 6.8.4.1p1
9773 return Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9774 << T << E->getSourceRange();
John McCall5a881bb2009-10-12 21:59:07 +00009775 }
9776
9777 return false;
9778}
Douglas Gregor586596f2010-05-06 17:25:47 +00009779
John McCall60d7b3a2010-08-24 06:29:42 +00009780ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9781 Expr *Sub) {
Douglas Gregoreecf38f2010-05-06 21:39:56 +00009782 if (!Sub)
Douglas Gregor586596f2010-05-06 17:25:47 +00009783 return ExprError();
9784
Douglas Gregorff331c12010-07-25 18:17:45 +00009785 if (CheckBooleanCondition(Sub, Loc))
Douglas Gregor586596f2010-05-06 17:25:47 +00009786 return ExprError();
Douglas Gregor586596f2010-05-06 17:25:47 +00009787
9788 return Owned(Sub);
9789}
John McCall2a984ca2010-10-12 00:20:44 +00009790
9791/// Check for operands with placeholder types and complain if found.
9792/// Returns true if there was an error and no recovery was possible.
9793ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) {
9794 const BuiltinType *BT = E->getType()->getAs<BuiltinType>();
9795 if (!BT || !BT->isPlaceholderType()) return Owned(E);
9796
9797 // If this is overload, check for a single overload.
Richard Smith34b41d92011-02-20 03:19:35 +00009798 assert(BT->getKind() == BuiltinType::Overload);
John McCall2a984ca2010-10-12 00:20:44 +00009799
Richard Smith34b41d92011-02-20 03:19:35 +00009800 if (FunctionDecl *Specialization
9801 = ResolveSingleFunctionTemplateSpecialization(E)) {
9802 // The access doesn't really matter in this case.
9803 DeclAccessPair Found = DeclAccessPair::make(Specialization,
9804 Specialization->getAccess());
9805 E = FixOverloadedFunctionReference(E, Found, Specialization);
9806 if (!E) return ExprError();
9807 return Owned(E);
John McCall2a984ca2010-10-12 00:20:44 +00009808 }
9809
Richard Smith34b41d92011-02-20 03:19:35 +00009810 Diag(Loc, diag::err_ovl_unresolvable) << E->getSourceRange();
John McCall2a984ca2010-10-12 00:20:44 +00009811 return ExprError();
9812}