blob: 760d5d58bc4c378a0e166fb105afc6aadfcdccc0 [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
Chris Lattner76a642f2009-02-15 22:43:40 +000078 // See if the decl is deprecated.
Benjamin Kramerce2d1862010-10-09 15:49:00 +000079 if (const DeprecatedAttr *DA = D->getAttr<DeprecatedAttr>())
Peter Collingbourne743b82b2011-01-02 19:53:12 +000080 EmitDeprecationWarning(D, DA->getMessage(), Loc, UnknownObjCClass);
Chris Lattner76a642f2009-02-15 22:43:40 +000081
Chris Lattnerffb93682009-10-25 17:21:40 +000082 // See if the decl is unavailable
Fariborz Jahanianc784dc12010-10-06 23:12:32 +000083 if (const UnavailableAttr *UA = D->getAttr<UnavailableAttr>()) {
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000084 if (UA->getMessage().empty()) {
Peter Collingbourne743b82b2011-01-02 19:53:12 +000085 if (!UnknownObjCClass)
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000086 Diag(Loc, diag::err_unavailable) << D->getDeclName();
87 else
88 Diag(Loc, diag::warn_unavailable_fwdclass_message)
89 << D->getDeclName();
90 }
91 else
Fariborz Jahanianc784dc12010-10-06 23:12:32 +000092 Diag(Loc, diag::err_unavailable_message)
Benjamin Kramerce2d1862010-10-09 15:49:00 +000093 << D->getDeclName() << UA->getMessage();
Chris Lattnerffb93682009-10-25 17:21:40 +000094 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
95 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000096
Douglas Gregor48f3bb92009-02-18 21:56:37 +000097 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000098 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000099 if (FD->isDeleted()) {
100 Diag(Loc, diag::err_deleted_function_use);
101 Diag(D->getLocation(), diag::note_unavailable_here) << true;
102 return true;
103 }
Douglas Gregor25d944a2009-02-24 04:26:15 +0000104 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000105
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000106 // Warn if this is used but marked unused.
107 if (D->hasAttr<UnusedAttr>())
108 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
109
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000110 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000111}
112
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000113/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +0000114/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000115/// attribute. It warns if call does not have the sentinel argument.
116///
117void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000118 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000119 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000120 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000121 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000122
123 // FIXME: In C++0x, if any of the arguments are parameter pack
124 // expansions, we can't check for the sentinel now.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000125 int sentinelPos = attr->getSentinel();
126 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +0000127
Mike Stump390b4cc2009-05-16 07:39:55 +0000128 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
129 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000130 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000131 bool warnNotEnoughArgs = false;
132 int isMethod = 0;
133 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
134 // skip over named parameters.
135 ObjCMethodDecl::param_iterator P, E = MD->param_end();
136 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
137 if (nullPos)
138 --nullPos;
139 else
140 ++i;
141 }
142 warnNotEnoughArgs = (P != E || i >= NumArgs);
143 isMethod = 1;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000144 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000145 // skip over named parameters.
146 ObjCMethodDecl::param_iterator P, E = FD->param_end();
147 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
148 if (nullPos)
149 --nullPos;
150 else
151 ++i;
152 }
153 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000154 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000155 // block or function pointer call.
156 QualType Ty = V->getType();
157 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000158 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000159 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
160 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000161 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
162 unsigned NumArgsInProto = Proto->getNumArgs();
163 unsigned k;
164 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
165 if (nullPos)
166 --nullPos;
167 else
168 ++i;
169 }
170 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
171 }
172 if (Ty->isBlockPointerType())
173 isMethod = 2;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000174 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000175 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000176 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000177 return;
178
179 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000180 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000181 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000182 return;
183 }
184 int sentinel = i;
185 while (sentinelPos > 0 && i < NumArgs-1) {
186 --sentinelPos;
187 ++i;
188 }
189 if (sentinelPos > 0) {
190 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000191 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000192 return;
193 }
194 while (i < NumArgs-1) {
195 ++i;
196 ++sentinel;
197 }
198 Expr *sentinelExpr = Args[sentinel];
John McCall8eb662e2010-05-06 23:53:00 +0000199 if (!sentinelExpr) return;
200 if (sentinelExpr->isTypeDependent()) return;
201 if (sentinelExpr->isValueDependent()) return;
Anders Carlsson343e6ff2010-11-05 15:21:33 +0000202
203 // nullptr_t is always treated as null.
204 if (sentinelExpr->getType()->isNullPtrType()) return;
205
Fariborz Jahanian9ccd7252010-07-14 16:37:51 +0000206 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall8eb662e2010-05-06 23:53:00 +0000207 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
208 Expr::NPC_ValueDependentIsNull))
209 return;
210
211 // Unfortunately, __null has type 'int'.
212 if (isa<GNUNullExpr>(sentinelExpr)) return;
213
214 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
215 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000216}
217
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000218SourceRange Sema::getExprRange(ExprTy *E) const {
219 Expr *Ex = (Expr *)E;
220 return Ex? Ex->getSourceRange() : SourceRange();
221}
222
Chris Lattnere7a2e912008-07-25 21:10:04 +0000223//===----------------------------------------------------------------------===//
224// Standard Promotions and Conversions
225//===----------------------------------------------------------------------===//
226
Chris Lattnere7a2e912008-07-25 21:10:04 +0000227/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
228void Sema::DefaultFunctionArrayConversion(Expr *&E) {
229 QualType Ty = E->getType();
230 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
231
Chris Lattnere7a2e912008-07-25 21:10:04 +0000232 if (Ty->isFunctionType())
Mike Stump1eb44332009-09-09 15:08:12 +0000233 ImpCastExprToType(E, Context.getPointerType(Ty),
John McCall2de56d12010-08-25 11:45:40 +0000234 CK_FunctionToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000235 else if (Ty->isArrayType()) {
236 // In C90 mode, arrays only promote to pointers if the array expression is
237 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
238 // type 'array of type' is converted to an expression that has type 'pointer
239 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
240 // that has type 'array of type' ...". The relevant change is "an lvalue"
241 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000242 //
243 // C++ 4.2p1:
244 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
245 // T" can be converted to an rvalue of type "pointer to T".
246 //
John McCall7eb0a9e2010-11-24 05:12:34 +0000247 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
Anders Carlsson112a0a82009-08-07 23:48:20 +0000248 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
John McCall2de56d12010-08-25 11:45:40 +0000249 CK_ArrayToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000250 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000251}
252
John McCall409fa9a2010-12-06 20:48:59 +0000253void Sema::DefaultLvalueConversion(Expr *&E) {
John McCall0ae287a2010-12-01 04:43:34 +0000254 // C++ [conv.lval]p1:
255 // A glvalue of a non-function, non-array type T can be
256 // converted to a prvalue.
John McCall409fa9a2010-12-06 20:48:59 +0000257 if (!E->isGLValue()) return;
John McCallf6a16482010-12-04 03:47:34 +0000258
John McCall409fa9a2010-12-06 20:48:59 +0000259 QualType T = E->getType();
260 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000261
John McCall409fa9a2010-12-06 20:48:59 +0000262 // Create a load out of an ObjCProperty l-value, if necessary.
263 if (E->getObjectKind() == OK_ObjCProperty) {
264 ConvertPropertyForRValue(E);
265 if (!E->isGLValue())
John McCallf6a16482010-12-04 03:47:34 +0000266 return;
Douglas Gregora873dfc2010-02-03 00:27:59 +0000267 }
John McCall409fa9a2010-12-06 20:48:59 +0000268
269 // We don't want to throw lvalue-to-rvalue casts on top of
270 // expressions of certain types in C++.
271 if (getLangOptions().CPlusPlus &&
272 (E->getType() == Context.OverloadTy ||
273 T->isDependentType() ||
274 T->isRecordType()))
275 return;
276
277 // The C standard is actually really unclear on this point, and
278 // DR106 tells us what the result should be but not why. It's
279 // generally best to say that void types just doesn't undergo
280 // lvalue-to-rvalue at all. Note that expressions of unqualified
281 // 'void' type are never l-values, but qualified void can be.
282 if (T->isVoidType())
283 return;
284
285 // C++ [conv.lval]p1:
286 // [...] If T is a non-class type, the type of the prvalue is the
287 // cv-unqualified version of T. Otherwise, the type of the
288 // rvalue is T.
289 //
290 // C99 6.3.2.1p2:
291 // If the lvalue has qualified type, the value has the unqualified
292 // version of the type of the lvalue; otherwise, the value has the
293 // type of the lvalue.
294 if (T.hasQualifiers())
295 T = T.getUnqualifiedType();
296
Ted Kremeneka0125d82011-02-16 01:57:07 +0000297 if (const ArraySubscriptExpr *ae = dyn_cast<ArraySubscriptExpr>(E))
298 CheckArrayAccess(ae);
299
John McCall409fa9a2010-12-06 20:48:59 +0000300 E = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
301 E, 0, VK_RValue);
302}
303
304void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
305 DefaultFunctionArrayConversion(E);
306 DefaultLvalueConversion(E);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000307}
308
309
Chris Lattnere7a2e912008-07-25 21:10:04 +0000310/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000311/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnere7a2e912008-07-25 21:10:04 +0000312/// sometimes surpressed. For example, the array->pointer conversion doesn't
313/// apply if the array is an argument to the sizeof or address (&) operators.
314/// In these instances, this routine should *not* be called.
John McCall0ae287a2010-12-01 04:43:34 +0000315Expr *Sema::UsualUnaryConversions(Expr *&E) {
316 // First, convert to an r-value.
317 DefaultFunctionArrayLvalueConversion(E);
318
319 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000320 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCall0ae287a2010-12-01 04:43:34 +0000321
322 // Try to perform integral promotions if the object has a theoretically
323 // promotable type.
324 if (Ty->isIntegralOrUnscopedEnumerationType()) {
325 // C99 6.3.1.1p2:
326 //
327 // The following may be used in an expression wherever an int or
328 // unsigned int may be used:
329 // - an object or expression with an integer type whose integer
330 // conversion rank is less than or equal to the rank of int
331 // and unsigned int.
332 // - A bit-field of type _Bool, int, signed int, or unsigned int.
333 //
334 // If an int can represent all values of the original type, the
335 // value is converted to an int; otherwise, it is converted to an
336 // unsigned int. These are called the integer promotions. All
337 // other types are unchanged by the integer promotions.
338
339 QualType PTy = Context.isPromotableBitField(E);
340 if (!PTy.isNull()) {
341 ImpCastExprToType(E, PTy, CK_IntegralCast);
342 return E;
343 }
344 if (Ty->isPromotableIntegerType()) {
345 QualType PT = Context.getPromotedIntegerType(Ty);
346 ImpCastExprToType(E, PT, CK_IntegralCast);
347 return E;
348 }
Eli Friedman04e83572009-08-20 04:21:42 +0000349 }
350
John McCall0ae287a2010-12-01 04:43:34 +0000351 return E;
Chris Lattnere7a2e912008-07-25 21:10:04 +0000352}
353
Chris Lattner05faf172008-07-25 22:25:12 +0000354/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000355/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000356/// double. All other argument types are converted by UsualUnaryConversions().
357void Sema::DefaultArgumentPromotion(Expr *&Expr) {
358 QualType Ty = Expr->getType();
359 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000360
John McCall40c29132010-12-06 18:36:11 +0000361 UsualUnaryConversions(Expr);
362
Chris Lattner05faf172008-07-25 22:25:12 +0000363 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000364 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John McCall40c29132010-12-06 18:36:11 +0000365 return ImpCastExprToType(Expr, Context.DoubleTy, CK_FloatingCast);
Chris Lattner05faf172008-07-25 22:25:12 +0000366}
367
Chris Lattner312531a2009-04-12 08:11:20 +0000368/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
369/// will warn if the resulting type is not a POD type, and rejects ObjC
370/// interfaces passed by value. This returns true if the argument type is
371/// completely illegal.
Chris Lattner40378332010-05-16 04:01:30 +0000372bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
373 FunctionDecl *FDecl) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000374 DefaultArgumentPromotion(Expr);
Mike Stump1eb44332009-09-09 15:08:12 +0000375
Chris Lattner40378332010-05-16 04:01:30 +0000376 // __builtin_va_start takes the second argument as a "varargs" argument, but
377 // it doesn't actually do anything with it. It doesn't need to be non-pod
378 // etc.
379 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
380 return false;
381
John McCallc12c5bb2010-05-15 11:32:37 +0000382 if (Expr->getType()->isObjCObjectType() &&
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000383 DiagRuntimeBehavior(Expr->getLocStart(),
384 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
385 << Expr->getType() << CT))
386 return true;
Douglas Gregor75b699a2009-12-12 07:25:49 +0000387
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000388 if (!Expr->getType()->isPODType() &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000389 DiagRuntimeBehavior(Expr->getLocStart(),
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000390 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
391 << Expr->getType() << CT))
392 return true;
Chris Lattner312531a2009-04-12 08:11:20 +0000393
394 return false;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000395}
396
Chris Lattnere7a2e912008-07-25 21:10:04 +0000397/// UsualArithmeticConversions - Performs various conversions that are common to
398/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000399/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000400/// responsible for emitting appropriate error diagnostics.
401/// FIXME: verify the conversion rules for "complex int" are consistent with
402/// GCC.
403QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
404 bool isCompAssign) {
Eli Friedmanab3a8522009-03-28 01:22:36 +0000405 if (!isCompAssign)
Chris Lattnere7a2e912008-07-25 21:10:04 +0000406 UsualUnaryConversions(lhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000407
408 UsualUnaryConversions(rhsExpr);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000409
Mike Stump1eb44332009-09-09 15:08:12 +0000410 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000411 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000412 QualType lhs =
413 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000414 QualType rhs =
Chris Lattnerb77792e2008-07-26 22:17:49 +0000415 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000416
417 // If both types are identical, no conversion is needed.
418 if (lhs == rhs)
419 return lhs;
420
421 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
422 // The caller can deal with this (e.g. pointer + int).
423 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
424 return lhs;
425
John McCallcf33b242010-11-13 08:17:45 +0000426 // Apply unary and bitfield promotions to the LHS's type.
427 QualType lhs_unpromoted = lhs;
428 if (lhs->isPromotableIntegerType())
429 lhs = Context.getPromotedIntegerType(lhs);
Eli Friedman04e83572009-08-20 04:21:42 +0000430 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000431 if (!LHSBitfieldPromoteTy.isNull())
432 lhs = LHSBitfieldPromoteTy;
John McCallcf33b242010-11-13 08:17:45 +0000433 if (lhs != lhs_unpromoted && !isCompAssign)
434 ImpCastExprToType(lhsExpr, lhs, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000435
John McCallcf33b242010-11-13 08:17:45 +0000436 // If both types are identical, no conversion is needed.
437 if (lhs == rhs)
438 return lhs;
439
440 // At this point, we have two different arithmetic types.
441
442 // Handle complex types first (C99 6.3.1.8p1).
443 bool LHSComplexFloat = lhs->isComplexType();
444 bool RHSComplexFloat = rhs->isComplexType();
445 if (LHSComplexFloat || RHSComplexFloat) {
446 // if we have an integer operand, the result is the complex type.
447
John McCall2bb5d002010-11-13 09:02:35 +0000448 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
449 if (rhs->isIntegerType()) {
450 QualType fp = cast<ComplexType>(lhs)->getElementType();
451 ImpCastExprToType(rhsExpr, fp, CK_IntegralToFloating);
452 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
453 } else {
454 assert(rhs->isComplexIntegerType());
John McCallf3ea8cf2010-11-14 08:17:51 +0000455 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000456 }
John McCallcf33b242010-11-13 08:17:45 +0000457 return lhs;
458 }
459
John McCall2bb5d002010-11-13 09:02:35 +0000460 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
461 if (!isCompAssign) {
462 // int -> float -> _Complex float
463 if (lhs->isIntegerType()) {
464 QualType fp = cast<ComplexType>(rhs)->getElementType();
465 ImpCastExprToType(lhsExpr, fp, CK_IntegralToFloating);
466 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
467 } else {
468 assert(lhs->isComplexIntegerType());
John McCallf3ea8cf2010-11-14 08:17:51 +0000469 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000470 }
471 }
John McCallcf33b242010-11-13 08:17:45 +0000472 return rhs;
473 }
474
475 // This handles complex/complex, complex/float, or float/complex.
476 // When both operands are complex, the shorter operand is converted to the
477 // type of the longer, and that is the type of the result. This corresponds
478 // to what is done when combining two real floating-point operands.
479 // The fun begins when size promotion occur across type domains.
480 // From H&S 6.3.4: When one operand is complex and the other is a real
481 // floating-point type, the less precise type is converted, within it's
482 // real or complex domain, to the precision of the other type. For example,
483 // when combining a "long double" with a "double _Complex", the
484 // "double _Complex" is promoted to "long double _Complex".
485 int order = Context.getFloatingTypeOrder(lhs, rhs);
486
487 // If both are complex, just cast to the more precise type.
488 if (LHSComplexFloat && RHSComplexFloat) {
489 if (order > 0) {
490 // _Complex float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000491 ImpCastExprToType(rhsExpr, lhs, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000492 return lhs;
493
494 } else if (order < 0) {
495 // _Complex float -> _Complex double
496 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000497 ImpCastExprToType(lhsExpr, rhs, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000498 return rhs;
499 }
500 return lhs;
501 }
502
503 // If just the LHS is complex, the RHS needs to be converted,
504 // and the LHS might need to be promoted.
505 if (LHSComplexFloat) {
506 if (order > 0) { // LHS is wider
507 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000508 QualType fp = cast<ComplexType>(lhs)->getElementType();
509 ImpCastExprToType(rhsExpr, fp, CK_FloatingCast);
510 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000511 return lhs;
512 }
513
514 // RHS is at least as wide. Find its corresponding complex type.
515 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
516
517 // double -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000518 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000519
520 // _Complex float -> _Complex double
521 if (!isCompAssign && order < 0)
John McCall2bb5d002010-11-13 09:02:35 +0000522 ImpCastExprToType(lhsExpr, result, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000523
524 return result;
525 }
526
527 // Just the RHS is complex, so the LHS needs to be converted
528 // and the RHS might need to be promoted.
529 assert(RHSComplexFloat);
530
531 if (order < 0) { // RHS is wider
532 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000533 if (!isCompAssign) {
Argyrios Kyrtzidise1889332011-01-18 18:49:33 +0000534 QualType fp = cast<ComplexType>(rhs)->getElementType();
535 ImpCastExprToType(lhsExpr, fp, CK_FloatingCast);
John McCall2bb5d002010-11-13 09:02:35 +0000536 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
537 }
John McCallcf33b242010-11-13 08:17:45 +0000538 return rhs;
539 }
540
541 // LHS is at least as wide. Find its corresponding complex type.
542 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
543
544 // double -> _Complex double
545 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000546 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000547
548 // _Complex float -> _Complex double
549 if (order > 0)
John McCall2bb5d002010-11-13 09:02:35 +0000550 ImpCastExprToType(rhsExpr, result, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000551
552 return result;
553 }
554
555 // Now handle "real" floating types (i.e. float, double, long double).
556 bool LHSFloat = lhs->isRealFloatingType();
557 bool RHSFloat = rhs->isRealFloatingType();
558 if (LHSFloat || RHSFloat) {
559 // If we have two real floating types, convert the smaller operand
560 // to the bigger result.
561 if (LHSFloat && RHSFloat) {
562 int order = Context.getFloatingTypeOrder(lhs, rhs);
563 if (order > 0) {
564 ImpCastExprToType(rhsExpr, lhs, CK_FloatingCast);
565 return lhs;
566 }
567
568 assert(order < 0 && "illegal float comparison");
569 if (!isCompAssign)
570 ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast);
571 return rhs;
572 }
573
574 // If we have an integer operand, the result is the real floating type.
575 if (LHSFloat) {
576 if (rhs->isIntegerType()) {
577 // Convert rhs to the lhs floating point type.
578 ImpCastExprToType(rhsExpr, lhs, CK_IntegralToFloating);
579 return lhs;
580 }
581
582 // Convert both sides to the appropriate complex float.
583 assert(rhs->isComplexIntegerType());
584 QualType result = Context.getComplexType(lhs);
585
586 // _Complex int -> _Complex float
John McCallf3ea8cf2010-11-14 08:17:51 +0000587 ImpCastExprToType(rhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000588
589 // float -> _Complex float
590 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000591 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000592
593 return result;
594 }
595
596 assert(RHSFloat);
597 if (lhs->isIntegerType()) {
598 // Convert lhs to the rhs floating point type.
599 if (!isCompAssign)
600 ImpCastExprToType(lhsExpr, rhs, CK_IntegralToFloating);
601 return rhs;
602 }
603
604 // Convert both sides to the appropriate complex float.
605 assert(lhs->isComplexIntegerType());
606 QualType result = Context.getComplexType(rhs);
607
608 // _Complex int -> _Complex float
609 if (!isCompAssign)
John McCallf3ea8cf2010-11-14 08:17:51 +0000610 ImpCastExprToType(lhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000611
612 // float -> _Complex float
John McCall2bb5d002010-11-13 09:02:35 +0000613 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000614
615 return result;
616 }
617
618 // Handle GCC complex int extension.
619 // FIXME: if the operands are (int, _Complex long), we currently
620 // don't promote the complex. Also, signedness?
621 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
622 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
623 if (lhsComplexInt && rhsComplexInt) {
624 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
625 rhsComplexInt->getElementType());
626 assert(order && "inequal types with equal element ordering");
627 if (order > 0) {
628 // _Complex int -> _Complex long
John McCall2bb5d002010-11-13 09:02:35 +0000629 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000630 return lhs;
631 }
632
633 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000634 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000635 return rhs;
636 } else if (lhsComplexInt) {
637 // int -> _Complex int
John McCall2bb5d002010-11-13 09:02:35 +0000638 ImpCastExprToType(rhsExpr, lhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000639 return lhs;
640 } else if (rhsComplexInt) {
641 // int -> _Complex int
642 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000643 ImpCastExprToType(lhsExpr, rhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000644 return rhs;
645 }
646
647 // Finally, we have two differing integer types.
648 // The rules for this case are in C99 6.3.1.8
649 int compare = Context.getIntegerTypeOrder(lhs, rhs);
650 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
651 rhsSigned = rhs->hasSignedIntegerRepresentation();
652 if (lhsSigned == rhsSigned) {
653 // Same signedness; use the higher-ranked type
654 if (compare >= 0) {
655 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
656 return lhs;
657 } else if (!isCompAssign)
658 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
659 return rhs;
660 } else if (compare != (lhsSigned ? 1 : -1)) {
661 // The unsigned type has greater than or equal rank to the
662 // signed type, so use the unsigned type
663 if (rhsSigned) {
664 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
665 return lhs;
666 } else if (!isCompAssign)
667 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
668 return rhs;
669 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
670 // The two types are different widths; if we are here, that
671 // means the signed type is larger than the unsigned type, so
672 // use the signed type.
673 if (lhsSigned) {
674 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
675 return lhs;
676 } else if (!isCompAssign)
677 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
678 return rhs;
679 } else {
680 // The signed type is higher-ranked than the unsigned type,
681 // but isn't actually any bigger (like unsigned int and long
682 // on most 32-bit systems). Use the unsigned type corresponding
683 // to the signed type.
684 QualType result =
685 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
686 ImpCastExprToType(rhsExpr, result, CK_IntegralCast);
687 if (!isCompAssign)
688 ImpCastExprToType(lhsExpr, result, CK_IntegralCast);
689 return result;
690 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000691}
692
Chris Lattnere7a2e912008-07-25 21:10:04 +0000693//===----------------------------------------------------------------------===//
694// Semantic Analysis for various Expression Types
695//===----------------------------------------------------------------------===//
696
697
Steve Narofff69936d2007-09-16 03:34:24 +0000698/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000699/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
700/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
701/// multiple tokens. However, the common case is that StringToks points to one
702/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000703///
John McCall60d7b3a2010-08-24 06:29:42 +0000704ExprResult
Sean Hunt6cf75022010-08-30 17:47:05 +0000705Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000706 assert(NumStringToks && "Must have at least one string!");
707
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000708 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000709 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000710 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000711
712 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
713 for (unsigned i = 0; i != NumStringToks; ++i)
714 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000715
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000716 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000717 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000718 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000719
720 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +0000721 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +0000722 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000723
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000724 // Get an array type for the string, according to C99 6.4.5. This includes
725 // the nul terminator character as well as the string length for pascal
726 // strings.
727 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000728 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000729 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000730
Reid Spencer5f016e22007-07-11 17:01:13 +0000731 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sean Hunt6cf75022010-08-30 17:47:05 +0000732 return Owned(StringLiteral::Create(Context, Literal.GetString(),
733 Literal.GetStringLength(),
734 Literal.AnyWide, StrTy,
735 &StringTokLocs[0],
736 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000737}
738
John McCall469a1eb2011-02-02 13:00:07 +0000739enum CaptureResult {
740 /// No capture is required.
741 CR_NoCapture,
742
743 /// A capture is required.
744 CR_Capture,
745
John McCall6b5a61b2011-02-07 10:33:21 +0000746 /// A by-ref capture is required.
747 CR_CaptureByRef,
748
John McCall469a1eb2011-02-02 13:00:07 +0000749 /// An error occurred when trying to capture the given variable.
750 CR_Error
751};
752
753/// Diagnose an uncapturable value reference.
Chris Lattner639e2d32008-10-20 05:16:36 +0000754///
John McCall469a1eb2011-02-02 13:00:07 +0000755/// \param var - the variable referenced
756/// \param DC - the context which we couldn't capture through
757static CaptureResult
John McCall6b5a61b2011-02-07 10:33:21 +0000758diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +0000759 VarDecl *var, DeclContext *DC) {
760 switch (S.ExprEvalContexts.back().Context) {
761 case Sema::Unevaluated:
762 // The argument will never be evaluated, so don't complain.
763 return CR_NoCapture;
Mike Stump1eb44332009-09-09 15:08:12 +0000764
John McCall469a1eb2011-02-02 13:00:07 +0000765 case Sema::PotentiallyEvaluated:
766 case Sema::PotentiallyEvaluatedIfUsed:
767 break;
Chris Lattner639e2d32008-10-20 05:16:36 +0000768
John McCall469a1eb2011-02-02 13:00:07 +0000769 case Sema::PotentiallyPotentiallyEvaluated:
770 // FIXME: delay these!
771 break;
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000772 }
Mike Stump1eb44332009-09-09 15:08:12 +0000773
John McCall469a1eb2011-02-02 13:00:07 +0000774 // Don't diagnose about capture if we're not actually in code right
775 // now; in general, there are more appropriate places that will
776 // diagnose this.
777 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
778
779 // This particular madness can happen in ill-formed default
780 // arguments; claim it's okay and let downstream code handle it.
781 if (isa<ParmVarDecl>(var) &&
782 S.CurContext == var->getDeclContext()->getParent())
783 return CR_NoCapture;
784
785 DeclarationName functionName;
786 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
787 functionName = fn->getDeclName();
788 // FIXME: variable from enclosing block that we couldn't capture from!
789
790 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
791 << var->getIdentifier() << functionName;
792 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
793 << var->getIdentifier();
794
795 return CR_Error;
Mike Stump1eb44332009-09-09 15:08:12 +0000796}
797
John McCall6b5a61b2011-02-07 10:33:21 +0000798/// There is a well-formed capture at a particular scope level;
799/// propagate it through all the nested blocks.
800static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
801 const BlockDecl::Capture &capture) {
802 VarDecl *var = capture.getVariable();
803
804 // Update all the inner blocks with the capture information.
805 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
806 i != e; ++i) {
807 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
808 innerBlock->Captures.push_back(
809 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
810 /*nested*/ true, capture.getCopyExpr()));
811 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
812 }
813
814 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
815}
816
817/// shouldCaptureValueReference - Determine if a reference to the
John McCall469a1eb2011-02-02 13:00:07 +0000818/// given value in the current context requires a variable capture.
819///
820/// This also keeps the captures set in the BlockScopeInfo records
821/// up-to-date.
John McCall6b5a61b2011-02-07 10:33:21 +0000822static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +0000823 ValueDecl *value) {
824 // Only variables ever require capture.
825 VarDecl *var = dyn_cast<VarDecl>(value);
John McCall76a40212011-02-09 01:13:10 +0000826 if (!var) return CR_NoCapture;
John McCall469a1eb2011-02-02 13:00:07 +0000827
828 // Fast path: variables from the current context never require capture.
829 DeclContext *DC = S.CurContext;
830 if (var->getDeclContext() == DC) return CR_NoCapture;
831
832 // Only variables with local storage require capture.
833 // FIXME: What about 'const' variables in C++?
834 if (!var->hasLocalStorage()) return CR_NoCapture;
835
836 // Otherwise, we need to capture.
837
838 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCall469a1eb2011-02-02 13:00:07 +0000839 do {
840 // Only blocks (and eventually C++0x closures) can capture; other
841 // scopes don't work.
842 if (!isa<BlockDecl>(DC))
John McCall6b5a61b2011-02-07 10:33:21 +0000843 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCall469a1eb2011-02-02 13:00:07 +0000844
845 BlockScopeInfo *blockScope =
846 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
847 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
848
John McCall6b5a61b2011-02-07 10:33:21 +0000849 // Check whether we've already captured it in this block. If so,
850 // we're done.
851 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
852 return propagateCapture(S, functionScopesIndex,
853 blockScope->Captures[indexPlus1 - 1]);
John McCall469a1eb2011-02-02 13:00:07 +0000854
855 functionScopesIndex--;
856 DC = cast<BlockDecl>(DC)->getDeclContext();
857 } while (var->getDeclContext() != DC);
858
John McCall6b5a61b2011-02-07 10:33:21 +0000859 // Okay, we descended all the way to the block that defines the variable.
860 // Actually try to capture it.
861 QualType type = var->getType();
862
863 // Prohibit variably-modified types.
864 if (type->isVariablyModifiedType()) {
865 S.Diag(loc, diag::err_ref_vm_type);
866 S.Diag(var->getLocation(), diag::note_declared_at);
867 return CR_Error;
868 }
869
870 // Prohibit arrays, even in __block variables, but not references to
871 // them.
872 if (type->isArrayType()) {
873 S.Diag(loc, diag::err_ref_array_type);
874 S.Diag(var->getLocation(), diag::note_declared_at);
875 return CR_Error;
876 }
877
878 S.MarkDeclarationReferenced(loc, var);
879
880 // The BlocksAttr indicates the variable is bound by-reference.
881 bool byRef = var->hasAttr<BlocksAttr>();
882
883 // Build a copy expression.
884 Expr *copyExpr = 0;
885 if (!byRef && S.getLangOptions().CPlusPlus &&
886 !type->isDependentType() && type->isStructureOrClassType()) {
887 // According to the blocks spec, the capture of a variable from
888 // the stack requires a const copy constructor. This is not true
889 // of the copy/move done to move a __block variable to the heap.
890 type.addConst();
891
892 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
893 ExprResult result =
894 S.PerformCopyInitialization(
895 InitializedEntity::InitializeBlock(var->getLocation(),
896 type, false),
897 loc, S.Owned(declRef));
898
899 // Build a full-expression copy expression if initialization
900 // succeeded and used a non-trivial constructor. Recover from
901 // errors by pretending that the copy isn't necessary.
902 if (!result.isInvalid() &&
903 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
904 result = S.MaybeCreateExprWithCleanups(result);
905 copyExpr = result.take();
906 }
907 }
908
909 // We're currently at the declarer; go back to the closure.
910 functionScopesIndex++;
911 BlockScopeInfo *blockScope =
912 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
913
914 // Build a valid capture in this scope.
915 blockScope->Captures.push_back(
916 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
917 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
918
919 // Propagate that to inner captures if necessary.
920 return propagateCapture(S, functionScopesIndex,
921 blockScope->Captures.back());
922}
923
924static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
925 const DeclarationNameInfo &NameInfo,
926 bool byRef) {
927 assert(isa<VarDecl>(vd) && "capturing non-variable");
928
929 VarDecl *var = cast<VarDecl>(vd);
930 assert(var->hasLocalStorage() && "capturing non-local");
931 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
932
933 QualType exprType = var->getType().getNonReferenceType();
934
935 BlockDeclRefExpr *BDRE;
936 if (!byRef) {
937 // The variable will be bound by copy; make it const within the
938 // closure, but record that this was done in the expression.
939 bool constAdded = !exprType.isConstQualified();
940 exprType.addConst();
941
942 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
943 NameInfo.getLoc(), false,
944 constAdded);
945 } else {
946 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
947 NameInfo.getLoc(), true);
948 }
949
950 return S.Owned(BDRE);
John McCall469a1eb2011-02-02 13:00:07 +0000951}
Chris Lattner639e2d32008-10-20 05:16:36 +0000952
John McCall60d7b3a2010-08-24 06:29:42 +0000953ExprResult
John McCallf89e55a2010-11-18 06:31:45 +0000954Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +0000955 SourceLocation Loc,
956 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000957 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +0000958 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +0000959}
960
John McCall76a40212011-02-09 01:13:10 +0000961/// BuildDeclRefExpr - Build an expression that references a
962/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +0000963ExprResult
John McCall76a40212011-02-09 01:13:10 +0000964Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +0000965 const DeclarationNameInfo &NameInfo,
966 const CXXScopeSpec *SS) {
John McCall76a40212011-02-09 01:13:10 +0000967 if (Ty == Context.UndeducedAutoTy) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000968 Diag(NameInfo.getLoc(),
Mike Stump1eb44332009-09-09 15:08:12 +0000969 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlssone2bb2242009-06-26 19:16:07 +0000970 << D->getDeclName();
971 return ExprError();
972 }
Mike Stump1eb44332009-09-09 15:08:12 +0000973
Abramo Bagnara25777432010-08-11 22:01:17 +0000974 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +0000975
John McCall7eb0a9e2010-11-24 05:12:34 +0000976 Expr *E = DeclRefExpr::Create(Context,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000977 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
John McCall7eb0a9e2010-11-24 05:12:34 +0000978 SS? SS->getRange() : SourceRange(),
979 D, NameInfo, Ty, VK);
980
981 // Just in case we're building an illegal pointer-to-member.
982 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
983 E->setObjectKind(OK_BitField);
984
985 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +0000986}
987
John McCalldfa1edb2010-11-23 20:48:44 +0000988static ExprResult
989BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
990 const CXXScopeSpec &SS, FieldDecl *Field,
991 DeclAccessPair FoundDecl,
992 const DeclarationNameInfo &MemberNameInfo);
993
John McCall60d7b3a2010-08-24 06:29:42 +0000994ExprResult
John McCall5808ce42011-02-03 08:15:49 +0000995Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
996 SourceLocation loc,
997 IndirectFieldDecl *indirectField,
998 Expr *baseObjectExpr,
999 SourceLocation opLoc) {
1000 // First, build the expression that refers to the base object.
1001
1002 bool baseObjectIsPointer = false;
1003 Qualifiers baseQuals;
1004
1005 // Case 1: the base of the indirect field is not a field.
1006 VarDecl *baseVariable = indirectField->getVarDecl();
1007 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 =
1020 BuildDeclarationNameExpr(SS, baseNameInfo, baseVariable);
1021 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,
1081 SS, field, foundDecl,
1082 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
1091 for (; FI != FEnd; FI++) {
1092 FieldDecl *field = cast<FieldDecl>(*FI);
1093
1094 // FIXME: these are somewhat meaningless
1095 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1096 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
1097 CXXScopeSpec memberSS;
1098
1099 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
1100 memberSS, field, foundDecl, memberNameInfo)
1101 .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);
1352 CXXDependentScopeMemberExpr *DepExpr =
1353 CXXDependentScopeMemberExpr::Create(
1354 Context, DepThis, DepThisType, true, SourceLocation(),
1355 ULE->getQualifier(), ULE->getQualifierRange(), NULL,
1356 R.getLookupNameInfo(), &TList);
1357 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +00001358 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001359 // FIXME: we should be able to handle this case too. It is correct
1360 // to add this-> here. This is a workaround for PR7947.
1361 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +00001362 }
Nick Lewycky03d98c52010-07-06 19:51:49 +00001363 } else {
John McCall578b69b2009-12-16 08:11:27 +00001364 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001365 }
John McCall578b69b2009-12-16 08:11:27 +00001366
1367 // Do we really want to note all of these?
1368 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1369 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1370
1371 // Tell the callee to try to recover.
1372 return false;
1373 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001374
1375 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001376 }
1377 }
1378
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001379 // We didn't find anything, so try to correct for a typo.
Douglas Gregoraaf87162010-04-14 20:04:41 +00001380 DeclarationName Corrected;
Daniel Dunbardc32cdf2010-06-02 15:46:52 +00001381 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001382 if (!R.empty()) {
1383 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1384 if (SS.isEmpty())
1385 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1386 << FixItHint::CreateReplacement(R.getNameLoc(),
1387 R.getLookupName().getAsString());
1388 else
1389 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1390 << Name << computeDeclContext(SS, false) << R.getLookupName()
1391 << SS.getRange()
1392 << FixItHint::CreateReplacement(R.getNameLoc(),
1393 R.getLookupName().getAsString());
1394 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1395 Diag(ND->getLocation(), diag::note_previous_decl)
1396 << ND->getDeclName();
1397
1398 // Tell the callee to try to recover.
1399 return false;
1400 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001401
Douglas Gregoraaf87162010-04-14 20:04:41 +00001402 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1403 // FIXME: If we ended up with a typo for a type name or
1404 // Objective-C class name, we're in trouble because the parser
1405 // is in the wrong place to recover. Suggest the typo
1406 // correction, but don't make it a fix-it since we're not going
1407 // to recover well anyway.
1408 if (SS.isEmpty())
1409 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1410 else
1411 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1412 << Name << computeDeclContext(SS, false) << R.getLookupName()
1413 << SS.getRange();
1414
1415 // Don't try to recover; it won't work.
1416 return true;
1417 }
1418 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001419 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001420 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001421 if (SS.isEmpty())
Douglas Gregoraaf87162010-04-14 20:04:41 +00001422 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001423 else
Douglas Gregord203a162010-01-01 00:15:04 +00001424 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001425 << Name << computeDeclContext(SS, false) << Corrected
1426 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001427 return true;
1428 }
Douglas Gregord203a162010-01-01 00:15:04 +00001429 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001430 }
1431
1432 // Emit a special diagnostic for failed member lookups.
1433 // FIXME: computing the declaration context might fail here (?)
1434 if (!SS.isEmpty()) {
1435 Diag(R.getNameLoc(), diag::err_no_member)
1436 << Name << computeDeclContext(SS, false)
1437 << SS.getRange();
1438 return true;
1439 }
1440
John McCall578b69b2009-12-16 08:11:27 +00001441 // Give up, we can't recover.
1442 Diag(R.getNameLoc(), diagnostic) << Name;
1443 return true;
1444}
1445
Douglas Gregorca45da02010-11-02 20:36:02 +00001446ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1447 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001448 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1449 if (!IDecl)
1450 return 0;
1451 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1452 if (!ClassImpDecl)
1453 return 0;
Douglas Gregorca45da02010-11-02 20:36:02 +00001454 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001455 if (!property)
1456 return 0;
1457 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregorca45da02010-11-02 20:36:02 +00001458 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1459 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001460 return 0;
1461 return property;
1462}
1463
Douglas Gregorca45da02010-11-02 20:36:02 +00001464bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1465 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1466 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1467 if (!IDecl)
1468 return false;
1469 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1470 if (!ClassImpDecl)
1471 return false;
1472 if (ObjCPropertyImplDecl *PIDecl
1473 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1474 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1475 PIDecl->getPropertyIvarDecl())
1476 return false;
1477
1478 return true;
1479}
1480
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001481static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001482 LookupResult &Lookup,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001483 IdentifierInfo *II,
1484 SourceLocation NameLoc) {
1485 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001486 bool LookForIvars;
1487 if (Lookup.empty())
1488 LookForIvars = true;
1489 else if (CurMeth->isClassMethod())
1490 LookForIvars = false;
1491 else
1492 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahaniand0fbadd2011-01-26 00:57:01 +00001493 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1494 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001495 if (!LookForIvars)
1496 return 0;
1497
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001498 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1499 if (!IDecl)
1500 return 0;
1501 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001502 if (!ClassImpDecl)
1503 return 0;
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001504 bool DynamicImplSeen = false;
1505 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1506 if (!property)
1507 return 0;
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001508 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001509 DynamicImplSeen =
1510 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001511 // property implementation has a designated ivar. No need to assume a new
1512 // one.
1513 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1514 return 0;
1515 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001516 if (!DynamicImplSeen) {
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001517 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1518 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001519 NameLoc,
1520 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian75049662010-12-15 23:29:04 +00001521 ObjCIvarDecl::Private,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001522 (Expr *)0, true);
1523 ClassImpDecl->addDecl(Ivar);
1524 IDecl->makeDeclVisibleInContext(Ivar, false);
1525 property->setPropertyIvarDecl(Ivar);
1526 return Ivar;
1527 }
1528 return 0;
1529}
1530
John McCall60d7b3a2010-08-24 06:29:42 +00001531ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001532 CXXScopeSpec &SS,
1533 UnqualifiedId &Id,
1534 bool HasTrailingLParen,
1535 bool isAddressOfOperand) {
John McCallf7a1a742009-11-24 19:00:30 +00001536 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1537 "cannot be direct & operand and have a trailing lparen");
1538
1539 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001540 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001541
John McCall129e2df2009-11-30 22:42:35 +00001542 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001543
1544 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001545 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001546 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnara25777432010-08-11 22:01:17 +00001547 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001548
Abramo Bagnara25777432010-08-11 22:01:17 +00001549 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001550 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001551 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001552
John McCallf7a1a742009-11-24 19:00:30 +00001553 // C++ [temp.dep.expr]p3:
1554 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001555 // -- an identifier that was declared with a dependent type,
1556 // (note: handled after lookup)
1557 // -- a template-id that is dependent,
1558 // (note: handled in BuildTemplateIdExpr)
1559 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001560 // -- a nested-name-specifier that contains a class-name that
1561 // names a dependent type.
1562 // Determine whether this is a member of an unknown specialization;
1563 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001564 bool DependentID = false;
1565 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1566 Name.getCXXNameType()->isDependentType()) {
1567 DependentID = true;
1568 } else if (SS.isSet()) {
1569 DeclContext *DC = computeDeclContext(SS, false);
1570 if (DC) {
1571 if (RequireCompleteDeclContext(SS, DC))
1572 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001573 } else {
1574 DependentID = true;
1575 }
1576 }
1577
1578 if (DependentID) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001579 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001580 TemplateArgs);
1581 }
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001582 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001583 // Perform the required lookup.
Abramo Bagnara25777432010-08-11 22:01:17 +00001584 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001585 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001586 // Lookup the template name again to correctly establish the context in
1587 // which it was found. This is really unfortunate as we already did the
1588 // lookup to determine that it was a template name in the first place. If
1589 // this becomes a performance hit, we can work harder to preserve those
1590 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001591 bool MemberOfUnknownSpecialization;
1592 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1593 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001594
1595 if (MemberOfUnknownSpecialization ||
1596 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1597 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1598 TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001599 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001600 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001601 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001602
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001603 // If the result might be in a dependent base class, this is a dependent
1604 // id-expression.
1605 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1606 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1607 TemplateArgs);
1608
John McCallf7a1a742009-11-24 19:00:30 +00001609 // If this reference is in an Objective-C method, then we need to do
1610 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001611 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001612 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001613 if (E.isInvalid())
1614 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001615
John McCallf7a1a742009-11-24 19:00:30 +00001616 Expr *Ex = E.takeAs<Expr>();
1617 if (Ex) return Owned(Ex);
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001618 // Synthesize ivars lazily
Fariborz Jahaniane776f882011-01-03 18:08:02 +00001619 if (getLangOptions().ObjCDefaultSynthProperties &&
1620 getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahaniande267602010-11-17 19:41:23 +00001621 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1622 if (const ObjCPropertyDecl *Property =
1623 canSynthesizeProvisionalIvar(II)) {
1624 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1625 Diag(Property->getLocation(), diag::note_property_declare);
1626 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001627 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1628 isAddressOfOperand);
Fariborz Jahaniande267602010-11-17 19:41:23 +00001629 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001630 }
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001631 // for further use, this must be set to false if in class method.
1632 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001633 }
Chris Lattner8a934232008-03-31 00:36:02 +00001634 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001635
John McCallf7a1a742009-11-24 19:00:30 +00001636 if (R.isAmbiguous())
1637 return ExprError();
1638
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001639 // Determine whether this name might be a candidate for
1640 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001641 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001642
John McCallf7a1a742009-11-24 19:00:30 +00001643 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001644 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001645 // in C90, extension in C99, forbidden in C++).
1646 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1647 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1648 if (D) R.addDecl(D);
1649 }
1650
1651 // If this name wasn't predeclared and if this is not a function
1652 // call, diagnose the problem.
1653 if (R.empty()) {
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001654 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001655 return ExprError();
1656
1657 assert(!R.empty() &&
1658 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001659
1660 // If we found an Objective-C instance variable, let
1661 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001662 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001663 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1664 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001665 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001666 assert(E.isInvalid() || E.get());
1667 return move(E);
1668 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001669 }
1670 }
Mike Stump1eb44332009-09-09 15:08:12 +00001671
John McCallf7a1a742009-11-24 19:00:30 +00001672 // This is guaranteed from this point on.
1673 assert(!R.empty() || ADL);
1674
1675 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001676 if (getLangOptions().ObjCNonFragileABI && IvarLookupFollowUp &&
Fariborz Jahaniane776f882011-01-03 18:08:02 +00001677 !(getLangOptions().ObjCDefaultSynthProperties &&
1678 getLangOptions().ObjCNonFragileABI2) &&
Fariborz Jahanianb1d58e32010-07-29 16:53:53 +00001679 Var->isFileVarDecl()) {
Douglas Gregorca45da02010-11-02 20:36:02 +00001680 ObjCPropertyDecl *Property = canSynthesizeProvisionalIvar(II);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001681 if (Property) {
1682 Diag(NameLoc, diag::warn_ivar_variable_conflict) << Var->getDeclName();
1683 Diag(Property->getLocation(), diag::note_property_declare);
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001684 Diag(Var->getLocation(), diag::note_global_declared_at);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001685 }
1686 }
Douglas Gregor751f9a42009-06-30 15:47:41 +00001687 }
Mike Stump1eb44332009-09-09 15:08:12 +00001688
John McCallaa81e162009-12-01 22:10:20 +00001689 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001690 // C++ [class.mfct.non-static]p3:
1691 // When an id-expression that is not part of a class member access
1692 // syntax and not used to form a pointer to member is used in the
1693 // body of a non-static member function of class X, if name lookup
1694 // resolves the name in the id-expression to a non-static non-type
1695 // member of some class C, the id-expression is transformed into a
1696 // class member access expression using (*this) as the
1697 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001698 //
1699 // But we don't actually need to do this for '&' operands if R
1700 // resolved to a function or overloaded function set, because the
1701 // expression is ill-formed if it actually works out to be a
1702 // non-static member function:
1703 //
1704 // C++ [expr.ref]p4:
1705 // Otherwise, if E1.E2 refers to a non-static member function. . .
1706 // [t]he expression can be used only as the left-hand operand of a
1707 // member function call.
1708 //
1709 // There are other safeguards against such uses, but it's important
1710 // to get this right here so that we don't end up making a
1711 // spuriously dependent expression if we're inside a dependent
1712 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001713 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001714 bool MightBeImplicitMember;
1715 if (!isAddressOfOperand)
1716 MightBeImplicitMember = true;
1717 else if (!SS.isEmpty())
1718 MightBeImplicitMember = false;
1719 else if (R.isOverloadedResult())
1720 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001721 else if (R.isUnresolvableResult())
1722 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001723 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001724 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1725 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001726
1727 if (MightBeImplicitMember)
John McCall3b4294e2009-12-16 12:17:52 +00001728 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001729 }
1730
John McCallf7a1a742009-11-24 19:00:30 +00001731 if (TemplateArgs)
1732 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001733
John McCallf7a1a742009-11-24 19:00:30 +00001734 return BuildDeclarationNameExpr(SS, R, ADL);
1735}
1736
John McCall3b4294e2009-12-16 12:17:52 +00001737/// Builds an expression which might be an implicit member expression.
John McCall60d7b3a2010-08-24 06:29:42 +00001738ExprResult
John McCall3b4294e2009-12-16 12:17:52 +00001739Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1740 LookupResult &R,
1741 const TemplateArgumentListInfo *TemplateArgs) {
1742 switch (ClassifyImplicitMemberAccess(*this, R)) {
1743 case IMA_Instance:
1744 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1745
John McCall3b4294e2009-12-16 12:17:52 +00001746 case IMA_Mixed:
1747 case IMA_Mixed_Unrelated:
1748 case IMA_Unresolved:
1749 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1750
1751 case IMA_Static:
1752 case IMA_Mixed_StaticContext:
1753 case IMA_Unresolved_StaticContext:
1754 if (TemplateArgs)
1755 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1756 return BuildDeclarationNameExpr(SS, R, false);
1757
1758 case IMA_Error_StaticContext:
1759 case IMA_Error_Unrelated:
John McCall5808ce42011-02-03 08:15:49 +00001760 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
1761 R.getLookupNameInfo());
John McCall3b4294e2009-12-16 12:17:52 +00001762 return ExprError();
1763 }
1764
1765 llvm_unreachable("unexpected instance member access kind");
1766 return ExprError();
1767}
1768
John McCall129e2df2009-11-30 22:42:35 +00001769/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1770/// declaration name, generally during template instantiation.
1771/// There's a large number of things which don't need to be done along
1772/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001773ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001774Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001775 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001776 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001777 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00001778 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00001779
John McCall77bb1aa2010-05-01 00:40:08 +00001780 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001781 return ExprError();
1782
Abramo Bagnara25777432010-08-11 22:01:17 +00001783 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001784 LookupQualifiedName(R, DC);
1785
1786 if (R.isAmbiguous())
1787 return ExprError();
1788
1789 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001790 Diag(NameInfo.getLoc(), diag::err_no_member)
1791 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001792 return ExprError();
1793 }
1794
1795 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1796}
1797
1798/// LookupInObjCMethod - The parser has read a name in, and Sema has
1799/// detected that we're currently inside an ObjC method. Perform some
1800/// additional lookup.
1801///
1802/// Ideally, most of this would be done by lookup, but there's
1803/// actually quite a lot of extra work involved.
1804///
1805/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001806ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001807Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001808 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001809 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001810 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001811
John McCallf7a1a742009-11-24 19:00:30 +00001812 // There are two cases to handle here. 1) scoped lookup could have failed,
1813 // in which case we should look for an ivar. 2) scoped lookup could have
1814 // found a decl, but that decl is outside the current instance method (i.e.
1815 // a global variable). In these two cases, we do a lookup for an ivar with
1816 // this name, if the lookup sucedes, we replace it our current decl.
1817
1818 // If we're in a class method, we don't normally want to look for
1819 // ivars. But if we don't find anything else, and there's an
1820 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001821 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001822
1823 bool LookForIvars;
1824 if (Lookup.empty())
1825 LookForIvars = true;
1826 else if (IsClassMethod)
1827 LookForIvars = false;
1828 else
1829 LookForIvars = (Lookup.isSingleResult() &&
1830 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001831 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001832 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001833 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001834 ObjCInterfaceDecl *ClassDeclared;
1835 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1836 // Diagnose using an ivar in a class method.
1837 if (IsClassMethod)
1838 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1839 << IV->getDeclName());
1840
1841 // If we're referencing an invalid decl, just return this as a silent
1842 // error node. The error diagnostic was already emitted on the decl.
1843 if (IV->isInvalidDecl())
1844 return ExprError();
1845
1846 // Check if referencing a field with __attribute__((deprecated)).
1847 if (DiagnoseUseOfDecl(IV, Loc))
1848 return ExprError();
1849
1850 // Diagnose the use of an ivar outside of the declaring class.
1851 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1852 ClassDeclared != IFace)
1853 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1854
1855 // FIXME: This should use a new expr for a direct reference, don't
1856 // turn this into Self->ivar, just return a BareIVarExpr or something.
1857 IdentifierInfo &II = Context.Idents.get("self");
1858 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001859 SelfName.setIdentifier(&II, SourceLocation());
John McCallf7a1a742009-11-24 19:00:30 +00001860 CXXScopeSpec SelfScopeSpec;
John McCall60d7b3a2010-08-24 06:29:42 +00001861 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001862 SelfName, false, false);
1863 if (SelfExpr.isInvalid())
1864 return ExprError();
1865
John McCall409fa9a2010-12-06 20:48:59 +00001866 Expr *SelfE = SelfExpr.take();
1867 DefaultLvalueConversion(SelfE);
1868
John McCallf7a1a742009-11-24 19:00:30 +00001869 MarkDeclarationReferenced(Loc, IV);
1870 return Owned(new (Context)
1871 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John McCall409fa9a2010-12-06 20:48:59 +00001872 SelfE, true, true));
John McCallf7a1a742009-11-24 19:00:30 +00001873 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001874 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001875 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00001876 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001877 ObjCInterfaceDecl *ClassDeclared;
1878 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1879 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1880 IFace == ClassDeclared)
1881 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1882 }
1883 }
1884
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001885 if (Lookup.empty() && II && AllowBuiltinCreation) {
1886 // FIXME. Consolidate this with similar code in LookupName.
1887 if (unsigned BuiltinID = II->getBuiltinID()) {
1888 if (!(getLangOptions().CPlusPlus &&
1889 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1890 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1891 S, Lookup.isForRedeclaration(),
1892 Lookup.getNameLoc());
1893 if (D) Lookup.addDecl(D);
1894 }
1895 }
1896 }
John McCallf7a1a742009-11-24 19:00:30 +00001897 // Sentinel value saying that we didn't do anything special.
1898 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001899}
John McCallba135432009-11-21 08:51:07 +00001900
John McCall6bb80172010-03-30 21:47:33 +00001901/// \brief Cast a base object to a member's actual type.
1902///
1903/// Logically this happens in three phases:
1904///
1905/// * First we cast from the base type to the naming class.
1906/// The naming class is the class into which we were looking
1907/// when we found the member; it's the qualifier type if a
1908/// qualifier was provided, and otherwise it's the base type.
1909///
1910/// * Next we cast from the naming class to the declaring class.
1911/// If the member we found was brought into a class's scope by
1912/// a using declaration, this is that class; otherwise it's
1913/// the class declaring the member.
1914///
1915/// * Finally we cast from the declaring class to the "true"
1916/// declaring class of the member. This conversion does not
1917/// obey access control.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001918bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00001919Sema::PerformObjectMemberConversion(Expr *&From,
1920 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00001921 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001922 NamedDecl *Member) {
1923 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1924 if (!RD)
1925 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001926
Douglas Gregor5fccd362010-03-03 23:55:11 +00001927 QualType DestRecordType;
1928 QualType DestType;
1929 QualType FromRecordType;
1930 QualType FromType = From->getType();
1931 bool PointerConversions = false;
1932 if (isa<FieldDecl>(Member)) {
1933 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001934
Douglas Gregor5fccd362010-03-03 23:55:11 +00001935 if (FromType->getAs<PointerType>()) {
1936 DestType = Context.getPointerType(DestRecordType);
1937 FromRecordType = FromType->getPointeeType();
1938 PointerConversions = true;
1939 } else {
1940 DestType = DestRecordType;
1941 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001942 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001943 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1944 if (Method->isStatic())
1945 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001946
Douglas Gregor5fccd362010-03-03 23:55:11 +00001947 DestType = Method->getThisType(Context);
1948 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001949
Douglas Gregor5fccd362010-03-03 23:55:11 +00001950 if (FromType->getAs<PointerType>()) {
1951 FromRecordType = FromType->getPointeeType();
1952 PointerConversions = true;
1953 } else {
1954 FromRecordType = FromType;
1955 DestType = DestRecordType;
1956 }
1957 } else {
1958 // No conversion necessary.
1959 return false;
1960 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001961
Douglas Gregor5fccd362010-03-03 23:55:11 +00001962 if (DestType->isDependentType() || FromType->isDependentType())
1963 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001964
Douglas Gregor5fccd362010-03-03 23:55:11 +00001965 // If the unqualified types are the same, no conversion is necessary.
1966 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1967 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001968
John McCall6bb80172010-03-30 21:47:33 +00001969 SourceRange FromRange = From->getSourceRange();
1970 SourceLocation FromLoc = FromRange.getBegin();
1971
John McCall5baba9d2010-08-25 10:28:54 +00001972 ExprValueKind VK = CastCategory(From);
Sebastian Redl906082e2010-07-20 04:20:21 +00001973
Douglas Gregor5fccd362010-03-03 23:55:11 +00001974 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001975 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00001976 // class name.
1977 //
1978 // If the member was a qualified name and the qualified referred to a
1979 // specific base subobject type, we'll cast to that intermediate type
1980 // first and then to the object in which the member is declared. That allows
1981 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1982 //
1983 // class Base { public: int x; };
1984 // class Derived1 : public Base { };
1985 // class Derived2 : public Base { };
1986 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1987 //
1988 // void VeryDerived::f() {
1989 // x = 17; // error: ambiguous base subobjects
1990 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1991 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001992 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00001993 QualType QType = QualType(Qualifier->getAsType(), 0);
1994 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1995 assert(QType->isRecordType() && "lookup done with non-record type");
1996
1997 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1998
1999 // In C++98, the qualifier type doesn't actually have to be a base
2000 // type of the object type, in which case we just ignore it.
2001 // Otherwise build the appropriate casts.
2002 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002003 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002004 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002005 FromLoc, FromRange, &BasePath))
John McCall6bb80172010-03-30 21:47:33 +00002006 return true;
2007
Douglas Gregor5fccd362010-03-03 23:55:11 +00002008 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002009 QType = Context.getPointerType(QType);
John McCall5baba9d2010-08-25 10:28:54 +00002010 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2011 VK, &BasePath);
John McCall6bb80172010-03-30 21:47:33 +00002012
2013 FromType = QType;
2014 FromRecordType = QRecordType;
2015
2016 // If the qualifier type was the same as the destination type,
2017 // we're done.
2018 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2019 return false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002020 }
2021 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002022
John McCall6bb80172010-03-30 21:47:33 +00002023 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002024
John McCall6bb80172010-03-30 21:47:33 +00002025 // If we actually found the member through a using declaration, cast
2026 // down to the using declaration's type.
2027 //
2028 // Pointer equality is fine here because only one declaration of a
2029 // class ever has member declarations.
2030 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2031 assert(isa<UsingShadowDecl>(FoundDecl));
2032 QualType URecordType = Context.getTypeDeclType(
2033 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2034
2035 // We only need to do this if the naming-class to declaring-class
2036 // conversion is non-trivial.
2037 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2038 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002039 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002040 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002041 FromLoc, FromRange, &BasePath))
John McCall6bb80172010-03-30 21:47:33 +00002042 return true;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002043
John McCall6bb80172010-03-30 21:47:33 +00002044 QualType UType = URecordType;
2045 if (PointerConversions)
2046 UType = Context.getPointerType(UType);
John McCall2de56d12010-08-25 11:45:40 +00002047 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00002048 VK, &BasePath);
John McCall6bb80172010-03-30 21:47:33 +00002049 FromType = UType;
2050 FromRecordType = URecordType;
2051 }
2052
2053 // We don't do access control for the conversion from the
2054 // declaring class to the true declaring class.
2055 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002056 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002057
John McCallf871d0c2010-08-07 06:22:56 +00002058 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002059 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2060 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002061 IgnoreAccess))
Douglas Gregor5fccd362010-03-03 23:55:11 +00002062 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002063
John McCall2de56d12010-08-25 11:45:40 +00002064 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00002065 VK, &BasePath);
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00002066 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002067}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002068
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002069/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00002070static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00002071 const CXXScopeSpec &SS, ValueDecl *Member,
John McCall161755a2010-04-06 21:38:20 +00002072 DeclAccessPair FoundDecl,
Abramo Bagnara25777432010-08-11 22:01:17 +00002073 const DeclarationNameInfo &MemberNameInfo,
2074 QualType Ty,
John McCallf89e55a2010-11-18 06:31:45 +00002075 ExprValueKind VK, ExprObjectKind OK,
John McCallf7a1a742009-11-24 19:00:30 +00002076 const TemplateArgumentListInfo *TemplateArgs = 0) {
2077 NestedNameSpecifier *Qualifier = 0;
2078 SourceRange QualifierRange;
John McCall129e2df2009-11-30 22:42:35 +00002079 if (SS.isSet()) {
2080 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
2081 QualifierRange = SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00002082 }
Mike Stump1eb44332009-09-09 15:08:12 +00002083
John McCallf7a1a742009-11-24 19:00:30 +00002084 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
Abramo Bagnara25777432010-08-11 22:01:17 +00002085 Member, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002086 TemplateArgs, Ty, VK, OK);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002087}
2088
John McCalldfa1edb2010-11-23 20:48:44 +00002089static ExprResult
2090BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2091 const CXXScopeSpec &SS, FieldDecl *Field,
2092 DeclAccessPair FoundDecl,
2093 const DeclarationNameInfo &MemberNameInfo) {
2094 // x.a is an l-value if 'a' has a reference type. Otherwise:
2095 // x.a is an l-value/x-value/pr-value if the base is (and note
2096 // that *x is always an l-value), except that if the base isn't
2097 // an ordinary object then we must have an rvalue.
2098 ExprValueKind VK = VK_LValue;
2099 ExprObjectKind OK = OK_Ordinary;
2100 if (!IsArrow) {
2101 if (BaseExpr->getObjectKind() == OK_Ordinary)
2102 VK = BaseExpr->getValueKind();
2103 else
2104 VK = VK_RValue;
2105 }
2106 if (VK != VK_RValue && Field->isBitField())
2107 OK = OK_BitField;
2108
2109 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2110 QualType MemberType = Field->getType();
2111 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2112 MemberType = Ref->getPointeeType();
2113 VK = VK_LValue;
2114 } else {
2115 QualType BaseType = BaseExpr->getType();
2116 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2117
2118 Qualifiers BaseQuals = BaseType.getQualifiers();
2119
2120 // GC attributes are never picked up by members.
2121 BaseQuals.removeObjCGCAttr();
2122
2123 // CVR attributes from the base are picked up by members,
2124 // except that 'mutable' members don't pick up 'const'.
2125 if (Field->isMutable()) BaseQuals.removeConst();
2126
2127 Qualifiers MemberQuals
2128 = S.Context.getCanonicalType(MemberType).getQualifiers();
2129
2130 // TR 18037 does not allow fields to be declared with address spaces.
2131 assert(!MemberQuals.hasAddressSpace());
2132
2133 Qualifiers Combined = BaseQuals + MemberQuals;
2134 if (Combined != MemberQuals)
2135 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2136 }
2137
2138 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
2139 if (S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2140 FoundDecl, Field))
2141 return ExprError();
2142 return S.Owned(BuildMemberExpr(S.Context, BaseExpr, IsArrow, SS,
2143 Field, FoundDecl, MemberNameInfo,
2144 MemberType, VK, OK));
2145}
2146
John McCallaa81e162009-12-01 22:10:20 +00002147/// Builds an implicit member access expression. The current context
2148/// is known to be an instance method, and the given unqualified lookup
2149/// set is known to contain only instance members, at least one of which
2150/// is from an appropriate type.
John McCall60d7b3a2010-08-24 06:29:42 +00002151ExprResult
John McCallaa81e162009-12-01 22:10:20 +00002152Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2153 LookupResult &R,
2154 const TemplateArgumentListInfo *TemplateArgs,
2155 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00002156 assert(!R.empty() && !R.isAmbiguous());
2157
John McCall5808ce42011-02-03 08:15:49 +00002158 SourceLocation loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00002159
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002160 // We may have found a field within an anonymous union or struct
2161 // (C++ [class.union]).
John McCallf7a1a742009-11-24 19:00:30 +00002162 // FIXME: template-ids inside anonymous structs?
Francois Pichet87c2e122010-11-21 06:08:52 +00002163 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCall5808ce42011-02-03 08:15:49 +00002164 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet87c2e122010-11-21 06:08:52 +00002165
John McCall5808ce42011-02-03 08:15:49 +00002166 // If this is known to be an instance access, go ahead and build an
2167 // implicit 'this' expression now.
John McCallaa81e162009-12-01 22:10:20 +00002168 // 'this' expression now.
John McCall5808ce42011-02-03 08:15:49 +00002169 CXXMethodDecl *method = tryCaptureCXXThis();
2170 assert(method && "didn't correctly pre-flight capture of 'this'");
2171
2172 QualType thisType = method->getThisType(Context);
2173 Expr *baseExpr = 0; // null signifies implicit access
John McCallaa81e162009-12-01 22:10:20 +00002174 if (IsKnownInstance) {
Douglas Gregor828a1972010-01-07 23:12:05 +00002175 SourceLocation Loc = R.getNameLoc();
2176 if (SS.getRange().isValid())
2177 Loc = SS.getRange().getBegin();
John McCall5808ce42011-02-03 08:15:49 +00002178 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
Douglas Gregor88a35142008-12-22 05:46:06 +00002179 }
2180
John McCall5808ce42011-02-03 08:15:49 +00002181 return BuildMemberReferenceExpr(baseExpr, thisType,
John McCallaa81e162009-12-01 22:10:20 +00002182 /*OpLoc*/ SourceLocation(),
2183 /*IsArrow*/ true,
John McCallc2233c52010-01-15 08:34:02 +00002184 SS,
2185 /*FirstQualifierInScope*/ 0,
2186 R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00002187}
2188
John McCallf7a1a742009-11-24 19:00:30 +00002189bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002190 const LookupResult &R,
2191 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002192 // Only when used directly as the postfix-expression of a call.
2193 if (!HasTrailingLParen)
2194 return false;
2195
2196 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002197 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002198 return false;
2199
2200 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00002201 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002202 return false;
2203
2204 // Turn off ADL when we find certain kinds of declarations during
2205 // normal lookup:
2206 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2207 NamedDecl *D = *I;
2208
2209 // C++0x [basic.lookup.argdep]p3:
2210 // -- a declaration of a class member
2211 // Since using decls preserve this property, we check this on the
2212 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002213 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002214 return false;
2215
2216 // C++0x [basic.lookup.argdep]p3:
2217 // -- a block-scope function declaration that is not a
2218 // using-declaration
2219 // NOTE: we also trigger this for function templates (in fact, we
2220 // don't check the decl type at all, since all other decl types
2221 // turn off ADL anyway).
2222 if (isa<UsingShadowDecl>(D))
2223 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2224 else if (D->getDeclContext()->isFunctionOrMethod())
2225 return false;
2226
2227 // C++0x [basic.lookup.argdep]p3:
2228 // -- a declaration that is neither a function or a function
2229 // template
2230 // And also for builtin functions.
2231 if (isa<FunctionDecl>(D)) {
2232 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2233
2234 // But also builtin functions.
2235 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2236 return false;
2237 } else if (!isa<FunctionTemplateDecl>(D))
2238 return false;
2239 }
2240
2241 return true;
2242}
2243
2244
John McCallba135432009-11-21 08:51:07 +00002245/// Diagnoses obvious problems with the use of the given declaration
2246/// as an expression. This is only actually called for lookups that
2247/// were not overloaded, and it doesn't promise that the declaration
2248/// will in fact be used.
2249static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2250 if (isa<TypedefDecl>(D)) {
2251 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2252 return true;
2253 }
2254
2255 if (isa<ObjCInterfaceDecl>(D)) {
2256 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2257 return true;
2258 }
2259
2260 if (isa<NamespaceDecl>(D)) {
2261 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2262 return true;
2263 }
2264
2265 return false;
2266}
2267
John McCall60d7b3a2010-08-24 06:29:42 +00002268ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002269Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002270 LookupResult &R,
2271 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002272 // If this is a single, fully-resolved result and we don't need ADL,
2273 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002274 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002275 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2276 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002277
2278 // We only need to check the declaration if there's exactly one
2279 // result, because in the overloaded case the results can only be
2280 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002281 if (R.isSingleResult() &&
2282 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002283 return ExprError();
2284
John McCallc373d482010-01-27 01:50:18 +00002285 // Otherwise, just build an unresolved lookup expression. Suppress
2286 // any lookup-related diagnostics; we'll hash these out later, when
2287 // we've picked a target.
2288 R.suppressDiagnostics();
2289
John McCallba135432009-11-21 08:51:07 +00002290 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002291 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00002292 (NestedNameSpecifier*) SS.getScopeRep(),
Abramo Bagnara25777432010-08-11 22:01:17 +00002293 SS.getRange(), R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002294 NeedsADL, R.isOverloadedResult(),
2295 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002296
2297 return Owned(ULE);
2298}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002299
John McCallba135432009-11-21 08:51:07 +00002300/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002301ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002302Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002303 const DeclarationNameInfo &NameInfo,
2304 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002305 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002306 assert(!isa<FunctionTemplateDecl>(D) &&
2307 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002308
Abramo Bagnara25777432010-08-11 22:01:17 +00002309 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002310 if (CheckDeclInExpr(*this, Loc, D))
2311 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002312
Douglas Gregor9af2f522009-12-01 16:58:18 +00002313 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2314 // Specifically diagnose references to class templates that are missing
2315 // a template argument list.
2316 Diag(Loc, diag::err_template_decl_ref)
2317 << Template << SS.getRange();
2318 Diag(Template->getLocation(), diag::note_template_decl_here);
2319 return ExprError();
2320 }
2321
2322 // Make sure that we're referring to a value.
2323 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2324 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002325 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002326 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002327 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002328 return ExprError();
2329 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002330
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002331 // Check whether this declaration can be used. Note that we suppress
2332 // this check when we're going to perform argument-dependent lookup
2333 // on this function name, because this might not be the function
2334 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002335 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002336 return ExprError();
2337
Steve Naroffdd972f22008-09-05 22:11:13 +00002338 // Only create DeclRefExpr's for valid Decl's.
2339 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002340 return ExprError();
2341
John McCall5808ce42011-02-03 08:15:49 +00002342 // Handle members of anonymous structs and unions. If we got here,
2343 // and the reference is to a class member indirect field, then this
2344 // must be the subject of a pointer-to-member expression.
2345 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2346 if (!indirectField->isCXXClassMember())
2347 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2348 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002349
Chris Lattner639e2d32008-10-20 05:16:36 +00002350 // If the identifier reference is inside a block, and it refers to a value
2351 // that is outside the block, create a BlockDeclRefExpr instead of a
2352 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2353 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00002354 //
Chris Lattner639e2d32008-10-20 05:16:36 +00002355 // We do not do this for things like enum constants, global variables, etc,
2356 // as they do not get snapshotted.
2357 //
John McCall6b5a61b2011-02-07 10:33:21 +00002358 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCall469a1eb2011-02-02 13:00:07 +00002359 case CR_Error:
2360 return ExprError();
Mike Stump0d6fd572010-01-05 02:56:35 +00002361
John McCall469a1eb2011-02-02 13:00:07 +00002362 case CR_Capture:
John McCall6b5a61b2011-02-07 10:33:21 +00002363 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2364 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2365
2366 case CR_CaptureByRef:
2367 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2368 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCall76a40212011-02-09 01:13:10 +00002369
2370 case CR_NoCapture: {
2371 // If this reference is not in a block or if the referenced
2372 // variable is within the block, create a normal DeclRefExpr.
2373
2374 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002375 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002376
2377 switch (D->getKind()) {
2378 // Ignore all the non-ValueDecl kinds.
2379#define ABSTRACT_DECL(kind)
2380#define VALUE(type, base)
2381#define DECL(type, base) \
2382 case Decl::type:
2383#include "clang/AST/DeclNodes.inc"
2384 llvm_unreachable("invalid value decl kind");
2385 return ExprError();
2386
2387 // These shouldn't make it here.
2388 case Decl::ObjCAtDefsField:
2389 case Decl::ObjCIvar:
2390 llvm_unreachable("forming non-member reference to ivar?");
2391 return ExprError();
2392
2393 // Enum constants are always r-values and never references.
2394 // Unresolved using declarations are dependent.
2395 case Decl::EnumConstant:
2396 case Decl::UnresolvedUsingValue:
2397 valueKind = VK_RValue;
2398 break;
2399
2400 // Fields and indirect fields that got here must be for
2401 // pointer-to-member expressions; we just call them l-values for
2402 // internal consistency, because this subexpression doesn't really
2403 // exist in the high-level semantics.
2404 case Decl::Field:
2405 case Decl::IndirectField:
2406 assert(getLangOptions().CPlusPlus &&
2407 "building reference to field in C?");
2408
2409 // These can't have reference type in well-formed programs, but
2410 // for internal consistency we do this anyway.
2411 type = type.getNonReferenceType();
2412 valueKind = VK_LValue;
2413 break;
2414
2415 // Non-type template parameters are either l-values or r-values
2416 // depending on the type.
2417 case Decl::NonTypeTemplateParm: {
2418 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2419 type = reftype->getPointeeType();
2420 valueKind = VK_LValue; // even if the parameter is an r-value reference
2421 break;
2422 }
2423
2424 // For non-references, we need to strip qualifiers just in case
2425 // the template parameter was declared as 'const int' or whatever.
2426 valueKind = VK_RValue;
2427 type = type.getUnqualifiedType();
2428 break;
2429 }
2430
2431 case Decl::Var:
2432 // In C, "extern void blah;" is valid and is an r-value.
2433 if (!getLangOptions().CPlusPlus &&
2434 !type.hasQualifiers() &&
2435 type->isVoidType()) {
2436 valueKind = VK_RValue;
2437 break;
2438 }
2439 // fallthrough
2440
2441 case Decl::ImplicitParam:
2442 case Decl::ParmVar:
2443 // These are always l-values.
2444 valueKind = VK_LValue;
2445 type = type.getNonReferenceType();
2446 break;
2447
2448 case Decl::Function: {
2449 // Functions are l-values in C++.
2450 if (getLangOptions().CPlusPlus) {
2451 valueKind = VK_LValue;
2452 break;
2453 }
2454
2455 // C99 DR 316 says that, if a function type comes from a
2456 // function definition (without a prototype), that type is only
2457 // used for checking compatibility. Therefore, when referencing
2458 // the function, we pretend that we don't have the full function
2459 // type.
2460 if (!cast<FunctionDecl>(VD)->hasPrototype())
2461 if (const FunctionProtoType *proto = type->getAs<FunctionProtoType>())
2462 type = Context.getFunctionNoProtoType(proto->getResultType(),
2463 proto->getExtInfo());
2464
2465 // Functions are r-values in C.
2466 valueKind = VK_RValue;
2467 break;
2468 }
2469
2470 case Decl::CXXMethod:
2471 // C++ methods are l-values if static, r-values if non-static.
2472 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2473 valueKind = VK_LValue;
2474 break;
2475 }
2476 // fallthrough
2477
2478 case Decl::CXXConversion:
2479 case Decl::CXXDestructor:
2480 case Decl::CXXConstructor:
2481 valueKind = VK_RValue;
2482 break;
2483 }
2484
2485 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2486 }
2487
John McCall469a1eb2011-02-02 13:00:07 +00002488 }
John McCallf89e55a2010-11-18 06:31:45 +00002489
John McCall6b5a61b2011-02-07 10:33:21 +00002490 llvm_unreachable("unknown capture result");
2491 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002492}
2493
John McCall60d7b3a2010-08-24 06:29:42 +00002494ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Sebastian Redlcd965b92009-01-18 18:53:16 +00002495 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002496 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002497
Reid Spencer5f016e22007-07-11 17:01:13 +00002498 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00002499 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002500 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2501 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2502 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002503 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002504
Chris Lattnerfa28b302008-01-12 08:14:25 +00002505 // Pre-defined identifiers are of type char[x], where x is the length of the
2506 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002507
Anders Carlsson3a082d82009-09-08 18:24:21 +00002508 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002509 if (!currentDecl && getCurBlock())
2510 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002511 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002512 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002513 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002514 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002515
Anders Carlsson773f3972009-09-11 01:22:35 +00002516 QualType ResTy;
2517 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2518 ResTy = Context.DependentTy;
2519 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002520 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002521
Anders Carlsson773f3972009-09-11 01:22:35 +00002522 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00002523 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002524 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2525 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002526 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002527}
2528
John McCall60d7b3a2010-08-24 06:29:42 +00002529ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002530 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002531 bool Invalid = false;
2532 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2533 if (Invalid)
2534 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002535
Benjamin Kramerddeea562010-02-27 13:44:12 +00002536 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2537 PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00002538 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002539 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002540
Chris Lattnere8337df2009-12-30 21:19:39 +00002541 QualType Ty;
2542 if (!getLangOptions().CPlusPlus)
2543 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2544 else if (Literal.isWide())
2545 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedman136b0cd2010-02-03 18:21:45 +00002546 else if (Literal.isMultiChar())
2547 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002548 else
2549 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002550
Sebastian Redle91b3bc2009-01-20 22:23:13 +00002551 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2552 Literal.isWide(),
Chris Lattnere8337df2009-12-30 21:19:39 +00002553 Ty, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002554}
2555
John McCall60d7b3a2010-08-24 06:29:42 +00002556ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002557 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00002558 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2559 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002560 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00002561 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002562 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00002563 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002564 }
Ted Kremenek28396602009-01-13 23:19:12 +00002565
Reid Spencer5f016e22007-07-11 17:01:13 +00002566 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002567 // Add padding so that NumericLiteralParser can overread by one character.
2568 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002569 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002570
Reid Spencer5f016e22007-07-11 17:01:13 +00002571 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002572 bool Invalid = false;
2573 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2574 if (Invalid)
2575 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002576
Mike Stump1eb44332009-09-09 15:08:12 +00002577 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002578 Tok.getLocation(), PP);
2579 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002580 return ExprError();
2581
Chris Lattner5d661452007-08-26 03:42:43 +00002582 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002583
Chris Lattner5d661452007-08-26 03:42:43 +00002584 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002585 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002586 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002587 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002588 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002589 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002590 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002591 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002592
2593 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2594
John McCall94c939d2009-12-24 09:08:04 +00002595 using llvm::APFloat;
2596 APFloat Val(Format);
2597
2598 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00002599
2600 // Overflow is always an error, but underflow is only an error if
2601 // we underflowed to zero (APFloat reports denormals as underflow).
2602 if ((result & APFloat::opOverflow) ||
2603 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00002604 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002605 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00002606 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00002607 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00002608 APFloat::getLargest(Format).toString(buffer);
2609 } else {
John McCall2a0d7572010-02-26 23:35:57 +00002610 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00002611 APFloat::getSmallest(Format).toString(buffer);
2612 }
2613
2614 Diag(Tok.getLocation(), diagnostic)
2615 << Ty
2616 << llvm::StringRef(buffer.data(), buffer.size());
2617 }
2618
2619 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002620 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002621
Peter Collingbourne09821362010-12-04 01:50:56 +00002622 if (getLangOptions().SinglePrecisionConstants && Ty == Context.DoubleTy)
2623 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2624
Chris Lattner5d661452007-08-26 03:42:43 +00002625 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002626 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002627 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002628 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002629
Neil Boothb9449512007-08-29 22:00:19 +00002630 // long long is a C99 feature.
2631 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00002632 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00002633 Diag(Tok.getLocation(), diag::ext_longlong);
2634
Reid Spencer5f016e22007-07-11 17:01:13 +00002635 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00002636 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002637
Reid Spencer5f016e22007-07-11 17:01:13 +00002638 if (Literal.GetIntegerValue(ResultVal)) {
2639 // If this value didn't fit into uintmax_t, warn and force to ull.
2640 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002641 Ty = Context.UnsignedLongLongTy;
2642 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002643 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002644 } else {
2645 // If this value fits into a ULL, try to figure out what else it fits into
2646 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002647
Reid Spencer5f016e22007-07-11 17:01:13 +00002648 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2649 // be an unsigned int.
2650 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2651
2652 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002653 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002654 if (!Literal.isLong && !Literal.isLongLong) {
2655 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002656 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002657
Reid Spencer5f016e22007-07-11 17:01:13 +00002658 // Does it fit in a unsigned int?
2659 if (ResultVal.isIntN(IntSize)) {
2660 // Does it fit in a signed int?
2661 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002662 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002663 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002664 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002665 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002666 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002667 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002668
Reid Spencer5f016e22007-07-11 17:01:13 +00002669 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002670 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002671 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002672
Reid Spencer5f016e22007-07-11 17:01:13 +00002673 // Does it fit in a unsigned long?
2674 if (ResultVal.isIntN(LongSize)) {
2675 // Does it fit in a signed long?
2676 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002677 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002678 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002679 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002680 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002681 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002682 }
2683
Reid Spencer5f016e22007-07-11 17:01:13 +00002684 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002685 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002686 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002687
Reid Spencer5f016e22007-07-11 17:01:13 +00002688 // Does it fit in a unsigned long long?
2689 if (ResultVal.isIntN(LongLongSize)) {
2690 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002691 // To be compatible with MSVC, hex integer literals ending with the
2692 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002693 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2694 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002695 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002696 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002697 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002698 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002699 }
2700 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002701
Reid Spencer5f016e22007-07-11 17:01:13 +00002702 // If we still couldn't decide a type, we probably have something that
2703 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002704 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002705 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002706 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002707 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002708 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002709
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002710 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002711 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002712 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002713 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002714 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002715
Chris Lattner5d661452007-08-26 03:42:43 +00002716 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2717 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002718 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002719 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002720
2721 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002722}
2723
John McCall60d7b3a2010-08-24 06:29:42 +00002724ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCall9ae2f072010-08-23 23:25:46 +00002725 SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002726 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002727 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002728}
2729
2730/// The UsualUnaryConversions() function is *not* called by this routine.
2731/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00002732bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00002733 SourceLocation OpLoc,
John McCall2a984ca2010-10-12 00:20:44 +00002734 SourceRange ExprRange,
Sebastian Redl05189992008-11-11 17:56:53 +00002735 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00002736 if (exprType->isDependentType())
2737 return false;
2738
Sebastian Redl5d484e82009-11-23 17:18:46 +00002739 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2740 // the result is the size of the referenced type."
2741 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2742 // result shall be the alignment of the referenced type."
2743 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2744 exprType = Ref->getPointeeType();
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.
Chris Lattner01072922009-01-24 19:46:37 +00002749 if (isSizeof)
2750 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2751 return false;
2752 }
Mike Stump1eb44332009-09-09 15:08:12 +00002753
Chris Lattner1efaa952009-04-24 00:30:45 +00002754 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00002755 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002756 Diag(OpLoc, diag::ext_sizeof_void_type)
2757 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00002758 return false;
2759 }
Mike Stump1eb44332009-09-09 15:08:12 +00002760
Chris Lattner1efaa952009-04-24 00:30:45 +00002761 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00002762 PDiag(diag::err_sizeof_alignof_incomplete_type)
2763 << int(!isSizeof) << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00002764 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002765
Chris Lattner1efaa952009-04-24 00:30:45 +00002766 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCallc12c5bb2010-05-15 11:32:37 +00002767 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002768 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00002769 << exprType << isSizeof << ExprRange;
2770 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00002771 }
Mike Stump1eb44332009-09-09 15:08:12 +00002772
Chris Lattner1efaa952009-04-24 00:30:45 +00002773 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002774}
2775
John McCall2a984ca2010-10-12 00:20:44 +00002776static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2777 SourceRange ExprRange) {
Chris Lattner31e21e02009-01-24 20:17:12 +00002778 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00002779
Mike Stump1eb44332009-09-09 15:08:12 +00002780 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00002781 if (isa<DeclRefExpr>(E))
2782 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00002783
2784 // Cannot know anything else if the expression is dependent.
2785 if (E->isTypeDependent())
2786 return false;
2787
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002788 if (E->getBitField()) {
John McCall2a984ca2010-10-12 00:20:44 +00002789 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002790 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00002791 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002792
2793 // Alignment of a field access is always okay, so long as it isn't a
2794 // bit-field.
2795 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00002796 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002797 return false;
2798
John McCall2a984ca2010-10-12 00:20:44 +00002799 return S.CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
Chris Lattner31e21e02009-01-24 20:17:12 +00002800}
2801
Douglas Gregorba498172009-03-13 21:01:28 +00002802/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002803ExprResult
John McCalla93c9342009-12-07 02:54:59 +00002804Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall5ab75172009-11-04 07:28:41 +00002805 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00002806 bool isSizeOf, SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00002807 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00002808 return ExprError();
2809
John McCalla93c9342009-12-07 02:54:59 +00002810 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00002811
Douglas Gregorba498172009-03-13 21:01:28 +00002812 if (!T->isDependentType() &&
2813 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2814 return ExprError();
2815
2816 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCalla93c9342009-12-07 02:54:59 +00002817 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00002818 Context.getSizeType(), OpLoc,
2819 R.getEnd()));
2820}
2821
2822/// \brief Build a sizeof or alignof expression given an expression
2823/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002824ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00002825Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00002826 bool isSizeOf, SourceRange R) {
2827 // Verify that the operand is valid.
2828 bool isInvalid = false;
2829 if (E->isTypeDependent()) {
2830 // Delay type-checking for type-dependent expressions.
2831 } else if (!isSizeOf) {
John McCall2a984ca2010-10-12 00:20:44 +00002832 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002833 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00002834 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2835 isInvalid = true;
John McCall2cd11fe2010-10-12 02:09:17 +00002836 } else if (E->getType()->isPlaceholderType()) {
2837 ExprResult PE = CheckPlaceholderExpr(E, OpLoc);
2838 if (PE.isInvalid()) return ExprError();
2839 return CreateSizeOfAlignOfExpr(PE.take(), OpLoc, isSizeOf, R);
Douglas Gregorba498172009-03-13 21:01:28 +00002840 } else {
2841 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2842 }
2843
2844 if (isInvalid)
2845 return ExprError();
2846
2847 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2848 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2849 Context.getSizeType(), OpLoc,
2850 R.getEnd()));
2851}
2852
Sebastian Redl05189992008-11-11 17:56:53 +00002853/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2854/// the same for @c alignof and @c __alignof
2855/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00002856ExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00002857Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2858 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002859 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002860 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002861
Sebastian Redl05189992008-11-11 17:56:53 +00002862 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00002863 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00002864 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
John McCalla93c9342009-12-07 02:54:59 +00002865 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00002866 }
Sebastian Redl05189992008-11-11 17:56:53 +00002867
Douglas Gregorba498172009-03-13 21:01:28 +00002868 Expr *ArgEx = (Expr *)TyOrEx;
John McCall60d7b3a2010-08-24 06:29:42 +00002869 ExprResult Result
Douglas Gregorba498172009-03-13 21:01:28 +00002870 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2871
Douglas Gregorba498172009-03-13 21:01:28 +00002872 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002873}
2874
John McCall09431682010-11-18 19:01:18 +00002875static QualType CheckRealImagOperand(Sema &S, Expr *&V, SourceLocation Loc,
2876 bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00002877 if (V->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00002878 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002879
John McCallf6a16482010-12-04 03:47:34 +00002880 // _Real and _Imag are only l-values for normal l-values.
2881 if (V->getObjectKind() != OK_Ordinary)
John McCall409fa9a2010-12-06 20:48:59 +00002882 S.DefaultLvalueConversion(V);
John McCallf6a16482010-12-04 03:47:34 +00002883
Chris Lattnercc26ed72007-08-26 05:39:26 +00002884 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00002885 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00002886 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002887
Chris Lattnercc26ed72007-08-26 05:39:26 +00002888 // Otherwise they pass through real integer and floating point types here.
2889 if (V->getType()->isArithmeticType())
2890 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002891
John McCall2cd11fe2010-10-12 02:09:17 +00002892 // Test for placeholders.
John McCall09431682010-11-18 19:01:18 +00002893 ExprResult PR = S.CheckPlaceholderExpr(V, Loc);
John McCall2cd11fe2010-10-12 02:09:17 +00002894 if (PR.isInvalid()) return QualType();
2895 if (PR.take() != V) {
2896 V = PR.take();
John McCall09431682010-11-18 19:01:18 +00002897 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall2cd11fe2010-10-12 02:09:17 +00002898 }
2899
Chris Lattnercc26ed72007-08-26 05:39:26 +00002900 // Reject anything else.
John McCall09431682010-11-18 19:01:18 +00002901 S.Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
Chris Lattnerba27e2a2009-02-17 08:12:06 +00002902 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00002903 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00002904}
2905
2906
Reid Spencer5f016e22007-07-11 17:01:13 +00002907
John McCall60d7b3a2010-08-24 06:29:42 +00002908ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00002909Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002910 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00002911 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00002912 switch (Kind) {
2913 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00002914 case tok::plusplus: Opc = UO_PostInc; break;
2915 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002916 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002917
John McCall9ae2f072010-08-23 23:25:46 +00002918 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00002919}
2920
John McCall09431682010-11-18 19:01:18 +00002921/// Expressions of certain arbitrary types are forbidden by C from
2922/// having l-value type. These are:
2923/// - 'void', but not qualified void
2924/// - function types
2925///
2926/// The exact rule here is C99 6.3.2.1:
2927/// An lvalue is an expression with an object type or an incomplete
2928/// type other than void.
2929static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
2930 return ((T->isVoidType() && !T.hasQualifiers()) ||
2931 T->isFunctionType());
2932}
2933
John McCall60d7b3a2010-08-24 06:29:42 +00002934ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002935Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2936 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00002937 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00002938 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00002939 if (Result.isInvalid()) return ExprError();
2940 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00002941
John McCall9ae2f072010-08-23 23:25:46 +00002942 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00002943
Douglas Gregor337c6b92008-11-19 17:17:41 +00002944 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002945 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002946 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00002947 Context.DependentTy,
2948 VK_LValue, OK_Ordinary,
2949 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002950 }
2951
Mike Stump1eb44332009-09-09 15:08:12 +00002952 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00002953 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00002954 LHSExp->getType()->isEnumeralType() ||
2955 RHSExp->getType()->isRecordType() ||
2956 RHSExp->getType()->isEnumeralType())) {
John McCall9ae2f072010-08-23 23:25:46 +00002957 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00002958 }
2959
John McCall9ae2f072010-08-23 23:25:46 +00002960 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00002961}
2962
2963
John McCall60d7b3a2010-08-24 06:29:42 +00002964ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002965Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2966 Expr *Idx, SourceLocation RLoc) {
2967 Expr *LHSExp = Base;
2968 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00002969
Chris Lattner12d9ff62007-07-16 00:14:47 +00002970 // Perform default conversions.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002971 if (!LHSExp->getType()->getAs<VectorType>())
2972 DefaultFunctionArrayLvalueConversion(LHSExp);
2973 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002974
Chris Lattner12d9ff62007-07-16 00:14:47 +00002975 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00002976 ExprValueKind VK = VK_LValue;
2977 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00002978
Reid Spencer5f016e22007-07-11 17:01:13 +00002979 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002980 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00002981 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00002982 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00002983 Expr *BaseExpr, *IndexExpr;
2984 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00002985 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2986 BaseExpr = LHSExp;
2987 IndexExpr = RHSExp;
2988 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00002989 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00002990 BaseExpr = LHSExp;
2991 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002992 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002993 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00002994 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00002995 BaseExpr = RHSExp;
2996 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002997 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002998 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00002999 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003000 BaseExpr = LHSExp;
3001 IndexExpr = RHSExp;
3002 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003003 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003004 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003005 // Handle the uncommon case of "123[Ptr]".
3006 BaseExpr = RHSExp;
3007 IndexExpr = LHSExp;
3008 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003009 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003010 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003011 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003012 VK = LHSExp->getValueKind();
3013 if (VK != VK_RValue)
3014 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003015
Chris Lattner12d9ff62007-07-16 00:14:47 +00003016 // FIXME: need to deal with const...
3017 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003018 } else if (LHSTy->isArrayType()) {
3019 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003020 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003021 // wasn't promoted because of the C90 rule that doesn't
3022 // allow promoting non-lvalue arrays. Warn, then
3023 // force the promotion here.
3024 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3025 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003026 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
John McCall2de56d12010-08-25 11:45:40 +00003027 CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003028 LHSTy = LHSExp->getType();
3029
3030 BaseExpr = LHSExp;
3031 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003032 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003033 } else if (RHSTy->isArrayType()) {
3034 // Same as previous, except for 123[f().a] case
3035 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3036 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003037 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
John McCall2de56d12010-08-25 11:45:40 +00003038 CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003039 RHSTy = RHSExp->getType();
3040
3041 BaseExpr = RHSExp;
3042 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003043 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003044 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003045 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3046 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003047 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003048 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003049 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003050 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3051 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003052
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003053 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003054 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3055 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003056 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3057
Douglas Gregore7450f52009-03-24 19:52:54 +00003058 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003059 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3060 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003061 // incomplete types are not object types.
3062 if (ResultType->isFunctionType()) {
3063 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3064 << ResultType << BaseExpr->getSourceRange();
3065 return ExprError();
3066 }
Mike Stump1eb44332009-09-09 15:08:12 +00003067
Abramo Bagnara46358452010-09-13 06:50:07 +00003068 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3069 // GNU extension: subscripting on pointer to void
3070 Diag(LLoc, diag::ext_gnu_void_ptr)
3071 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003072
3073 // C forbids expressions of unqualified void type from being l-values.
3074 // See IsCForbiddenLValueType.
3075 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003076 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003077 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003078 PDiag(diag::err_subscript_incomplete_type)
3079 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00003080 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003081
Chris Lattner1efaa952009-04-24 00:30:45 +00003082 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00003083 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003084 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3085 << ResultType << BaseExpr->getSourceRange();
3086 return ExprError();
3087 }
Mike Stump1eb44332009-09-09 15:08:12 +00003088
John McCall09431682010-11-18 19:01:18 +00003089 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3090 !IsCForbiddenLValueType(Context, ResultType));
3091
Mike Stumpeed9cac2009-02-19 03:04:26 +00003092 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003093 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003094}
3095
John McCall09431682010-11-18 19:01:18 +00003096/// Check an ext-vector component access expression.
3097///
3098/// VK should be set in advance to the value kind of the base
3099/// expression.
3100static QualType
3101CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3102 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00003103 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00003104 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3105 // see FIXME there.
3106 //
3107 // FIXME: This logic can be greatly simplified by splitting it along
3108 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00003109 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00003110
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003111 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00003112 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00003113
Mike Stumpeed9cac2009-02-19 03:04:26 +00003114 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00003115 // special names that indicate a subset of exactly half the elements are
3116 // to be selected.
3117 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003118
Nate Begeman353417a2009-01-18 01:47:54 +00003119 // This flag determines whether or not CompName has an 's' char prefix,
3120 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00003121 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00003122
John McCall09431682010-11-18 19:01:18 +00003123 bool HasRepeated = false;
3124 bool HasIndex[16] = {};
3125
3126 int Idx;
3127
Nate Begeman8a997642008-05-09 06:41:27 +00003128 // Check that we've found one of the special components, or that the component
3129 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003130 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00003131 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3132 HalvingSwizzle = true;
John McCall09431682010-11-18 19:01:18 +00003133 } else if (!HexSwizzle &&
3134 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3135 do {
3136 if (HasIndex[Idx]) HasRepeated = true;
3137 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00003138 compStr++;
John McCall09431682010-11-18 19:01:18 +00003139 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3140 } else {
3141 if (HexSwizzle) compStr++;
3142 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3143 if (HasIndex[Idx]) HasRepeated = true;
3144 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00003145 compStr++;
John McCall09431682010-11-18 19:01:18 +00003146 }
Chris Lattner88dca042007-08-02 22:33:49 +00003147 }
Nate Begeman353417a2009-01-18 01:47:54 +00003148
Mike Stumpeed9cac2009-02-19 03:04:26 +00003149 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003150 // We didn't get to the end of the string. This means the component names
3151 // didn't come from the same set *or* we encountered an illegal name.
John McCall09431682010-11-18 19:01:18 +00003152 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00003153 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003154 return QualType();
3155 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003156
Nate Begeman353417a2009-01-18 01:47:54 +00003157 // Ensure no component accessor exceeds the width of the vector type it
3158 // operates on.
3159 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00003160 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00003161
3162 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003163 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00003164
3165 while (*compStr) {
3166 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall09431682010-11-18 19:01:18 +00003167 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begeman353417a2009-01-18 01:47:54 +00003168 << baseType << SourceRange(CompLoc);
3169 return QualType();
3170 }
3171 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003172 }
Nate Begeman8a997642008-05-09 06:41:27 +00003173
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003174 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003175 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003176 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00003177 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00003178 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman0479a0b2009-12-15 18:13:04 +00003179 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00003180 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00003181 if (HexSwizzle)
3182 CompSize--;
3183
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003184 if (CompSize == 1)
3185 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003186
John McCall09431682010-11-18 19:01:18 +00003187 if (HasRepeated) VK = VK_RValue;
3188
3189 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003190 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00003191 // diagostics look bad. We want extended vector types to appear built-in.
John McCall09431682010-11-18 19:01:18 +00003192 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3193 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3194 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00003195 }
3196 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003197}
3198
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003199static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00003200 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003201 const Selector &Sel,
3202 ASTContext &Context) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003203 if (Member)
3204 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3205 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003206 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003207 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00003208
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003209 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3210 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003211 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3212 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003213 return D;
3214 }
3215 return 0;
3216}
3217
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003218static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3219 IdentifierInfo *Member,
3220 const Selector &Sel,
3221 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003222 // Check protocols on qualified interfaces.
3223 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003224 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003225 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003226 if (Member)
3227 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3228 GDecl = PD;
3229 break;
3230 }
3231 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003232 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003233 GDecl = OMD;
3234 break;
3235 }
3236 }
3237 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003238 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003239 E = QIdTy->qual_end(); I != E; ++I) {
3240 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003241 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3242 Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003243 if (GDecl)
3244 return GDecl;
3245 }
3246 }
3247 return GDecl;
3248}
Chris Lattner76a642f2009-02-15 22:43:40 +00003249
John McCall60d7b3a2010-08-24 06:29:42 +00003250ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003251Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCallaa81e162009-12-01 22:10:20 +00003252 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00003253 const CXXScopeSpec &SS,
3254 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003255 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003256 const TemplateArgumentListInfo *TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00003257 // Even in dependent contexts, try to diagnose base expressions with
3258 // obviously wrong types, e.g.:
3259 //
3260 // T* t;
3261 // t.f;
3262 //
3263 // In Obj-C++, however, the above expression is valid, since it could be
3264 // accessing the 'f' property if T is an Obj-C interface. The extra check
3265 // allows this, while still reporting an error if T is a struct pointer.
3266 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00003267 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00003268 if (PT && (!getLangOptions().ObjC1 ||
3269 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00003270 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnara25777432010-08-11 22:01:17 +00003271 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00003272 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00003273 return ExprError();
3274 }
3275 }
3276
Abramo Bagnara25777432010-08-11 22:01:17 +00003277 assert(BaseType->isDependentType() ||
3278 NameInfo.getName().isDependentName() ||
Douglas Gregor01e56ae2010-04-12 20:54:26 +00003279 isDependentScopeSpecifier(SS));
John McCall129e2df2009-11-30 22:42:35 +00003280
3281 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3282 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00003283 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003284 IsArrow, OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003285 SS.getScopeRep(),
John McCall129e2df2009-11-30 22:42:35 +00003286 SS.getRange(),
3287 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003288 NameInfo, TemplateArgs));
John McCall129e2df2009-11-30 22:42:35 +00003289}
3290
3291/// We know that the given qualified member reference points only to
3292/// declarations which do not belong to the static type of the base
3293/// expression. Diagnose the problem.
3294static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3295 Expr *BaseExpr,
3296 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003297 const CXXScopeSpec &SS,
John McCall5808ce42011-02-03 08:15:49 +00003298 NamedDecl *rep,
3299 const DeclarationNameInfo &nameInfo) {
John McCall2f841ba2009-12-02 03:53:29 +00003300 // If this is an implicit member access, use a different set of
3301 // diagnostics.
3302 if (!BaseExpr)
John McCall5808ce42011-02-03 08:15:49 +00003303 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall129e2df2009-11-30 22:42:35 +00003304
John McCall5808ce42011-02-03 08:15:49 +00003305 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3306 << SS.getRange() << rep << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00003307}
3308
3309// Check whether the declarations we found through a nested-name
3310// specifier in a member expression are actually members of the base
3311// type. The restriction here is:
3312//
3313// C++ [expr.ref]p2:
3314// ... In these cases, the id-expression shall name a
3315// member of the class or of one of its base classes.
3316//
3317// So it's perfectly legitimate for the nested-name specifier to name
3318// an unrelated class, and for us to find an overload set including
3319// decls from classes which are not superclasses, as long as the decl
3320// we actually pick through overload resolution is from a superclass.
3321bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3322 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003323 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003324 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00003325 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3326 if (!BaseRT) {
3327 // We can't check this yet because the base type is still
3328 // dependent.
3329 assert(BaseType->isDependentType());
3330 return false;
3331 }
3332 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00003333
3334 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00003335 // If this is an implicit member reference and we find a
3336 // non-instance member, it's not an error.
John McCall161755a2010-04-06 21:38:20 +00003337 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCallaa81e162009-12-01 22:10:20 +00003338 return false;
John McCall129e2df2009-11-30 22:42:35 +00003339
John McCallaa81e162009-12-01 22:10:20 +00003340 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman02463762010-07-27 20:51:02 +00003341 DeclContext *DC = (*I)->getDeclContext();
3342 while (DC->isTransparentContext())
3343 DC = DC->getParent();
John McCallaa81e162009-12-01 22:10:20 +00003344
Douglas Gregor9d4bb942010-07-28 22:27:52 +00003345 if (!DC->isRecord())
3346 continue;
3347
John McCallaa81e162009-12-01 22:10:20 +00003348 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman02463762010-07-27 20:51:02 +00003349 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCallaa81e162009-12-01 22:10:20 +00003350
3351 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3352 return false;
3353 }
3354
John McCall5808ce42011-02-03 08:15:49 +00003355 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3356 R.getRepresentativeDecl(),
3357 R.getLookupNameInfo());
John McCallaa81e162009-12-01 22:10:20 +00003358 return true;
3359}
3360
3361static bool
3362LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3363 SourceRange BaseRange, const RecordType *RTy,
John McCallad00b772010-06-16 08:42:20 +00003364 SourceLocation OpLoc, CXXScopeSpec &SS,
3365 bool HasTemplateArgs) {
John McCallaa81e162009-12-01 22:10:20 +00003366 RecordDecl *RDecl = RTy->getDecl();
3367 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003368 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCallaa81e162009-12-01 22:10:20 +00003369 << BaseRange))
3370 return true;
3371
John McCallad00b772010-06-16 08:42:20 +00003372 if (HasTemplateArgs) {
3373 // LookupTemplateName doesn't expect these both to exist simultaneously.
3374 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3375
3376 bool MOUS;
3377 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3378 return false;
3379 }
3380
John McCallaa81e162009-12-01 22:10:20 +00003381 DeclContext *DC = RDecl;
3382 if (SS.isSet()) {
3383 // If the member name was a qualified-id, look into the
3384 // nested-name-specifier.
3385 DC = SemaRef.computeDeclContext(SS, false);
3386
John McCall77bb1aa2010-05-01 00:40:08 +00003387 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCall2f841ba2009-12-02 03:53:29 +00003388 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3389 << SS.getRange() << DC;
3390 return true;
3391 }
3392
John McCallaa81e162009-12-01 22:10:20 +00003393 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003394
John McCallaa81e162009-12-01 22:10:20 +00003395 if (!isa<TypeDecl>(DC)) {
3396 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3397 << DC << SS.getRange();
3398 return true;
John McCall129e2df2009-11-30 22:42:35 +00003399 }
3400 }
3401
John McCallaa81e162009-12-01 22:10:20 +00003402 // The record definition is complete, now look up the member.
3403 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00003404
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003405 if (!R.empty())
3406 return false;
3407
3408 // We didn't find anything with the given name, so try to correct
3409 // for typos.
3410 DeclarationName Name = R.getLookupName();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003411 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00003412 !R.empty() &&
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003413 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3414 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3415 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00003416 << FixItHint::CreateReplacement(R.getNameLoc(),
3417 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00003418 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3419 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3420 << ND->getDeclName();
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003421 return false;
3422 } else {
3423 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003424 R.setLookupName(Name);
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003425 }
3426
John McCall129e2df2009-11-30 22:42:35 +00003427 return false;
3428}
3429
John McCall60d7b3a2010-08-24 06:29:42 +00003430ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003431Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003432 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003433 CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003434 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003435 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003436 const TemplateArgumentListInfo *TemplateArgs) {
John McCall2f841ba2009-12-02 03:53:29 +00003437 if (BaseType->isDependentType() ||
3438 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCall9ae2f072010-08-23 23:25:46 +00003439 return ActOnDependentMemberExpr(Base, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003440 IsArrow, OpLoc,
3441 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003442 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003443
Abramo Bagnara25777432010-08-11 22:01:17 +00003444 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00003445
John McCallaa81e162009-12-01 22:10:20 +00003446 // Implicit member accesses.
3447 if (!Base) {
3448 QualType RecordTy = BaseType;
3449 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3450 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3451 RecordTy->getAs<RecordType>(),
John McCallad00b772010-06-16 08:42:20 +00003452 OpLoc, SS, TemplateArgs != 0))
John McCallaa81e162009-12-01 22:10:20 +00003453 return ExprError();
3454
3455 // Explicit member accesses.
3456 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00003457 ExprResult Result =
John McCallaa81e162009-12-01 22:10:20 +00003458 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCalld226f652010-08-21 09:40:31 +00003459 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCallaa81e162009-12-01 22:10:20 +00003460
3461 if (Result.isInvalid()) {
3462 Owned(Base);
3463 return ExprError();
3464 }
3465
3466 if (Result.get())
3467 return move(Result);
Sebastian Redlf3e63372010-05-07 09:25:11 +00003468
3469 // LookupMemberExpr can modify Base, and thus change BaseType
3470 BaseType = Base->getType();
John McCall129e2df2009-11-30 22:42:35 +00003471 }
3472
John McCall9ae2f072010-08-23 23:25:46 +00003473 return BuildMemberReferenceExpr(Base, BaseType,
John McCallc2233c52010-01-15 08:34:02 +00003474 OpLoc, IsArrow, SS, FirstQualifierInScope,
3475 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003476}
3477
John McCall60d7b3a2010-08-24 06:29:42 +00003478ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003479Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCallaa81e162009-12-01 22:10:20 +00003480 SourceLocation OpLoc, bool IsArrow,
3481 const CXXScopeSpec &SS,
John McCallc2233c52010-01-15 08:34:02 +00003482 NamedDecl *FirstQualifierInScope,
John McCall129e2df2009-11-30 22:42:35 +00003483 LookupResult &R,
Douglas Gregor06a9f362010-05-01 20:49:11 +00003484 const TemplateArgumentListInfo *TemplateArgs,
3485 bool SuppressQualifierCheck) {
John McCallaa81e162009-12-01 22:10:20 +00003486 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00003487 if (IsArrow) {
3488 assert(BaseType->isPointerType());
3489 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3490 }
John McCall161755a2010-04-06 21:38:20 +00003491 R.setBaseObjectType(BaseType);
John McCall129e2df2009-11-30 22:42:35 +00003492
John McCall9ae2f072010-08-23 23:25:46 +00003493 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara25777432010-08-11 22:01:17 +00003494 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3495 DeclarationName MemberName = MemberNameInfo.getName();
3496 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall129e2df2009-11-30 22:42:35 +00003497
3498 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00003499 return ExprError();
3500
John McCall129e2df2009-11-30 22:42:35 +00003501 if (R.empty()) {
3502 // Rederive where we looked up.
3503 DeclContext *DC = (SS.isSet()
3504 ? computeDeclContext(SS, false)
3505 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00003506
John McCall129e2df2009-11-30 22:42:35 +00003507 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00003508 << MemberName << DC
3509 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00003510 return ExprError();
3511 }
3512
John McCallc2233c52010-01-15 08:34:02 +00003513 // Diagnose lookups that find only declarations from a non-base
3514 // type. This is possible for either qualified lookups (which may
3515 // have been qualified with an unrelated type) or implicit member
3516 // expressions (which were found with unqualified lookup and thus
3517 // may have come from an enclosing scope). Note that it's okay for
3518 // lookup to find declarations from a non-base type as long as those
3519 // aren't the ones picked by overload resolution.
3520 if ((SS.isSet() || !BaseExpr ||
3521 (isa<CXXThisExpr>(BaseExpr) &&
3522 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00003523 !SuppressQualifierCheck &&
John McCallc2233c52010-01-15 08:34:02 +00003524 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00003525 return ExprError();
3526
3527 // Construct an unresolved result if we in fact got an unresolved
3528 // result.
3529 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallc373d482010-01-27 01:50:18 +00003530 // Suppress any lookup-related diagnostics; we'll do these when we
3531 // pick a member.
3532 R.suppressDiagnostics();
3533
John McCall129e2df2009-11-30 22:42:35 +00003534 UnresolvedMemberExpr *MemExpr
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003535 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00003536 BaseExpr, BaseExprType,
3537 IsArrow, OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00003538 Qualifier, SS.getRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +00003539 MemberNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00003540 TemplateArgs, R.begin(), R.end());
John McCall129e2df2009-11-30 22:42:35 +00003541
3542 return Owned(MemExpr);
3543 }
3544
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003545 assert(R.isSingleResult());
John McCall161755a2010-04-06 21:38:20 +00003546 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall129e2df2009-11-30 22:42:35 +00003547 NamedDecl *MemberDecl = R.getFoundDecl();
3548
3549 // FIXME: diagnose the presence of template arguments now.
3550
3551 // If the decl being referenced had an error, return an error for this
3552 // sub-expr without emitting another error, in order to avoid cascading
3553 // error cases.
3554 if (MemberDecl->isInvalidDecl())
3555 return ExprError();
3556
John McCallaa81e162009-12-01 22:10:20 +00003557 // Handle the implicit-member-access case.
3558 if (!BaseExpr) {
3559 // If this is not an instance member, convert to a non-member access.
John McCall161755a2010-04-06 21:38:20 +00003560 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnara25777432010-08-11 22:01:17 +00003561 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCallaa81e162009-12-01 22:10:20 +00003562
Douglas Gregor828a1972010-01-07 23:12:05 +00003563 SourceLocation Loc = R.getNameLoc();
3564 if (SS.getRange().isValid())
3565 Loc = SS.getRange().getBegin();
3566 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003567 }
3568
John McCall129e2df2009-11-30 22:42:35 +00003569 bool ShouldCheckUse = true;
3570 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3571 // Don't diagnose the use of a virtual member function unless it's
3572 // explicitly qualified.
3573 if (MD->isVirtual() && !SS.isSet())
3574 ShouldCheckUse = false;
3575 }
3576
3577 // Check the use of this member.
3578 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3579 Owned(BaseExpr);
3580 return ExprError();
3581 }
3582
John McCallf6a16482010-12-04 03:47:34 +00003583 // Perform a property load on the base regardless of whether we
3584 // actually need it for the declaration.
3585 if (BaseExpr->getObjectKind() == OK_ObjCProperty)
3586 ConvertPropertyForRValue(BaseExpr);
3587
John McCalldfa1edb2010-11-23 20:48:44 +00003588 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3589 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3590 SS, FD, FoundDecl, MemberNameInfo);
John McCall129e2df2009-11-30 22:42:35 +00003591
Francois Pichet87c2e122010-11-21 06:08:52 +00003592 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3593 // We may have found a field within an anonymous union or struct
3594 // (C++ [class.union]).
John McCall5808ce42011-02-03 08:15:49 +00003595 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCallf6a16482010-12-04 03:47:34 +00003596 BaseExpr, OpLoc);
Francois Pichet87c2e122010-11-21 06:08:52 +00003597
John McCall129e2df2009-11-30 22:42:35 +00003598 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3599 MarkDeclarationReferenced(MemberLoc, Var);
3600 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003601 Var, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003602 Var->getType().getNonReferenceType(),
John McCall09431682010-11-18 19:01:18 +00003603 VK_LValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003604 }
3605
John McCallf89e55a2010-11-18 06:31:45 +00003606 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall129e2df2009-11-30 22:42:35 +00003607 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3608 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003609 MemberFn, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003610 MemberFn->getType(),
3611 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3612 OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003613 }
John McCallf89e55a2010-11-18 06:31:45 +00003614 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall129e2df2009-11-30 22:42:35 +00003615
3616 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3617 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3618 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003619 Enum, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003620 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003621 }
3622
3623 Owned(BaseExpr);
3624
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003625 // We found something that we didn't expect. Complain.
John McCall129e2df2009-11-30 22:42:35 +00003626 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnara25777432010-08-11 22:01:17 +00003627 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003628 << MemberName << BaseType << int(IsArrow);
3629 else
3630 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3631 << MemberName << BaseType << int(IsArrow);
John McCall129e2df2009-11-30 22:42:35 +00003632
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003633 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3634 << MemberName;
Douglas Gregor2b147f02010-04-25 21:15:30 +00003635 R.suppressDiagnostics();
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003636 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00003637}
3638
John McCall028d3972010-12-15 16:46:44 +00003639/// Given that normal member access failed on the given expression,
3640/// and given that the expression's type involves builtin-id or
3641/// builtin-Class, decide whether substituting in the redefinition
3642/// types would be profitable. The redefinition type is whatever
3643/// this translation unit tried to typedef to id/Class; we store
3644/// it to the side and then re-use it in places like this.
3645static bool ShouldTryAgainWithRedefinitionType(Sema &S, Expr *&base) {
3646 const ObjCObjectPointerType *opty
3647 = base->getType()->getAs<ObjCObjectPointerType>();
3648 if (!opty) return false;
3649
3650 const ObjCObjectType *ty = opty->getObjectType();
3651
3652 QualType redef;
3653 if (ty->isObjCId()) {
3654 redef = S.Context.ObjCIdRedefinitionType;
3655 } else if (ty->isObjCClass()) {
3656 redef = S.Context.ObjCClassRedefinitionType;
3657 } else {
3658 return false;
3659 }
3660
3661 // Do the substitution as long as the redefinition type isn't just a
3662 // possibly-qualified pointer to builtin-id or builtin-Class again.
3663 opty = redef->getAs<ObjCObjectPointerType>();
3664 if (opty && !opty->getObjectType()->getInterface() != 0)
3665 return false;
3666
3667 S.ImpCastExprToType(base, redef, CK_BitCast);
3668 return true;
3669}
3670
John McCall129e2df2009-11-30 22:42:35 +00003671/// Look up the given member of the given non-type-dependent
3672/// expression. This can return in one of two ways:
3673/// * If it returns a sentinel null-but-valid result, the caller will
3674/// assume that lookup was performed and the results written into
3675/// the provided structure. It will take over from there.
3676/// * Otherwise, the returned expression will be produced in place of
3677/// an ordinary member expression.
3678///
3679/// The ObjCImpDecl bit is a gross hack that will need to be properly
3680/// fixed for ObjC++.
John McCall60d7b3a2010-08-24 06:29:42 +00003681ExprResult
John McCall129e2df2009-11-30 22:42:35 +00003682Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCall812c1542009-12-07 22:46:59 +00003683 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003684 CXXScopeSpec &SS,
John McCalld226f652010-08-21 09:40:31 +00003685 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003686 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00003687
Steve Naroff3cc4af82007-12-16 21:42:28 +00003688 // Perform default conversions.
3689 DefaultFunctionArrayConversion(BaseExpr);
John McCall5e3c67b2010-12-15 04:42:30 +00003690 if (IsArrow) DefaultLvalueConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003691
Steve Naroffdfa6aae2007-07-26 03:11:44 +00003692 QualType BaseType = BaseExpr->getType();
John McCall129e2df2009-11-30 22:42:35 +00003693 assert(!BaseType->isDependentType());
3694
3695 DeclarationName MemberName = R.getLookupName();
3696 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00003697
John McCall028d3972010-12-15 16:46:44 +00003698 // For later type-checking purposes, turn arrow accesses into dot
3699 // accesses. The only access type we support that doesn't follow
3700 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
3701 // and those never use arrows, so this is unaffected.
3702 if (IsArrow) {
3703 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3704 BaseType = Ptr->getPointeeType();
3705 else if (const ObjCObjectPointerType *Ptr
3706 = BaseType->getAs<ObjCObjectPointerType>())
3707 BaseType = Ptr->getPointeeType();
3708 else if (BaseType->isRecordType()) {
3709 // Recover from arrow accesses to records, e.g.:
3710 // struct MyRecord foo;
3711 // foo->bar
3712 // This is actually well-formed in C++ if MyRecord has an
3713 // overloaded operator->, but that should have been dealt with
3714 // by now.
3715 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3716 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3717 << FixItHint::CreateReplacement(OpLoc, ".");
3718 IsArrow = false;
3719 } else {
3720 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3721 << BaseType << BaseExpr->getSourceRange();
3722 return ExprError();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00003723 }
3724 }
3725
John McCall028d3972010-12-15 16:46:44 +00003726 // Handle field access to simple records.
3727 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
3728 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
3729 RTy, OpLoc, SS, HasTemplateArgs))
3730 return ExprError();
3731
3732 // Returning valid-but-null is how we indicate to the caller that
3733 // the lookup result was filled in.
3734 return Owned((Expr*) 0);
David Chisnall0f436562009-08-17 16:35:33 +00003735 }
John McCall129e2df2009-11-30 22:42:35 +00003736
John McCall028d3972010-12-15 16:46:44 +00003737 // Handle ivar access to Objective-C objects.
3738 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003739 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall028d3972010-12-15 16:46:44 +00003740
3741 // There are three cases for the base type:
3742 // - builtin id (qualified or unqualified)
3743 // - builtin Class (qualified or unqualified)
3744 // - an interface
3745 ObjCInterfaceDecl *IDecl = OTy->getInterface();
3746 if (!IDecl) {
3747 // There's an implicit 'isa' ivar on all objects.
3748 // But we only actually find it this way on objects of type 'id',
3749 // apparently.
3750 if (OTy->isObjCId() && Member->isStr("isa"))
3751 return Owned(new (Context) ObjCIsaExpr(BaseExpr, IsArrow, MemberLoc,
3752 Context.getObjCClassType()));
3753
3754 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3755 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3756 ObjCImpDecl, HasTemplateArgs);
3757 goto fail;
3758 }
3759
3760 ObjCInterfaceDecl *ClassDeclared;
3761 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
3762
3763 if (!IV) {
3764 // Attempt to correct for typos in ivar names.
3765 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3766 LookupMemberName);
3767 if (CorrectTypo(Res, 0, 0, IDecl, false,
3768 IsArrow ? CTC_ObjCIvarLookup
3769 : CTC_ObjCPropertyLookup) &&
3770 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
3771 Diag(R.getNameLoc(),
3772 diag::err_typecheck_member_reference_ivar_suggest)
3773 << IDecl->getDeclName() << MemberName << IV->getDeclName()
3774 << FixItHint::CreateReplacement(R.getNameLoc(),
3775 IV->getNameAsString());
3776 Diag(IV->getLocation(), diag::note_previous_decl)
3777 << IV->getDeclName();
3778 } else {
3779 Res.clear();
3780 Res.setLookupName(Member);
3781
3782 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
3783 << IDecl->getDeclName() << MemberName
3784 << BaseExpr->getSourceRange();
3785 return ExprError();
3786 }
3787 }
3788
3789 // If the decl being referenced had an error, return an error for this
3790 // sub-expr without emitting another error, in order to avoid cascading
3791 // error cases.
3792 if (IV->isInvalidDecl())
3793 return ExprError();
3794
3795 // Check whether we can reference this field.
3796 if (DiagnoseUseOfDecl(IV, MemberLoc))
3797 return ExprError();
3798 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3799 IV->getAccessControl() != ObjCIvarDecl::Package) {
3800 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3801 if (ObjCMethodDecl *MD = getCurMethodDecl())
3802 ClassOfMethodDecl = MD->getClassInterface();
3803 else if (ObjCImpDecl && getCurFunctionDecl()) {
3804 // Case of a c-function declared inside an objc implementation.
3805 // FIXME: For a c-style function nested inside an objc implementation
3806 // class, there is no implementation context available, so we pass
3807 // down the context as argument to this routine. Ideally, this context
3808 // need be passed down in the AST node and somehow calculated from the
3809 // AST for a function decl.
3810 if (ObjCImplementationDecl *IMPD =
3811 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
3812 ClassOfMethodDecl = IMPD->getClassInterface();
3813 else if (ObjCCategoryImplDecl* CatImplClass =
3814 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
3815 ClassOfMethodDecl = CatImplClass->getClassInterface();
3816 }
3817
3818 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3819 if (ClassDeclared != IDecl ||
3820 ClassOfMethodDecl != ClassDeclared)
3821 Diag(MemberLoc, diag::error_private_ivar_access)
3822 << IV->getDeclName();
3823 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3824 // @protected
3825 Diag(MemberLoc, diag::error_protected_ivar_access)
3826 << IV->getDeclName();
3827 }
3828
3829 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3830 MemberLoc, BaseExpr,
3831 IsArrow));
3832 }
3833
3834 // Objective-C property access.
3835 const ObjCObjectPointerType *OPT;
3836 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
3837 // This actually uses the base as an r-value.
3838 DefaultLvalueConversion(BaseExpr);
3839 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr->getType()));
3840
3841 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3842
3843 const ObjCObjectType *OT = OPT->getObjectType();
3844
3845 // id, with and without qualifiers.
3846 if (OT->isObjCId()) {
3847 // Check protocols on qualified interfaces.
3848 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3849 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
3850 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3851 // Check the use of this declaration
3852 if (DiagnoseUseOfDecl(PD, MemberLoc))
3853 return ExprError();
3854
3855 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3856 VK_LValue,
3857 OK_ObjCProperty,
3858 MemberLoc,
3859 BaseExpr));
3860 }
3861
3862 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3863 // Check the use of this method.
3864 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3865 return ExprError();
3866 Selector SetterSel =
3867 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3868 PP.getSelectorTable(), Member);
3869 ObjCMethodDecl *SMD = 0;
3870 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
3871 SetterSel, Context))
3872 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3873 QualType PType = OMD->getSendResultType();
3874
3875 ExprValueKind VK = VK_LValue;
3876 if (!getLangOptions().CPlusPlus &&
3877 IsCForbiddenLValueType(Context, PType))
3878 VK = VK_RValue;
3879 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3880
3881 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
3882 VK, OK,
3883 MemberLoc, BaseExpr));
3884 }
3885 }
3886
3887 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3888 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3889 ObjCImpDecl, HasTemplateArgs);
3890
3891 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3892 << MemberName << BaseType);
3893 }
3894
3895 // 'Class', unqualified only.
3896 if (OT->isObjCClass()) {
3897 // Only works in a method declaration (??!).
3898 ObjCMethodDecl *MD = getCurMethodDecl();
3899 if (!MD) {
3900 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3901 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3902 ObjCImpDecl, HasTemplateArgs);
3903
3904 goto fail;
3905 }
3906
3907 // Also must look for a getter name which uses property syntax.
3908 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003909 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3910 ObjCMethodDecl *Getter;
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003911 if ((Getter = IFace->lookupClassMethod(Sel))) {
3912 // Check the use of this method.
3913 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3914 return ExprError();
John McCall028d3972010-12-15 16:46:44 +00003915 } else
Fariborz Jahanian74b27562010-12-03 23:37:08 +00003916 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003917 // If we found a getter then this may be a valid dot-reference, we
3918 // will look for the matching setter, in case it is needed.
3919 Selector SetterSel =
John McCall028d3972010-12-15 16:46:44 +00003920 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3921 PP.getSelectorTable(), Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003922 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3923 if (!Setter) {
3924 // If this reference is in an @implementation, also check for 'private'
3925 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +00003926 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003927 }
3928 // Look through local category implementations associated with the class.
3929 if (!Setter)
3930 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003931
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003932 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3933 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003934
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003935 if (Getter || Setter) {
3936 QualType PType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003937
John McCall09431682010-11-18 19:01:18 +00003938 ExprValueKind VK = VK_LValue;
3939 if (Getter) {
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003940 PType = Getter->getSendResultType();
John McCall09431682010-11-18 19:01:18 +00003941 if (!getLangOptions().CPlusPlus &&
3942 IsCForbiddenLValueType(Context, PType))
3943 VK = VK_RValue;
3944 } else {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003945 // Get the expression type from Setter's incoming parameter.
3946 PType = (*(Setter->param_end() -1))->getType();
John McCall09431682010-11-18 19:01:18 +00003947 }
3948 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3949
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003950 // FIXME: we must check that the setter has property type.
John McCall12f78a62010-12-02 01:19:52 +00003951 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
3952 PType, VK, OK,
3953 MemberLoc, BaseExpr));
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003954 }
John McCall028d3972010-12-15 16:46:44 +00003955
3956 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3957 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3958 ObjCImpDecl, HasTemplateArgs);
3959
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003960 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall028d3972010-12-15 16:46:44 +00003961 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00003962 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003963
John McCall028d3972010-12-15 16:46:44 +00003964 // Normal property access.
3965 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc,
3966 SourceLocation(), QualType(), false);
Steve Naroff14108da2009-07-10 23:34:53 +00003967 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003968
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003969 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00003970 if (BaseType->isExtVectorType()) {
John McCall5e3c67b2010-12-15 04:42:30 +00003971 // FIXME: this expr should store IsArrow.
Anders Carlsson8f28f992009-08-26 18:25:21 +00003972 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall5e3c67b2010-12-15 04:42:30 +00003973 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr->getValueKind());
John McCall09431682010-11-18 19:01:18 +00003974 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
3975 Member, MemberLoc);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003976 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003977 return ExprError();
John McCall09431682010-11-18 19:01:18 +00003978
3979 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr,
3980 *Member, MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003981 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003982
John McCall028d3972010-12-15 16:46:44 +00003983 // Adjust builtin-sel to the appropriate redefinition type if that's
3984 // not just a pointer to builtin-sel again.
3985 if (IsArrow &&
3986 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
3987 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
3988 ImpCastExprToType(BaseExpr, Context.ObjCSelRedefinitionType, CK_BitCast);
3989 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3990 ObjCImpDecl, HasTemplateArgs);
3991 }
3992
3993 // Failure cases.
3994 fail:
3995
3996 // There's a possible road to recovery for function types.
3997 const FunctionType *Fun = 0;
3998
3999 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4000 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
4001 // fall out, handled below.
4002
4003 // Recover from dot accesses to pointers, e.g.:
4004 // type *foo;
4005 // foo.bar
4006 // This is actually well-formed in two cases:
4007 // - 'type' is an Objective C type
4008 // - 'bar' is a pseudo-destructor name which happens to refer to
4009 // the appropriate pointer type
Argyrios Kyrtzidisdf8dc5d2011-01-25 23:16:36 +00004010 } else if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
John McCall028d3972010-12-15 16:46:44 +00004011 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
4012 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4013 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
4014 << FixItHint::CreateReplacement(OpLoc, "->");
4015
4016 // Recurse as an -> access.
4017 IsArrow = true;
4018 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4019 ObjCImpDecl, HasTemplateArgs);
4020 }
4021 } else {
4022 Fun = BaseType->getAs<FunctionType>();
4023 }
4024
4025 // If the user is trying to apply -> or . to a function pointer
4026 // type, it's probably because they forgot parentheses to call that
4027 // function. Suggest the addition of those parentheses, build the
4028 // call, and continue on.
4029 if (Fun || BaseType == Context.OverloadTy) {
4030 bool TryCall;
4031 if (BaseType == Context.OverloadTy) {
4032 TryCall = true;
4033 } else {
4034 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
4035 TryCall = (FPT->getNumArgs() == 0);
4036 } else {
4037 TryCall = true;
4038 }
4039
4040 if (TryCall) {
4041 QualType ResultTy = Fun->getResultType();
4042 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
4043 (IsArrow && ResultTy->isPointerType() &&
4044 ResultTy->getAs<PointerType>()->getPointeeType()->isRecordType());
4045 }
4046 }
4047
4048
4049 if (TryCall) {
4050 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
4051 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
4052 << QualType(Fun, 0)
4053 << FixItHint::CreateInsertion(Loc, "()");
4054
4055 ExprResult NewBase
4056 = ActOnCallExpr(0, BaseExpr, Loc, MultiExprArg(*this, 0, 0), Loc);
4057 if (NewBase.isInvalid())
4058 return ExprError();
4059 BaseExpr = NewBase.takeAs<Expr>();
4060
4061
4062 DefaultFunctionArrayConversion(BaseExpr);
4063 BaseType = BaseExpr->getType();
4064
4065 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4066 ObjCImpDecl, HasTemplateArgs);
4067 }
4068 }
4069
Douglas Gregor214f31a2009-03-27 06:00:30 +00004070 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
4071 << BaseType << BaseExpr->getSourceRange();
4072
Douglas Gregor214f31a2009-03-27 06:00:30 +00004073 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00004074}
4075
John McCall129e2df2009-11-30 22:42:35 +00004076/// The main callback when the parser finds something like
4077/// expression . [nested-name-specifier] identifier
4078/// expression -> [nested-name-specifier] identifier
4079/// where 'identifier' encompasses a fairly broad spectrum of
4080/// possibilities, including destructor and operator references.
4081///
4082/// \param OpKind either tok::arrow or tok::period
4083/// \param HasTrailingLParen whether the next token is '(', which
4084/// is used to diagnose mis-uses of special members that can
4085/// only be called
4086/// \param ObjCImpDecl the current ObjC @implementation decl;
4087/// this is an ugly hack around the fact that ObjC @implementations
4088/// aren't properly put in the context chain
John McCall60d7b3a2010-08-24 06:29:42 +00004089ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall5e3c67b2010-12-15 04:42:30 +00004090 SourceLocation OpLoc,
4091 tok::TokenKind OpKind,
4092 CXXScopeSpec &SS,
4093 UnqualifiedId &Id,
4094 Decl *ObjCImpDecl,
4095 bool HasTrailingLParen) {
John McCall129e2df2009-11-30 22:42:35 +00004096 if (SS.isSet() && SS.isInvalid())
4097 return ExprError();
4098
Francois Pichetdbee3412011-01-18 05:04:39 +00004099 // Warn about the explicit constructor calls Microsoft extension.
4100 if (getLangOptions().Microsoft &&
4101 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4102 Diag(Id.getSourceRange().getBegin(),
4103 diag::ext_ms_explicit_constructor_call);
4104
John McCall129e2df2009-11-30 22:42:35 +00004105 TemplateArgumentListInfo TemplateArgsBuffer;
4106
4107 // Decompose the name into its component parts.
Abramo Bagnara25777432010-08-11 22:01:17 +00004108 DeclarationNameInfo NameInfo;
John McCall129e2df2009-11-30 22:42:35 +00004109 const TemplateArgumentListInfo *TemplateArgs;
4110 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnara25777432010-08-11 22:01:17 +00004111 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004112
Abramo Bagnara25777432010-08-11 22:01:17 +00004113 DeclarationName Name = NameInfo.getName();
John McCall129e2df2009-11-30 22:42:35 +00004114 bool IsArrow = (OpKind == tok::arrow);
4115
4116 NamedDecl *FirstQualifierInScope
4117 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4118 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4119
4120 // This is a postfix expression, so get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004121 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004122 if (Result.isInvalid()) return ExprError();
4123 Base = Result.take();
John McCall129e2df2009-11-30 22:42:35 +00004124
Douglas Gregor01e56ae2010-04-12 20:54:26 +00004125 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4126 isDependentScopeSpecifier(SS)) {
John McCall9ae2f072010-08-23 23:25:46 +00004127 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00004128 IsArrow, OpLoc,
4129 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00004130 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004131 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00004132 LookupResult R(*this, NameInfo, LookupMemberName);
John McCallad00b772010-06-16 08:42:20 +00004133 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
4134 SS, ObjCImpDecl, TemplateArgs != 0);
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004135
John McCallad00b772010-06-16 08:42:20 +00004136 if (Result.isInvalid()) {
4137 Owned(Base);
4138 return ExprError();
4139 }
John McCall129e2df2009-11-30 22:42:35 +00004140
John McCallad00b772010-06-16 08:42:20 +00004141 if (Result.get()) {
4142 // The only way a reference to a destructor can be used is to
4143 // immediately call it, which falls into this case. If the
4144 // next token is not a '(', produce a diagnostic and build the
4145 // call now.
4146 if (!HasTrailingLParen &&
4147 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCall9ae2f072010-08-23 23:25:46 +00004148 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall129e2df2009-11-30 22:42:35 +00004149
John McCallad00b772010-06-16 08:42:20 +00004150 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00004151 }
4152
John McCall9ae2f072010-08-23 23:25:46 +00004153 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCallc2233c52010-01-15 08:34:02 +00004154 OpLoc, IsArrow, SS, FirstQualifierInScope,
4155 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004156 }
4157
4158 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00004159}
4160
John McCall60d7b3a2010-08-24 06:29:42 +00004161ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00004162 FunctionDecl *FD,
4163 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00004164 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004165 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00004166 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00004167 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00004168 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00004169 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004170 return ExprError();
4171 }
4172
4173 if (Param->hasUninstantiatedDefaultArg()) {
4174 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00004175
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004176 // Instantiate the expression.
4177 MultiLevelTemplateArgumentList ArgList
4178 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00004179
Nico Weber08e41a62010-11-29 18:19:25 +00004180 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004181 = ArgList.getInnermost();
4182 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4183 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004184
Nico Weber08e41a62010-11-29 18:19:25 +00004185 ExprResult Result;
4186 {
4187 // C++ [dcl.fct.default]p5:
4188 // The names in the [default argument] expression are bound, and
4189 // the semantic constraints are checked, at the point where the
4190 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00004191 ContextRAII SavedContext(*this, FD);
Nico Weber08e41a62010-11-29 18:19:25 +00004192 Result = SubstExpr(UninstExpr, ArgList);
4193 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004194 if (Result.isInvalid())
4195 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004196
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004197 // Check the expression as an initializer for the parameter.
4198 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004199 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004200 InitializationKind Kind
4201 = InitializationKind::CreateCopy(Param->getLocation(),
4202 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4203 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00004204
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004205 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4206 Result = InitSeq.Perform(*this, Entity, Kind,
4207 MultiExprArg(*this, &ResultE, 1));
4208 if (Result.isInvalid())
4209 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004210
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004211 // Build the default argument expression.
4212 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4213 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004214 }
4215
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004216 // If the default expression creates temporaries, we need to
4217 // push them to the current stack of expression temporaries so they'll
4218 // be properly destroyed.
4219 // FIXME: We should really be rebuilding the default argument with new
4220 // bound temporaries; see the comment in PR5810.
Douglas Gregor5833b0b2010-09-14 22:55:20 +00004221 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4222 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4223 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4224 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4225 ExprTemporaries.push_back(Temporary);
4226 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004227
4228 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00004229 // Just mark all of the declarations in this potentially-evaluated expression
4230 // as being "referenced".
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004231 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor036aed12009-12-23 23:03:06 +00004232 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004233}
4234
Douglas Gregor88a35142008-12-22 05:46:06 +00004235/// ConvertArgumentsForCall - Converts the arguments specified in
4236/// Args/NumArgs to the parameter types of the function FDecl with
4237/// function prototype Proto. Call is the call expression itself, and
4238/// Fn is the function expression. For a C++ member function, this
4239/// routine does not attempt to convert the object argument. Returns
4240/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004241bool
4242Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00004243 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00004244 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00004245 Expr **Args, unsigned NumArgs,
4246 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004247 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00004248 // assignment, to the types of the corresponding parameter, ...
4249 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004250 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004251
Douglas Gregor88a35142008-12-22 05:46:06 +00004252 // If too few arguments are available (and we don't have default
4253 // arguments for the remaining parameters), don't make the call.
4254 if (NumArgs < NumArgsInProto) {
4255 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4256 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004257 << Fn->getType()->isBlockPointerType()
Eric Christopherd77b9a22010-04-16 04:48:22 +00004258 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00004259 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00004260 }
4261
4262 // If too many are passed and not variadic, error on the extras and drop
4263 // them.
4264 if (NumArgs > NumArgsInProto) {
4265 if (!Proto->isVariadic()) {
4266 Diag(Args[NumArgsInProto]->getLocStart(),
4267 diag::err_typecheck_call_too_many_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004268 << Fn->getType()->isBlockPointerType()
Eric Christopherccfa9632010-04-16 04:56:46 +00004269 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00004270 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4271 Args[NumArgs-1]->getLocEnd());
4272 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004273 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004274 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004275 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004276 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004277 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004278 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004279 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4280 if (Fn->getType()->isBlockPointerType())
4281 CallType = VariadicBlock; // Block
4282 else if (isa<MemberExpr>(Fn))
4283 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004284 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004285 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004286 if (Invalid)
4287 return true;
4288 unsigned TotalNumArgs = AllArgs.size();
4289 for (unsigned i = 0; i < TotalNumArgs; ++i)
4290 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004291
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004292 return false;
4293}
Mike Stumpeed9cac2009-02-19 03:04:26 +00004294
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004295bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4296 FunctionDecl *FDecl,
4297 const FunctionProtoType *Proto,
4298 unsigned FirstProtoArg,
4299 Expr **Args, unsigned NumArgs,
4300 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004301 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004302 unsigned NumArgsInProto = Proto->getNumArgs();
4303 unsigned NumArgsToCheck = NumArgs;
4304 bool Invalid = false;
4305 if (NumArgs != NumArgsInProto)
4306 // Use default arguments for missing arguments
4307 NumArgsToCheck = NumArgsInProto;
4308 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00004309 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004310 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004311 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004312
Douglas Gregor88a35142008-12-22 05:46:06 +00004313 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004314 if (ArgIx < NumArgs) {
4315 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004316
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004317 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4318 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00004319 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004320 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004321 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004322
Douglas Gregora188ff22009-12-22 16:09:06 +00004323 // Pass the argument
4324 ParmVarDecl *Param = 0;
4325 if (FDecl && i < FDecl->getNumParams())
4326 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00004327
Douglas Gregora188ff22009-12-22 16:09:06 +00004328 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004329 Param? InitializedEntity::InitializeParameter(Context, Param)
4330 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCall60d7b3a2010-08-24 06:29:42 +00004331 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00004332 SourceLocation(),
4333 Owned(Arg));
Douglas Gregora188ff22009-12-22 16:09:06 +00004334 if (ArgE.isInvalid())
4335 return true;
4336
4337 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004338 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00004339 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004340
John McCall60d7b3a2010-08-24 06:29:42 +00004341 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004342 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004343 if (ArgExpr.isInvalid())
4344 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004345
Anders Carlsson56c5e332009-08-25 03:49:14 +00004346 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004347 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004348 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00004349 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004350
Douglas Gregor88a35142008-12-22 05:46:06 +00004351 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004352 if (CallType != VariadicDoesNotApply) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004353 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner40378332010-05-16 04:01:30 +00004354 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004355 Expr *Arg = Args[i];
Chris Lattner40378332010-05-16 04:01:30 +00004356 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004357 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00004358 }
4359 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004360 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00004361}
4362
Steve Narofff69936d2007-09-16 03:34:24 +00004363/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00004364/// This provides the location of the left/right parens and a list of comma
4365/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00004366ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004367Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004368 MultiExprArg args, SourceLocation RParenLoc,
4369 Expr *ExecConfig) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00004370 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00004371
4372 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004373 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00004374 if (Result.isInvalid()) return ExprError();
4375 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00004376
John McCall9ae2f072010-08-23 23:25:46 +00004377 Expr **Args = args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004378
Douglas Gregor88a35142008-12-22 05:46:06 +00004379 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00004380 // If this is a pseudo-destructor expression, build the call immediately.
4381 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4382 if (NumArgs > 0) {
4383 // Pseudo-destructor calls should not have any arguments.
4384 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00004385 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00004386 SourceRange(Args[0]->getLocStart(),
4387 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00004388
Douglas Gregora71d8192009-09-04 17:36:40 +00004389 NumArgs = 0;
4390 }
Mike Stump1eb44332009-09-09 15:08:12 +00004391
Douglas Gregora71d8192009-09-04 17:36:40 +00004392 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00004393 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00004394 }
Mike Stump1eb44332009-09-09 15:08:12 +00004395
Douglas Gregor17330012009-02-04 15:01:18 +00004396 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00004397 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00004398 // FIXME: Will need to cache the results of name lookup (including ADL) in
4399 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00004400 bool Dependent = false;
4401 if (Fn->isTypeDependent())
4402 Dependent = true;
4403 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4404 Dependent = true;
4405
Peter Collingbournee08ce652011-02-09 21:07:24 +00004406 if (Dependent) {
4407 if (ExecConfig) {
4408 return Owned(new (Context) CUDAKernelCallExpr(
4409 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4410 Context.DependentTy, VK_RValue, RParenLoc));
4411 } else {
4412 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4413 Context.DependentTy, VK_RValue,
4414 RParenLoc));
4415 }
4416 }
Douglas Gregor17330012009-02-04 15:01:18 +00004417
4418 // Determine whether this is a call to an object (C++ [over.call.object]).
4419 if (Fn->getType()->isRecordType())
4420 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004421 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00004422
John McCall129e2df2009-11-30 22:42:35 +00004423 Expr *NakedFn = Fn->IgnoreParens();
4424
4425 // Determine whether this is a call to an unresolved member function.
4426 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4427 // If lookup was unresolved but not dependent (i.e. didn't find
4428 // an unresolved using declaration), it has to be an overloaded
4429 // function set, which means it must contain either multiple
4430 // declarations (all methods or method templates) or a single
4431 // method template.
4432 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor2b147f02010-04-25 21:15:30 +00004433 isa<FunctionTemplateDecl>(
4434 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor958aeb02009-12-01 03:34:29 +00004435 (void)MemE;
John McCall129e2df2009-11-30 22:42:35 +00004436
John McCallaa81e162009-12-01 22:10:20 +00004437 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004438 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00004439 }
4440
Douglas Gregorfa047642009-02-04 00:32:51 +00004441 // Determine whether this is a call to a member function.
John McCall129e2df2009-11-30 22:42:35 +00004442 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00004443 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall129e2df2009-11-30 22:42:35 +00004444 if (isa<CXXMethodDecl>(MemDecl))
John McCallaa81e162009-12-01 22:10:20 +00004445 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004446 RParenLoc);
Douglas Gregore53060f2009-06-25 22:08:12 +00004447 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004448
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004449 // Determine whether this is a call to a pointer-to-member function.
John McCall129e2df2009-11-30 22:42:35 +00004450 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
John McCall2de56d12010-08-25 11:45:40 +00004451 if (BO->getOpcode() == BO_PtrMemD ||
4452 BO->getOpcode() == BO_PtrMemI) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00004453 if (const FunctionProtoType *FPT
4454 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004455 QualType ResultTy = FPT->getCallResultType(Context);
John McCallf89e55a2010-11-18 06:31:45 +00004456 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004457
Douglas Gregorfdc13a02011-02-04 12:57:49 +00004458 // Check that the object type isn't more qualified than the
4459 // member function we're calling.
4460 Qualifiers FuncQuals = Qualifiers::fromCVRMask(FPT->getTypeQuals());
4461 Qualifiers ObjectQuals
4462 = BO->getOpcode() == BO_PtrMemD
4463 ? BO->getLHS()->getType().getQualifiers()
4464 : BO->getLHS()->getType()->getAs<PointerType>()
4465 ->getPointeeType().getQualifiers();
4466
4467 Qualifiers Difference = ObjectQuals - FuncQuals;
4468 Difference.removeObjCGCAttr();
4469 Difference.removeAddressSpace();
4470 if (Difference) {
4471 std::string QualsString = Difference.getAsString();
4472 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
4473 << BO->getType().getUnqualifiedType()
4474 << QualsString
4475 << (QualsString.find(' ') == std::string::npos? 1 : 2);
4476 }
4477
John McCall9ae2f072010-08-23 23:25:46 +00004478 CXXMemberCallExpr *TheCall
Abramo Bagnara6c572f12010-12-03 21:39:42 +00004479 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
John McCallf89e55a2010-11-18 06:31:45 +00004480 NumArgs, ResultTy, VK,
John McCall9ae2f072010-08-23 23:25:46 +00004481 RParenLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004482
4483 if (CheckCallReturnType(FPT->getResultType(),
4484 BO->getRHS()->getSourceRange().getBegin(),
John McCall9ae2f072010-08-23 23:25:46 +00004485 TheCall, 0))
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004486 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00004487
John McCall9ae2f072010-08-23 23:25:46 +00004488 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004489 RParenLoc))
4490 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004491
John McCall9ae2f072010-08-23 23:25:46 +00004492 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004493 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004494 return ExprError(Diag(Fn->getLocStart(),
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004495 diag::err_typecheck_call_not_function)
4496 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004497 }
4498 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004499 }
4500
Douglas Gregorfa047642009-02-04 00:32:51 +00004501 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00004502 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004503 // lookup and whether there were any explicitly-specified template arguments.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004504
Eli Friedmanefa42f72009-12-26 03:35:45 +00004505 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00004506 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4507 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4508 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004509 RParenLoc, ExecConfig);
Douglas Gregoref9b1492010-11-09 20:03:54 +00004510 }
4511
John McCall3b4294e2009-12-16 12:17:52 +00004512 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00004513 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4514 if (UnOp->getOpcode() == UO_AddrOf)
4515 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4516
John McCall3b4294e2009-12-16 12:17:52 +00004517 if (isa<DeclRefExpr>(NakedFn))
4518 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4519
Peter Collingbournee08ce652011-02-09 21:07:24 +00004520 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
4521 ExecConfig);
4522}
4523
4524ExprResult
4525Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4526 MultiExprArg execConfig, SourceLocation GGGLoc) {
4527 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4528 if (!ConfigDecl)
4529 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4530 << "cudaConfigureCall");
4531 QualType ConfigQTy = ConfigDecl->getType();
4532
4533 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4534 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
4535
4536 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCallaa81e162009-12-01 22:10:20 +00004537}
4538
John McCall3b4294e2009-12-16 12:17:52 +00004539/// BuildResolvedCallExpr - Build a call to a resolved expression,
4540/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00004541/// unary-convert to an expression of function-pointer or
4542/// block-pointer type.
4543///
4544/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00004545ExprResult
John McCallaa81e162009-12-01 22:10:20 +00004546Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4547 SourceLocation LParenLoc,
4548 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004549 SourceLocation RParenLoc,
4550 Expr *Config) {
John McCallaa81e162009-12-01 22:10:20 +00004551 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4552
Chris Lattner04421082008-04-08 04:40:51 +00004553 // Promote the function operand.
4554 UsualUnaryConversions(Fn);
4555
Chris Lattner925e60d2007-12-28 05:29:59 +00004556 // Make the call expr early, before semantic checks. This guarantees cleanup
4557 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00004558 CallExpr *TheCall;
4559 if (Config) {
4560 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4561 cast<CallExpr>(Config),
4562 Args, NumArgs,
4563 Context.BoolTy,
4564 VK_RValue,
4565 RParenLoc);
4566 } else {
4567 TheCall = new (Context) CallExpr(Context, Fn,
4568 Args, NumArgs,
4569 Context.BoolTy,
4570 VK_RValue,
4571 RParenLoc);
4572 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004573
Steve Naroffdd972f22008-09-05 22:11:13 +00004574 const FunctionType *FuncT;
4575 if (!Fn->getType()->isBlockPointerType()) {
4576 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4577 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00004578 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00004579 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00004580 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4581 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00004582 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00004583 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00004584 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00004585 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00004586 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004587 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00004588 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4589 << Fn->getType() << Fn->getSourceRange());
4590
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004591 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004592 if (CheckCallReturnType(FuncT->getResultType(),
John McCall9ae2f072010-08-23 23:25:46 +00004593 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004594 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004595 return ExprError();
4596
Chris Lattner925e60d2007-12-28 05:29:59 +00004597 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004598 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00004599 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00004600
Douglas Gregor72564e72009-02-26 23:50:07 +00004601 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00004602 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00004603 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00004604 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00004605 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004606 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00004607
Douglas Gregor74734d52009-04-02 15:37:10 +00004608 if (FDecl) {
4609 // Check if we have too few/too many template arguments, based
4610 // on our knowledge of the function definition.
4611 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00004612 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004613 const FunctionProtoType *Proto
4614 = Def->getType()->getAs<FunctionProtoType>();
4615 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004616 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4617 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004618 }
Douglas Gregor46542412010-10-25 20:39:23 +00004619
4620 // If the function we're calling isn't a function prototype, but we have
4621 // a function prototype from a prior declaratiom, use that prototype.
4622 if (!FDecl->hasPrototype())
4623 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00004624 }
4625
Steve Naroffb291ab62007-08-28 23:30:39 +00004626 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00004627 for (unsigned i = 0; i != NumArgs; i++) {
4628 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00004629
4630 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004631 InitializedEntity Entity
4632 = InitializedEntity::InitializeParameter(Context,
4633 Proto->getArgType(i));
4634 ExprResult ArgE = PerformCopyInitialization(Entity,
4635 SourceLocation(),
4636 Owned(Arg));
4637 if (ArgE.isInvalid())
4638 return true;
4639
4640 Arg = ArgE.takeAs<Expr>();
4641
4642 } else {
4643 DefaultArgumentPromotion(Arg);
Douglas Gregor46542412010-10-25 20:39:23 +00004644 }
4645
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004646 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4647 Arg->getType(),
4648 PDiag(diag::err_call_incomplete_argument)
4649 << Arg->getSourceRange()))
4650 return ExprError();
4651
Chris Lattner925e60d2007-12-28 05:29:59 +00004652 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00004653 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004654 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004655
Douglas Gregor88a35142008-12-22 05:46:06 +00004656 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4657 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004658 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4659 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00004660
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00004661 // Check for sentinels
4662 if (NDecl)
4663 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00004664
Chris Lattner59907c42007-08-10 20:18:51 +00004665 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00004666 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00004667 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00004668 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004669
Fariborz Jahanian67aba812010-11-30 17:35:24 +00004670 if (unsigned BuiltinID = FDecl->getBuiltinID())
4671 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00004672 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00004673 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00004674 return ExprError();
4675 }
Chris Lattner59907c42007-08-10 20:18:51 +00004676
John McCall9ae2f072010-08-23 23:25:46 +00004677 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00004678}
4679
John McCall60d7b3a2010-08-24 06:29:42 +00004680ExprResult
John McCallb3d87482010-08-24 05:47:05 +00004681Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004682 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00004683 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00004684 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00004685 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00004686
4687 TypeSourceInfo *TInfo;
4688 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4689 if (!TInfo)
4690 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4691
John McCall9ae2f072010-08-23 23:25:46 +00004692 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00004693}
4694
John McCall60d7b3a2010-08-24 06:29:42 +00004695ExprResult
John McCall42f56b52010-01-18 19:35:47 +00004696Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCall9ae2f072010-08-23 23:25:46 +00004697 SourceLocation RParenLoc, Expr *literalExpr) {
John McCall42f56b52010-01-18 19:35:47 +00004698 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00004699
Eli Friedman6223c222008-05-20 05:22:08 +00004700 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004701 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4702 PDiag(diag::err_illegal_decl_array_incomplete_type)
4703 << SourceRange(LParenLoc,
4704 literalExpr->getSourceRange().getEnd())))
4705 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004706 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004707 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4708 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004709 } else if (!literalType->isDependentType() &&
4710 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00004711 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00004712 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00004713 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004714 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00004715
Douglas Gregor99a2e602009-12-16 01:38:02 +00004716 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00004717 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004718 InitializationKind Kind
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004719 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor99a2e602009-12-16 01:38:02 +00004720 /*IsCStyleCast=*/true);
Eli Friedman08544622009-12-22 02:35:53 +00004721 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00004722 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00004723 MultiExprArg(*this, &literalExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00004724 &literalType);
4725 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004726 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00004727 literalExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00004728
Chris Lattner371f2582008-12-04 23:50:19 +00004729 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00004730 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00004731 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004732 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00004733 }
Eli Friedman08544622009-12-22 02:35:53 +00004734
John McCallf89e55a2010-11-18 06:31:45 +00004735 // In C, compound literals are l-values for some reason.
4736 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
4737
John McCall1d7d8d62010-01-19 22:33:45 +00004738 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCallf89e55a2010-11-18 06:31:45 +00004739 VK, literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00004740}
4741
John McCall60d7b3a2010-08-24 06:29:42 +00004742ExprResult
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004743Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004744 SourceLocation RBraceLoc) {
4745 unsigned NumInit = initlist.size();
John McCall9ae2f072010-08-23 23:25:46 +00004746 Expr **InitList = initlist.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00004747
Steve Naroff08d92e42007-09-15 18:49:24 +00004748 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00004749 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004750
Ted Kremenek709210f2010-04-13 23:39:13 +00004751 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4752 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00004753 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004754 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00004755}
4756
John McCallf3ea8cf2010-11-14 08:17:51 +00004757/// Prepares for a scalar cast, performing all the necessary stages
4758/// except the final cast and returning the kind required.
4759static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
4760 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4761 // Also, callers should have filtered out the invalid cases with
4762 // pointers. Everything else should be possible.
4763
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004764 QualType SrcTy = Src->getType();
John McCallf3ea8cf2010-11-14 08:17:51 +00004765 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00004766 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00004767
John McCalldaa8e4e2010-11-15 09:13:47 +00004768 switch (SrcTy->getScalarTypeKind()) {
4769 case Type::STK_MemberPointer:
4770 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004771
John McCalldaa8e4e2010-11-15 09:13:47 +00004772 case Type::STK_Pointer:
4773 switch (DestTy->getScalarTypeKind()) {
4774 case Type::STK_Pointer:
4775 return DestTy->isObjCObjectPointerType() ?
John McCallf3ea8cf2010-11-14 08:17:51 +00004776 CK_AnyPointerToObjCPointerCast :
4777 CK_BitCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004778 case Type::STK_Bool:
4779 return CK_PointerToBoolean;
4780 case Type::STK_Integral:
4781 return CK_PointerToIntegral;
4782 case Type::STK_Floating:
4783 case Type::STK_FloatingComplex:
4784 case Type::STK_IntegralComplex:
4785 case Type::STK_MemberPointer:
4786 llvm_unreachable("illegal cast from pointer");
4787 }
4788 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004789
John McCalldaa8e4e2010-11-15 09:13:47 +00004790 case Type::STK_Bool: // casting from bool is like casting from an integer
4791 case Type::STK_Integral:
4792 switch (DestTy->getScalarTypeKind()) {
4793 case Type::STK_Pointer:
John McCallf3ea8cf2010-11-14 08:17:51 +00004794 if (Src->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00004795 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00004796 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00004797 case Type::STK_Bool:
4798 return CK_IntegralToBoolean;
4799 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00004800 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004801 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004802 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004803 case Type::STK_IntegralComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004804 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCall8786da72010-12-14 17:51:41 +00004805 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004806 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004807 case Type::STK_FloatingComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004808 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004809 CK_IntegralToFloating);
4810 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004811 case Type::STK_MemberPointer:
4812 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004813 }
4814 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004815
John McCalldaa8e4e2010-11-15 09:13:47 +00004816 case Type::STK_Floating:
4817 switch (DestTy->getScalarTypeKind()) {
4818 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004819 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004820 case Type::STK_Bool:
4821 return CK_FloatingToBoolean;
4822 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00004823 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004824 case Type::STK_FloatingComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004825 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCall8786da72010-12-14 17:51:41 +00004826 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004827 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004828 case Type::STK_IntegralComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004829 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004830 CK_FloatingToIntegral);
4831 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004832 case Type::STK_Pointer:
4833 llvm_unreachable("valid float->pointer cast?");
4834 case Type::STK_MemberPointer:
4835 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004836 }
4837 break;
4838
John McCalldaa8e4e2010-11-15 09:13:47 +00004839 case Type::STK_FloatingComplex:
4840 switch (DestTy->getScalarTypeKind()) {
4841 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004842 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004843 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004844 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00004845 case Type::STK_Floating: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004846 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00004847 if (S.Context.hasSameType(ET, DestTy))
4848 return CK_FloatingComplexToReal;
4849 S.ImpCastExprToType(Src, ET, CK_FloatingComplexToReal);
4850 return CK_FloatingCast;
4851 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004852 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004853 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004854 case Type::STK_Integral:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004855 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004856 CK_FloatingComplexToReal);
4857 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004858 case Type::STK_Pointer:
4859 llvm_unreachable("valid complex float->pointer cast?");
4860 case Type::STK_MemberPointer:
4861 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004862 }
4863 break;
4864
John McCalldaa8e4e2010-11-15 09:13:47 +00004865 case Type::STK_IntegralComplex:
4866 switch (DestTy->getScalarTypeKind()) {
4867 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004868 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004869 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004870 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00004871 case Type::STK_Integral: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004872 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00004873 if (S.Context.hasSameType(ET, DestTy))
4874 return CK_IntegralComplexToReal;
4875 S.ImpCastExprToType(Src, ET, CK_IntegralComplexToReal);
4876 return CK_IntegralCast;
4877 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004878 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004879 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004880 case Type::STK_Floating:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004881 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004882 CK_IntegralComplexToReal);
4883 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004884 case Type::STK_Pointer:
4885 llvm_unreachable("valid complex int->pointer cast?");
4886 case Type::STK_MemberPointer:
4887 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004888 }
4889 break;
Anders Carlsson82debc72009-10-18 18:12:03 +00004890 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004891
John McCallf3ea8cf2010-11-14 08:17:51 +00004892 llvm_unreachable("Unhandled scalar cast");
4893 return CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00004894}
4895
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004896/// CheckCastTypes - Check type constraints for casting between types.
John McCallf89e55a2010-11-18 06:31:45 +00004897bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
4898 Expr *&castExpr, CastKind& Kind, ExprValueKind &VK,
4899 CXXCastPath &BasePath, bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00004900 if (getLangOptions().CPlusPlus)
Douglas Gregor40749ee2010-11-03 00:35:38 +00004901 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
4902 castExpr->getLocEnd()),
John McCallf89e55a2010-11-18 06:31:45 +00004903 castType, VK, castExpr, Kind, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004904 FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00004905
John McCallf89e55a2010-11-18 06:31:45 +00004906 // We only support r-value casts in C.
4907 VK = VK_RValue;
4908
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004909 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4910 // type needs to be scalar.
4911 if (castType->isVoidType()) {
John McCallf6a16482010-12-04 03:47:34 +00004912 // We don't necessarily do lvalue-to-rvalue conversions on this.
4913 IgnoredValueConversions(castExpr);
4914
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004915 // Cast to void allows any expr type.
John McCall2de56d12010-08-25 11:45:40 +00004916 Kind = CK_ToVoid;
Anders Carlssonebeaf202009-10-16 02:35:04 +00004917 return false;
4918 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004919
John McCallf6a16482010-12-04 03:47:34 +00004920 DefaultFunctionArrayLvalueConversion(castExpr);
4921
Eli Friedman8d438082010-07-17 20:43:49 +00004922 if (RequireCompleteType(TyR.getBegin(), castType,
4923 diag::err_typecheck_cast_to_incomplete))
4924 return true;
4925
Anders Carlssonebeaf202009-10-16 02:35:04 +00004926 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00004927 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004928 (castType->isStructureType() || castType->isUnionType())) {
4929 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004930 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004931 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
4932 << castType << castExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004933 Kind = CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00004934 return false;
4935 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004936
Anders Carlssonc3516322009-10-16 02:48:28 +00004937 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004938 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00004939 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004940 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004941 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004942 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004943 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara8c4bfe52010-10-07 21:20:44 +00004944 castExpr->getType()) &&
4945 !Field->isUnnamedBitfield()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004946 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4947 << castExpr->getSourceRange();
4948 break;
4949 }
4950 }
4951 if (Field == FieldEnd)
4952 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
4953 << castExpr->getType() << castExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004954 Kind = CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00004955 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004956 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004957
Anders Carlssonc3516322009-10-16 02:48:28 +00004958 // Reject any other conversions to non-scalar types.
4959 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
4960 << castType << castExpr->getSourceRange();
4961 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004962
John McCallf3ea8cf2010-11-14 08:17:51 +00004963 // The type we're casting to is known to be a scalar or vector.
4964
4965 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004966 if (!castExpr->getType()->isScalarType() &&
Anders Carlssonc3516322009-10-16 02:48:28 +00004967 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004968 return Diag(castExpr->getLocStart(),
4969 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00004970 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00004971 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004972
4973 if (castType->isExtVectorType())
Anders Carlsson16a89042009-10-16 05:23:41 +00004974 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004975
Anders Carlssonc3516322009-10-16 02:48:28 +00004976 if (castType->isVectorType())
4977 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
4978 if (castExpr->getType()->isVectorType())
4979 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
4980
John McCallf3ea8cf2010-11-14 08:17:51 +00004981 // The source and target types are both scalars, i.e.
4982 // - arithmetic types (fundamental, enum, and complex)
4983 // - all kinds of pointers
4984 // Note that member pointers were filtered out with C++, above.
4985
Anders Carlsson16a89042009-10-16 05:23:41 +00004986 if (isa<ObjCSelectorExpr>(castExpr))
4987 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004988
John McCallf3ea8cf2010-11-14 08:17:51 +00004989 // If either type is a pointer, the other type has to be either an
4990 // integer or a pointer.
Anders Carlssonc3516322009-10-16 02:48:28 +00004991 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00004992 QualType castExprType = castExpr->getType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00004993 if (!castExprType->isIntegralType(Context) &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004994 castExprType->isArithmeticType())
Eli Friedman41826bb2009-05-01 02:23:58 +00004995 return Diag(castExpr->getLocStart(),
4996 diag::err_cast_pointer_from_non_pointer_int)
4997 << castExprType << castExpr->getSourceRange();
4998 } else if (!castExpr->getType()->isArithmeticType()) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00004999 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
Eli Friedman41826bb2009-05-01 02:23:58 +00005000 return Diag(castExpr->getLocStart(),
5001 diag::err_cast_pointer_to_non_pointer_int)
5002 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005003 }
Anders Carlsson82debc72009-10-18 18:12:03 +00005004
John McCallf3ea8cf2010-11-14 08:17:51 +00005005 Kind = PrepareScalarCast(*this, castExpr, castType);
John McCallb7f4ffe2010-08-12 21:44:57 +00005006
John McCallf3ea8cf2010-11-14 08:17:51 +00005007 if (Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +00005008 CheckCastAlign(castExpr, castType, TyR);
5009
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005010 return false;
5011}
5012
Anders Carlssonc3516322009-10-16 02:48:28 +00005013bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00005014 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00005015 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005016
Anders Carlssona64db8f2007-11-27 05:51:55 +00005017 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00005018 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00005019 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00005020 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00005021 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005022 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00005023 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00005024 } else
5025 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005026 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00005027 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005028
John McCall2de56d12010-08-25 11:45:40 +00005029 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00005030 return false;
5031}
5032
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005033bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
John McCall2de56d12010-08-25 11:45:40 +00005034 CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00005035 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005036
Anders Carlsson16a89042009-10-16 05:23:41 +00005037 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005038
Nate Begeman9b10da62009-06-27 22:05:55 +00005039 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5040 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00005041 if (SrcTy->isVectorType()) {
5042 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
5043 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5044 << DestTy << SrcTy << R;
John McCall2de56d12010-08-25 11:45:40 +00005045 Kind = CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00005046 return false;
5047 }
5048
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005049 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00005050 // conversion will take place first from scalar to elt type, and then
5051 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005052 if (SrcTy->isPointerType())
5053 return Diag(R.getBegin(),
5054 diag::err_invalid_conversion_between_vector_and_scalar)
5055 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00005056
5057 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5058 ImpCastExprToType(CastExpr, DestElemTy,
John McCallf3ea8cf2010-11-14 08:17:51 +00005059 PrepareScalarCast(*this, CastExpr, DestElemTy));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005060
John McCall2de56d12010-08-25 11:45:40 +00005061 Kind = CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00005062 return false;
5063}
5064
John McCall60d7b3a2010-08-24 06:29:42 +00005065ExprResult
John McCallb3d87482010-08-24 05:47:05 +00005066Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005067 SourceLocation RParenLoc, Expr *castExpr) {
5068 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005069 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00005070
John McCall9d125032010-01-15 18:39:57 +00005071 TypeSourceInfo *castTInfo;
5072 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5073 if (!castTInfo)
John McCall42f56b52010-01-18 19:35:47 +00005074 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump1eb44332009-09-09 15:08:12 +00005075
Nate Begeman2ef13e52009-08-10 23:49:36 +00005076 // If the Expr being casted is a ParenListExpr, handle it specially.
5077 if (isa<ParenListExpr>(castExpr))
John McCall9ae2f072010-08-23 23:25:46 +00005078 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCall42f56b52010-01-18 19:35:47 +00005079 castTInfo);
John McCallb042fdf2010-01-15 18:56:44 +00005080
John McCall9ae2f072010-08-23 23:25:46 +00005081 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallb042fdf2010-01-15 18:56:44 +00005082}
5083
John McCall60d7b3a2010-08-24 06:29:42 +00005084ExprResult
John McCallb042fdf2010-01-15 18:56:44 +00005085Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005086 SourceLocation RParenLoc, Expr *castExpr) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005087 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +00005088 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +00005089 CXXCastPath BasePath;
John McCallb042fdf2010-01-15 18:56:44 +00005090 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
John McCallf89e55a2010-11-18 06:31:45 +00005091 Kind, VK, BasePath))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005092 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00005093
John McCallf871d0c2010-08-07 06:22:56 +00005094 return Owned(CStyleCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +00005095 Ty->getType().getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +00005096 VK, Kind, castExpr, &BasePath, Ty,
John McCallf871d0c2010-08-07 06:22:56 +00005097 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00005098}
5099
Nate Begeman2ef13e52009-08-10 23:49:36 +00005100/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5101/// of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00005102ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005103Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005104 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5105 if (!E)
5106 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00005107
John McCall60d7b3a2010-08-24 06:29:42 +00005108 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00005109
Nate Begeman2ef13e52009-08-10 23:49:36 +00005110 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00005111 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5112 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00005113
John McCall9ae2f072010-08-23 23:25:46 +00005114 if (Result.isInvalid()) return ExprError();
5115
5116 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00005117}
5118
John McCall60d7b3a2010-08-24 06:29:42 +00005119ExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00005120Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00005121 SourceLocation RParenLoc, Expr *Op,
John McCall42f56b52010-01-18 19:35:47 +00005122 TypeSourceInfo *TInfo) {
John McCall9ae2f072010-08-23 23:25:46 +00005123 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCall42f56b52010-01-18 19:35:47 +00005124 QualType Ty = TInfo->getType();
John Thompson8bb59a82010-06-30 22:55:51 +00005125 bool isAltiVecLiteral = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005126
John Thompson8bb59a82010-06-30 22:55:51 +00005127 // Check for an altivec literal,
5128 // i.e. all the elements are integer constants.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005129 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5130 if (PE->getNumExprs() == 0) {
5131 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5132 return ExprError();
5133 }
John Thompson8bb59a82010-06-30 22:55:51 +00005134 if (PE->getNumExprs() == 1) {
5135 if (!PE->getExpr(0)->getType()->isVectorType())
5136 isAltiVecLiteral = true;
5137 }
5138 else
5139 isAltiVecLiteral = true;
5140 }
Nate Begeman2ef13e52009-08-10 23:49:36 +00005141
John Thompson8bb59a82010-06-30 22:55:51 +00005142 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
5143 // then handle it as such.
5144 if (isAltiVecLiteral) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005145 llvm::SmallVector<Expr *, 8> initExprs;
5146 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5147 initExprs.push_back(PE->getExpr(i));
5148
5149 // FIXME: This means that pretty-printing the final AST will produce curly
5150 // braces instead of the original commas.
Ted Kremenek709210f2010-04-13 23:39:13 +00005151 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5152 &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00005153 initExprs.size(), RParenLoc);
5154 E->setType(Ty);
John McCall9ae2f072010-08-23 23:25:46 +00005155 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman2ef13e52009-08-10 23:49:36 +00005156 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00005157 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00005158 // sequence of BinOp comma operators.
John McCall60d7b3a2010-08-24 06:29:42 +00005159 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCall9ae2f072010-08-23 23:25:46 +00005160 if (Result.isInvalid()) return ExprError();
5161 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman2ef13e52009-08-10 23:49:36 +00005162 }
5163}
5164
John McCall60d7b3a2010-08-24 06:29:42 +00005165ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00005166 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00005167 MultiExprArg Val,
John McCallb3d87482010-08-24 05:47:05 +00005168 ParsedType TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005169 unsigned nexprs = Val.size();
5170 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00005171 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5172 Expr *expr;
5173 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5174 expr = new (Context) ParenExpr(L, R, exprs[0]);
5175 else
5176 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00005177 return Owned(expr);
5178}
5179
Sebastian Redl28507842009-02-26 14:39:58 +00005180/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5181/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00005182/// C99 6.5.15
5183QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCallf89e55a2010-11-18 06:31:45 +00005184 Expr *&SAVE, ExprValueKind &VK,
John McCall09431682010-11-18 19:01:18 +00005185 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00005186 SourceLocation QuestionLoc) {
Douglas Gregor7ad5d422010-11-09 21:07:58 +00005187 // If both LHS and RHS are overloaded functions, try to resolve them.
5188 if (Context.hasSameType(LHS->getType(), RHS->getType()) &&
5189 LHS->getType()->isSpecificBuiltinType(BuiltinType::Overload)) {
5190 ExprResult LHSResult = CheckPlaceholderExpr(LHS, QuestionLoc);
5191 if (LHSResult.isInvalid())
5192 return QualType();
5193
5194 ExprResult RHSResult = CheckPlaceholderExpr(RHS, QuestionLoc);
5195 if (RHSResult.isInvalid())
5196 return QualType();
5197
5198 LHS = LHSResult.take();
5199 RHS = RHSResult.take();
5200 }
5201
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005202 // C++ is sufficiently different to merit its own checker.
5203 if (getLangOptions().CPlusPlus)
John McCall09431682010-11-18 19:01:18 +00005204 return CXXCheckConditionalOperands(Cond, LHS, RHS, SAVE,
5205 VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00005206
5207 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005208 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005209
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005210 UsualUnaryConversions(Cond);
Fariborz Jahanian1fb019b2010-09-18 19:38:38 +00005211 if (SAVE) {
5212 SAVE = LHS = Cond;
5213 }
5214 else
5215 UsualUnaryConversions(LHS);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005216 UsualUnaryConversions(RHS);
5217 QualType CondTy = Cond->getType();
5218 QualType LHSTy = LHS->getType();
5219 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005220
Reid Spencer5f016e22007-07-11 17:01:13 +00005221 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005222 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begeman6155d732010-09-20 22:41:17 +00005223 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5224 // Throw an error if its not either.
5225 if (getLangOptions().OpenCL) {
5226 if (!CondTy->isVectorType()) {
5227 Diag(Cond->getLocStart(),
5228 diag::err_typecheck_cond_expect_scalar_or_vector)
5229 << CondTy;
5230 return QualType();
5231 }
5232 }
5233 else {
5234 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5235 << CondTy;
5236 return QualType();
5237 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005238 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005239
Chris Lattner70d67a92008-01-06 22:42:25 +00005240 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005241 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5242 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00005243
Nate Begeman6155d732010-09-20 22:41:17 +00005244 // OpenCL: If the condition is a vector, and both operands are scalar,
5245 // attempt to implicity convert them to the vector type to act like the
5246 // built in select.
5247 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5248 // Both operands should be of scalar type.
5249 if (!LHSTy->isScalarType()) {
5250 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5251 << CondTy;
5252 return QualType();
5253 }
5254 if (!RHSTy->isScalarType()) {
5255 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5256 << CondTy;
5257 return QualType();
5258 }
5259 // Implicity convert these scalars to the type of the condition.
5260 ImpCastExprToType(LHS, CondTy, CK_IntegralCast);
5261 ImpCastExprToType(RHS, CondTy, CK_IntegralCast);
5262 }
5263
Chris Lattner70d67a92008-01-06 22:42:25 +00005264 // If both operands have arithmetic type, do the usual arithmetic conversions
5265 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005266 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5267 UsualArithmeticConversions(LHS, RHS);
5268 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00005269 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005270
Chris Lattner70d67a92008-01-06 22:42:25 +00005271 // If both operands are the same structure or union type, the result is that
5272 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005273 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5274 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00005275 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005276 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00005277 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005278 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005279 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00005280 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005281
Chris Lattner70d67a92008-01-06 22:42:25 +00005282 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00005283 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005284 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5285 if (!LHSTy->isVoidType())
5286 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5287 << RHS->getSourceRange();
5288 if (!RHSTy->isVoidType())
5289 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5290 << LHS->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005291 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid);
5292 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00005293 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00005294 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00005295 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5296 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005297 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005298 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005299 // promote the null to a pointer.
John McCalldaa8e4e2010-11-15 09:13:47 +00005300 ImpCastExprToType(RHS, LHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005301 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00005302 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005303 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005304 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005305 ImpCastExprToType(LHS, RHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005306 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00005307 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005308
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005309 // All objective-c pointer type analysis is done here.
5310 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5311 QuestionLoc);
5312 if (!compositeType.isNull())
5313 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005314
5315
Steve Naroff7154a772009-07-01 14:36:47 +00005316 // Handle block pointer types.
5317 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5318 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5319 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5320 QualType destType = Context.getPointerType(Context.VoidTy);
John McCall2de56d12010-08-25 11:45:40 +00005321 ImpCastExprToType(LHS, destType, CK_BitCast);
5322 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005323 return destType;
5324 }
5325 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005326 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00005327 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00005328 }
Steve Naroff7154a772009-07-01 14:36:47 +00005329 // We have 2 block pointer types.
5330 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5331 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005332 return LHSTy;
5333 }
Steve Naroff7154a772009-07-01 14:36:47 +00005334 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00005335 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5336 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005337
Steve Naroff7154a772009-07-01 14:36:47 +00005338 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5339 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00005340 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005341 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00005342 // In this situation, we assume void* type. No especially good
5343 // reason, but this is what gcc does, and we do have to pick
5344 // to get a consistent AST.
5345 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCall2de56d12010-08-25 11:45:40 +00005346 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5347 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00005348 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005349 }
Steve Naroff7154a772009-07-01 14:36:47 +00005350 // The block pointer types are compatible.
John McCall2de56d12010-08-25 11:45:40 +00005351 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5352 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00005353 return LHSTy;
5354 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005355
Steve Naroff7154a772009-07-01 14:36:47 +00005356 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5357 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5358 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00005359 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5360 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00005361
5362 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5363 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5364 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00005365 QualType destPointee
5366 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00005367 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005368 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005369 ImpCastExprToType(LHS, destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005370 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005371 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005372 return destType;
5373 }
5374 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00005375 QualType destPointee
5376 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00005377 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005378 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005379 ImpCastExprToType(RHS, destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005380 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005381 ImpCastExprToType(LHS, destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005382 return destType;
5383 }
5384
5385 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5386 // Two identical pointer types are always compatible.
5387 return LHSTy;
5388 }
5389 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5390 rhptee.getUnqualifiedType())) {
5391 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5392 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5393 // In this situation, we assume void* type. No especially good
5394 // reason, but this is what gcc does, and we do have to pick
5395 // to get a consistent AST.
5396 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCall2de56d12010-08-25 11:45:40 +00005397 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5398 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005399 return incompatTy;
5400 }
5401 // The pointer types are compatible.
5402 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5403 // differently qualified versions of compatible types, the result type is
5404 // a pointer to an appropriately qualified version of the *composite*
5405 // type.
5406 // FIXME: Need to calculate the composite type.
5407 // FIXME: Need to add qualifiers
John McCall2de56d12010-08-25 11:45:40 +00005408 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5409 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005410 return LHSTy;
5411 }
Mike Stump1eb44332009-09-09 15:08:12 +00005412
John McCall404cd162010-11-13 01:35:44 +00005413 // GCC compatibility: soften pointer/integer mismatch. Note that
5414 // null pointers have been filtered out by this point.
Steve Naroff7154a772009-07-01 14:36:47 +00005415 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5416 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5417 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005418 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00005419 return RHSTy;
5420 }
5421 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5422 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5423 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005424 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00005425 return LHSTy;
5426 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00005427
Chris Lattner70d67a92008-01-06 22:42:25 +00005428 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005429 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5430 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005431 return QualType();
5432}
5433
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005434/// FindCompositeObjCPointerType - Helper method to find composite type of
5435/// two objective-c pointer types of the two input expressions.
5436QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
5437 SourceLocation QuestionLoc) {
5438 QualType LHSTy = LHS->getType();
5439 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005440
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005441 // Handle things like Class and struct objc_class*. Here we case the result
5442 // to the pseudo-builtin, because that will be implicitly cast back to the
5443 // redefinition type if an attempt is made to access its fields.
5444 if (LHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005445 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005446 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005447 return LHSTy;
5448 }
5449 if (RHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005450 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005451 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005452 return RHSTy;
5453 }
5454 // And the same for struct objc_object* / id
5455 if (LHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005456 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005457 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005458 return LHSTy;
5459 }
5460 if (RHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005461 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005462 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005463 return RHSTy;
5464 }
5465 // And the same for struct objc_selector* / SEL
5466 if (Context.isObjCSelType(LHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00005467 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005468 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005469 return LHSTy;
5470 }
5471 if (Context.isObjCSelType(RHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00005472 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005473 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005474 return RHSTy;
5475 }
5476 // Check constraints for Objective-C object pointers types.
5477 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005478
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005479 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5480 // Two identical object pointer types are always compatible.
5481 return LHSTy;
5482 }
5483 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5484 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5485 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005486
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005487 // If both operands are interfaces and either operand can be
5488 // assigned to the other, use that type as the composite
5489 // type. This allows
5490 // xxx ? (A*) a : (B*) b
5491 // where B is a subclass of A.
5492 //
5493 // Additionally, as for assignment, if either type is 'id'
5494 // allow silent coercion. Finally, if the types are
5495 // incompatible then make sure to use 'id' as the composite
5496 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005497
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005498 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5499 // It could return the composite type.
5500 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5501 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5502 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5503 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5504 } else if ((LHSTy->isObjCQualifiedIdType() ||
5505 RHSTy->isObjCQualifiedIdType()) &&
5506 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5507 // Need to handle "id<xx>" explicitly.
5508 // GCC allows qualified id and any Objective-C type to devolve to
5509 // id. Currently localizing to here until clear this should be
5510 // part of ObjCQualifiedIdTypesAreCompatible.
5511 compositeType = Context.getObjCIdType();
5512 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5513 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005514 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005515 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5516 ;
5517 else {
5518 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5519 << LHSTy << RHSTy
5520 << LHS->getSourceRange() << RHS->getSourceRange();
5521 QualType incompatTy = Context.getObjCIdType();
John McCall2de56d12010-08-25 11:45:40 +00005522 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5523 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005524 return incompatTy;
5525 }
5526 // The object pointer types are compatible.
John McCall2de56d12010-08-25 11:45:40 +00005527 ImpCastExprToType(LHS, compositeType, CK_BitCast);
5528 ImpCastExprToType(RHS, compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005529 return compositeType;
5530 }
5531 // Check Objective-C object pointer types and 'void *'
5532 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5533 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5534 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5535 QualType destPointee
5536 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5537 QualType destType = Context.getPointerType(destPointee);
5538 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005539 ImpCastExprToType(LHS, destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005540 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005541 ImpCastExprToType(RHS, destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005542 return destType;
5543 }
5544 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5545 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5546 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5547 QualType destPointee
5548 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5549 QualType destType = Context.getPointerType(destPointee);
5550 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005551 ImpCastExprToType(RHS, destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005552 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005553 ImpCastExprToType(LHS, destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005554 return destType;
5555 }
5556 return QualType();
5557}
5558
Steve Narofff69936d2007-09-16 03:34:24 +00005559/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005560/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005561ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005562 SourceLocation ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +00005563 Expr *CondExpr, Expr *LHSExpr,
5564 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005565 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5566 // was the condition.
5567 bool isLHSNull = LHSExpr == 0;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005568 Expr *SAVEExpr = 0;
5569 if (isLHSNull) {
5570 LHSExpr = SAVEExpr = CondExpr;
5571 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005572
John McCallf89e55a2010-11-18 06:31:45 +00005573 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005574 ExprObjectKind OK = OK_Ordinary;
Fariborz Jahanian1fb019b2010-09-18 19:38:38 +00005575 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr,
John McCall09431682010-11-18 19:01:18 +00005576 SAVEExpr, VK, OK, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00005577 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005578 return ExprError();
5579
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00005580 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005581 LHSExpr, ColonLoc,
5582 RHSExpr, SAVEExpr,
John McCall09431682010-11-18 19:01:18 +00005583 result, VK, OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005584}
5585
John McCalle4be87e2011-01-31 23:13:11 +00005586// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005587// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005588// routine is it effectively iqnores the qualifiers on the top level pointee.
5589// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5590// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005591static Sema::AssignConvertType
5592checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5593 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5594 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005595
Reid Spencer5f016e22007-07-11 17:01:13 +00005596 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005597 const Type *lhptee, *rhptee;
5598 Qualifiers lhq, rhq;
5599 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5600 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005601
John McCalle4be87e2011-01-31 23:13:11 +00005602 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005603
5604 // C99 6.5.16.1p1: This following citation is common to constraints
5605 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5606 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005607 Qualifiers lq;
5608
5609 if (!lhq.compatiblyIncludes(rhq)) {
5610 // Treat address-space mismatches as fatal. TODO: address subspaces
5611 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5612 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5613
5614 // For GCC compatibility, other qualifier mismatches are treated
5615 // as still compatible in C.
5616 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5617 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005618
Mike Stumpeed9cac2009-02-19 03:04:26 +00005619 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5620 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005621 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005622 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005623 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005624 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005625
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005626 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005627 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005628 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005629 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005630
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005631 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005632 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005633 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005634
5635 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005636 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005637 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005638 }
John McCall86c05f32011-02-01 00:10:29 +00005639
Mike Stumpeed9cac2009-02-19 03:04:26 +00005640 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005641 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005642 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5643 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005644 // Check if the pointee types are compatible ignoring the sign.
5645 // We explicitly check for char so that we catch "char" vs
5646 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005647 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005648 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005649 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005650 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005651
Chris Lattner6a2b9262009-10-17 20:33:28 +00005652 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005653 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005654 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005655 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005656
John McCall86c05f32011-02-01 00:10:29 +00005657 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005658 // Types are compatible ignoring the sign. Qualifier incompatibility
5659 // takes priority over sign incompatibility because the sign
5660 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005661 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005662 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005663
John McCalle4be87e2011-01-31 23:13:11 +00005664 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005665 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005666
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005667 // If we are a multi-level pointer, it's possible that our issue is simply
5668 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5669 // the eventual target type is the same and the pointers have the same
5670 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005671 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005672 do {
John McCall86c05f32011-02-01 00:10:29 +00005673 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5674 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005675 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005676
John McCall86c05f32011-02-01 00:10:29 +00005677 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005678 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005679 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005680
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005681 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005682 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005683 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005684 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005685}
5686
John McCalle4be87e2011-01-31 23:13:11 +00005687/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005688/// block pointer types are compatible or whether a block and normal pointer
5689/// are compatible. It is more restrict than comparing two function pointer
5690// types.
John McCalle4be87e2011-01-31 23:13:11 +00005691static Sema::AssignConvertType
5692checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5693 QualType rhsType) {
5694 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5695 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5696
Steve Naroff1c7d0672008-09-04 15:10:53 +00005697 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005698
Steve Naroff1c7d0672008-09-04 15:10:53 +00005699 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCalle4be87e2011-01-31 23:13:11 +00005700 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5701 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005702
John McCalle4be87e2011-01-31 23:13:11 +00005703 // In C++, the types have to match exactly.
5704 if (S.getLangOptions().CPlusPlus)
5705 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005706
John McCalle4be87e2011-01-31 23:13:11 +00005707 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005708
Steve Naroff1c7d0672008-09-04 15:10:53 +00005709 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005710 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5711 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005712
John McCalle4be87e2011-01-31 23:13:11 +00005713 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5714 return Sema::IncompatibleBlockPointer;
5715
Steve Naroff1c7d0672008-09-04 15:10:53 +00005716 return ConvTy;
5717}
5718
John McCalle4be87e2011-01-31 23:13:11 +00005719/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005720/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005721static Sema::AssignConvertType
5722checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5723 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5724 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5725
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005726 if (lhsType->isObjCBuiltinType()) {
5727 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00005728 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5729 !rhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005730 return Sema::IncompatiblePointer;
5731 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005732 }
5733 if (rhsType->isObjCBuiltinType()) {
5734 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00005735 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5736 !lhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005737 return Sema::IncompatiblePointer;
5738 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005739 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005740 QualType lhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005741 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005742 QualType rhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005743 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005744
John McCalle4be87e2011-01-31 23:13:11 +00005745 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5746 return Sema::CompatiblePointerDiscardsQualifiers;
5747
5748 if (S.Context.typesAreCompatible(lhsType, rhsType))
5749 return Sema::Compatible;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005750 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005751 return Sema::IncompatibleObjCQualifiedId;
5752 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005753}
5754
John McCall1c23e912010-11-16 02:32:08 +00005755Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005756Sema::CheckAssignmentConstraints(SourceLocation Loc,
5757 QualType lhsType, QualType rhsType) {
John McCall1c23e912010-11-16 02:32:08 +00005758 // Fake up an opaque expression. We don't actually care about what
5759 // cast operations are required, so if CheckAssignmentConstraints
5760 // adds casts to this they'll be wasted, but fortunately that doesn't
5761 // usually happen on valid code.
Douglas Gregorb608b982011-01-28 02:26:04 +00005762 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John McCall1c23e912010-11-16 02:32:08 +00005763 Expr *rhsPtr = &rhs;
5764 CastKind K = CK_Invalid;
5765
5766 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5767}
5768
Mike Stumpeed9cac2009-02-19 03:04:26 +00005769/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5770/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005771/// pointers. Here are some objectionable examples that GCC considers warnings:
5772///
5773/// int a, *pint;
5774/// short *pshort;
5775/// struct foo *pfoo;
5776///
5777/// pint = pshort; // warning: assignment from incompatible pointer type
5778/// a = pint; // warning: assignment makes integer from pointer without a cast
5779/// pint = a; // warning: assignment makes pointer from integer without a cast
5780/// pint = pfoo; // warning: assignment from incompatible pointer type
5781///
5782/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005783/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005784///
John McCalldaa8e4e2010-11-15 09:13:47 +00005785/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005786Sema::AssignConvertType
John McCall1c23e912010-11-16 02:32:08 +00005787Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs,
John McCalldaa8e4e2010-11-15 09:13:47 +00005788 CastKind &Kind) {
John McCall1c23e912010-11-16 02:32:08 +00005789 QualType rhsType = rhs->getType();
5790
Chris Lattnerfc144e22008-01-04 23:18:45 +00005791 // Get canonical types. We're not formatting these types, just comparing
5792 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00005793 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5794 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005795
John McCallb6cfa242011-01-31 22:28:28 +00005796 // Common case: no conversion required.
John McCalldaa8e4e2010-11-15 09:13:47 +00005797 if (lhsType == rhsType) {
5798 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005799 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005800 }
5801
Douglas Gregor9d293df2008-10-28 00:22:11 +00005802 // If the left-hand side is a reference type, then we are in a
5803 // (rare!) case where we've allowed the use of references in C,
5804 // e.g., as a parameter type in a built-in function. In this case,
5805 // just make sure that the type referenced is compatible with the
5806 // right-hand side type. The caller is responsible for adjusting
5807 // lhsType so that the resulting expression does not have reference
5808 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005809 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005810 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5811 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005812 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005813 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005814 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005815 }
John McCallb6cfa242011-01-31 22:28:28 +00005816
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005817 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5818 // to the same ExtVector type.
5819 if (lhsType->isExtVectorType()) {
5820 if (rhsType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005821 return Incompatible;
5822 if (rhsType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005823 // CK_VectorSplat does T -> vector T, so first cast to the
5824 // element type.
5825 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5826 if (elType != rhsType) {
5827 Kind = PrepareScalarCast(*this, rhs, elType);
5828 ImpCastExprToType(rhs, elType, Kind);
5829 }
5830 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005831 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005832 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005833 }
Mike Stump1eb44332009-09-09 15:08:12 +00005834
John McCallb6cfa242011-01-31 22:28:28 +00005835 // Conversions to or from vector type.
Nate Begemanbe2341d2008-07-14 18:02:46 +00005836 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor255210e2010-08-06 10:14:59 +00005837 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005838 // Allow assignments of an AltiVec vector type to an equivalent GCC
5839 // vector type and vice versa
5840 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5841 Kind = CK_BitCast;
5842 return Compatible;
5843 }
5844
Douglas Gregor255210e2010-08-06 10:14:59 +00005845 // If we are allowing lax vector conversions, and LHS and RHS are both
5846 // vectors, the total size only needs to be the same. This is a bitcast;
5847 // no bits are changed but the result type is different.
5848 if (getLangOptions().LaxVectorConversions &&
John McCalldaa8e4e2010-11-15 09:13:47 +00005849 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005850 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005851 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005852 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005853 }
5854 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005855 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005856
John McCallb6cfa242011-01-31 22:28:28 +00005857 // Arithmetic conversions.
Douglas Gregor88623ad2010-05-23 21:53:47 +00005858 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00005859 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall1c23e912010-11-16 02:32:08 +00005860 Kind = PrepareScalarCast(*this, rhs, lhsType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005861 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005862 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005863
John McCallb6cfa242011-01-31 22:28:28 +00005864 // Conversions to normal pointers.
5865 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5866 // U* -> T*
John McCalldaa8e4e2010-11-15 09:13:47 +00005867 if (isa<PointerType>(rhsType)) {
5868 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00005869 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005870 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005871
John McCallb6cfa242011-01-31 22:28:28 +00005872 // int -> T*
5873 if (rhsType->isIntegerType()) {
5874 Kind = CK_IntegralToPointer; // FIXME: null?
5875 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005876 }
John McCallb6cfa242011-01-31 22:28:28 +00005877
5878 // C pointers are not compatible with ObjC object pointers,
5879 // with two exceptions:
5880 if (isa<ObjCObjectPointerType>(rhsType)) {
5881 // - conversions to void*
5882 if (lhsPointer->getPointeeType()->isVoidType()) {
5883 Kind = CK_AnyPointerToObjCPointerCast;
5884 return Compatible;
5885 }
5886
5887 // - conversions from 'Class' to the redefinition type
5888 if (rhsType->isObjCClassType() &&
5889 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005890 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005891 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005892 }
Steve Naroffb4406862008-09-29 18:10:17 +00005893
John McCallb6cfa242011-01-31 22:28:28 +00005894 Kind = CK_BitCast;
5895 return IncompatiblePointer;
5896 }
5897
5898 // U^ -> void*
5899 if (rhsType->getAs<BlockPointerType>()) {
5900 if (lhsPointer->getPointeeType()->isVoidType()) {
5901 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005902 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005903 }
Steve Naroffb4406862008-09-29 18:10:17 +00005904 }
John McCallb6cfa242011-01-31 22:28:28 +00005905
Steve Naroff1c7d0672008-09-04 15:10:53 +00005906 return Incompatible;
5907 }
5908
John McCallb6cfa242011-01-31 22:28:28 +00005909 // Conversions to block pointers.
Steve Naroff1c7d0672008-09-04 15:10:53 +00005910 if (isa<BlockPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005911 // U^ -> T^
5912 if (rhsType->isBlockPointerType()) {
5913 Kind = CK_AnyPointerToBlockPointerCast;
John McCalle4be87e2011-01-31 23:13:11 +00005914 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00005915 }
5916
5917 // int or null -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00005918 if (rhsType->isIntegerType()) {
5919 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005920 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005921 }
5922
John McCallb6cfa242011-01-31 22:28:28 +00005923 // id -> T^
5924 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
5925 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005926 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005927 }
Steve Naroffb4406862008-09-29 18:10:17 +00005928
John McCallb6cfa242011-01-31 22:28:28 +00005929 // void* -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00005930 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005931 if (RHSPT->getPointeeType()->isVoidType()) {
5932 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005933 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005934 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005935
Chris Lattnerfc144e22008-01-04 23:18:45 +00005936 return Incompatible;
5937 }
5938
John McCallb6cfa242011-01-31 22:28:28 +00005939 // Conversions to Objective-C pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00005940 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005941 // A* -> B*
5942 if (rhsType->isObjCObjectPointerType()) {
5943 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00005944 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00005945 }
5946
5947 // int or null -> A*
John McCalldaa8e4e2010-11-15 09:13:47 +00005948 if (rhsType->isIntegerType()) {
5949 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005950 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005951 }
5952
John McCallb6cfa242011-01-31 22:28:28 +00005953 // In general, C pointers are not compatible with ObjC object pointers,
5954 // with two exceptions:
Steve Naroff14108da2009-07-10 23:34:53 +00005955 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005956 // - conversions from 'void*'
5957 if (rhsType->isVoidPointerType()) {
5958 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005959 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005960 }
5961
5962 // - conversions to 'Class' from its redefinition type
5963 if (lhsType->isObjCClassType() &&
5964 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
5965 Kind = CK_BitCast;
5966 return Compatible;
5967 }
5968
5969 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005970 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005971 }
John McCallb6cfa242011-01-31 22:28:28 +00005972
5973 // T^ -> A*
5974 if (rhsType->isBlockPointerType()) {
5975 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005976 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005977 }
5978
Steve Naroff14108da2009-07-10 23:34:53 +00005979 return Incompatible;
5980 }
John McCallb6cfa242011-01-31 22:28:28 +00005981
5982 // Conversions from pointers that are not covered by the above.
Chris Lattner78eca282008-04-07 06:49:41 +00005983 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005984 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00005985 if (lhsType == Context.BoolTy) {
5986 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005987 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005988 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005989
John McCallb6cfa242011-01-31 22:28:28 +00005990 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00005991 if (lhsType->isIntegerType()) {
5992 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005993 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005994 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005995
Chris Lattnerfc144e22008-01-04 23:18:45 +00005996 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005997 }
John McCallb6cfa242011-01-31 22:28:28 +00005998
5999 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff14108da2009-07-10 23:34:53 +00006000 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006001 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00006002 if (lhsType == Context.BoolTy) {
6003 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00006004 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006005 }
Steve Naroff14108da2009-07-10 23:34:53 +00006006
John McCallb6cfa242011-01-31 22:28:28 +00006007 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00006008 if (lhsType->isIntegerType()) {
6009 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00006010 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00006011 }
6012
Steve Naroff14108da2009-07-10 23:34:53 +00006013 return Incompatible;
6014 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006015
John McCallb6cfa242011-01-31 22:28:28 +00006016 // struct A -> struct B
Chris Lattnerfc144e22008-01-04 23:18:45 +00006017 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006018 if (Context.typesAreCompatible(lhsType, rhsType)) {
6019 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00006020 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006021 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006022 }
John McCallb6cfa242011-01-31 22:28:28 +00006023
Reid Spencer5f016e22007-07-11 17:01:13 +00006024 return Incompatible;
6025}
6026
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006027/// \brief Constructs a transparent union from an expression that is
6028/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00006029static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006030 QualType UnionType, FieldDecl *Field) {
6031 // Build an initializer list that designates the appropriate member
6032 // of the transparent union.
Ted Kremenek709210f2010-04-13 23:39:13 +00006033 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00006034 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006035 SourceLocation());
6036 Initializer->setType(UnionType);
6037 Initializer->setInitializedFieldInUnion(Field);
6038
6039 // Build a compound literal constructing a value of the transparent
6040 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00006041 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall1d7d8d62010-01-19 22:33:45 +00006042 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCallf89e55a2010-11-18 06:31:45 +00006043 VK_RValue, Initializer, false);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006044}
6045
6046Sema::AssignConvertType
6047Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
6048 QualType FromType = rExpr->getType();
6049
Mike Stump1eb44332009-09-09 15:08:12 +00006050 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006051 // transparent_union GCC extension.
6052 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006053 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006054 return Incompatible;
6055
6056 // The field to initialize within the transparent union.
6057 RecordDecl *UD = UT->getDecl();
6058 FieldDecl *InitField = 0;
6059 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006060 for (RecordDecl::field_iterator it = UD->field_begin(),
6061 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006062 it != itend; ++it) {
6063 if (it->getType()->isPointerType()) {
6064 // If the transparent union contains a pointer type, we allow:
6065 // 1) void pointer
6066 // 2) null pointer constant
6067 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00006068 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John McCall2de56d12010-08-25 11:45:40 +00006069 ImpCastExprToType(rExpr, it->getType(), CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006070 InitField = *it;
6071 break;
6072 }
Mike Stump1eb44332009-09-09 15:08:12 +00006073
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006074 if (rExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006075 Expr::NPC_ValueDependentIsNull)) {
John McCall404cd162010-11-13 01:35:44 +00006076 ImpCastExprToType(rExpr, it->getType(), CK_NullToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006077 InitField = *it;
6078 break;
6079 }
6080 }
6081
John McCall1c23e912010-11-16 02:32:08 +00006082 Expr *rhs = rExpr;
John McCalldaa8e4e2010-11-15 09:13:47 +00006083 CastKind Kind = CK_Invalid;
John McCall1c23e912010-11-16 02:32:08 +00006084 if (CheckAssignmentConstraints(it->getType(), rhs, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006085 == Compatible) {
John McCall1c23e912010-11-16 02:32:08 +00006086 ImpCastExprToType(rhs, it->getType(), Kind);
6087 rExpr = rhs;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006088 InitField = *it;
6089 break;
6090 }
6091 }
6092
6093 if (!InitField)
6094 return Incompatible;
6095
6096 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
6097 return Compatible;
6098}
6099
Chris Lattner5cf216b2008-01-04 18:04:52 +00006100Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00006101Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00006102 if (getLangOptions().CPlusPlus) {
6103 if (!lhsType->isRecordType()) {
6104 // C++ 5.17p3: If the left operand is not of class type, the
6105 // expression is implicitly converted (C++ 4) to the
6106 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00006107 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor68647482009-12-16 03:45:30 +00006108 AA_Assigning))
Douglas Gregor98cd5992008-10-21 23:43:52 +00006109 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00006110 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00006111 }
6112
6113 // FIXME: Currently, we fall through and treat C++ classes like C
6114 // structures.
John McCallf6a16482010-12-04 03:47:34 +00006115 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00006116
Steve Naroff529a4ad2007-11-27 17:58:44 +00006117 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6118 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00006119 if ((lhsType->isPointerType() ||
6120 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00006121 lhsType->isBlockPointerType())
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006122 && rExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006123 Expr::NPC_ValueDependentIsNull)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006124 ImpCastExprToType(rExpr, lhsType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00006125 return Compatible;
6126 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006127
Chris Lattner943140e2007-10-16 02:55:40 +00006128 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00006129 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00006130 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00006131 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00006132 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00006133 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00006134 if (!lhsType->isReferenceType())
Douglas Gregora873dfc2010-02-03 00:27:59 +00006135 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00006136
John McCalldaa8e4e2010-11-15 09:13:47 +00006137 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006138 Sema::AssignConvertType result =
John McCall1c23e912010-11-16 02:32:08 +00006139 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006140
Steve Narofff1120de2007-08-24 22:33:52 +00006141 // C99 6.5.16.1p2: The value of the right operand is converted to the
6142 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00006143 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6144 // so that we can use references in built-in functions even in C.
6145 // The getNonReferenceType() call makes sure that the resulting expression
6146 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006147 if (result != Incompatible && rExpr->getType() != lhsType)
John McCalldaa8e4e2010-11-15 09:13:47 +00006148 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00006149 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00006150}
6151
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006152QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006153 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00006154 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006155 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00006156 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006157}
6158
Chris Lattner7ef655a2010-01-12 21:23:57 +00006159QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00006160 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006161 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00006162 QualType lhsType =
6163 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
6164 QualType rhsType =
6165 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006166
Nate Begemanbe2341d2008-07-14 18:02:46 +00006167 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006168 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00006169 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00006170
Nate Begemanbe2341d2008-07-14 18:02:46 +00006171 // Handle the case of a vector & extvector type of the same size and element
6172 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006173 if (getLangOptions().LaxVectorConversions) {
John McCall183700f2009-09-21 23:43:11 +00006174 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth629f9e42010-08-30 07:36:24 +00006175 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00006176 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006177 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregor26bcf672010-05-19 03:21:00 +00006178 if (lhsType->isExtVectorType()) {
John McCall2de56d12010-08-25 11:45:40 +00006179 ImpCastExprToType(rex, lhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006180 return lhsType;
6181 }
6182
John McCall2de56d12010-08-25 11:45:40 +00006183 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006184 return rhsType;
Eric Christophere84f9eb2010-08-26 00:42:16 +00006185 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6186 // If we are allowing lax vector conversions, and LHS and RHS are both
6187 // vectors, the total size only needs to be the same. This is a
6188 // bitcast; no bits are changed but the result type is different.
6189 ImpCastExprToType(rex, lhsType, CK_BitCast);
6190 return lhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006191 }
Eric Christophere84f9eb2010-08-26 00:42:16 +00006192 }
Chandler Carruth629f9e42010-08-30 07:36:24 +00006193 }
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006194 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006195
Douglas Gregor255210e2010-08-06 10:14:59 +00006196 // Handle the case of equivalent AltiVec and GCC vector types
6197 if (lhsType->isVectorType() && rhsType->isVectorType() &&
6198 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John McCall2de56d12010-08-25 11:45:40 +00006199 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor255210e2010-08-06 10:14:59 +00006200 return rhsType;
6201 }
6202
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006203 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6204 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6205 bool swapped = false;
6206 if (rhsType->isExtVectorType()) {
6207 swapped = true;
6208 std::swap(rex, lex);
6209 std::swap(rhsType, lhsType);
6210 }
Mike Stump1eb44332009-09-09 15:08:12 +00006211
Nate Begemandde25982009-06-28 19:12:57 +00006212 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00006213 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006214 QualType EltTy = LV->getElementType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00006215 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006216 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6217 if (order > 0)
6218 ImpCastExprToType(rex, EltTy, CK_IntegralCast);
6219 if (order >= 0) {
6220 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006221 if (swapped) std::swap(rex, lex);
6222 return lhsType;
6223 }
6224 }
6225 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6226 rhsType->isRealFloatingType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006227 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6228 if (order > 0)
6229 ImpCastExprToType(rex, EltTy, CK_FloatingCast);
6230 if (order >= 0) {
6231 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006232 if (swapped) std::swap(rex, lex);
6233 return lhsType;
6234 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00006235 }
6236 }
Mike Stump1eb44332009-09-09 15:08:12 +00006237
Nate Begemandde25982009-06-28 19:12:57 +00006238 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006239 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00006240 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006241 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006242 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00006243}
6244
Chris Lattner7ef655a2010-01-12 21:23:57 +00006245QualType Sema::CheckMultiplyDivideOperands(
6246 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00006247 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006248 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006249
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006250 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006251
Chris Lattner7ef655a2010-01-12 21:23:57 +00006252 if (!lex->getType()->isArithmeticType() ||
6253 !rex->getType()->isArithmeticType())
6254 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006255
Chris Lattner7ef655a2010-01-12 21:23:57 +00006256 // Check for division by zero.
6257 if (isDiv &&
6258 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006259 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
Chris Lattnercb329c52010-01-12 21:30:55 +00006260 << rex->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006261
Chris Lattner7ef655a2010-01-12 21:23:57 +00006262 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006263}
6264
Chris Lattner7ef655a2010-01-12 21:23:57 +00006265QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00006266 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00006267 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
Douglas Gregorf6094622010-07-23 15:58:24 +00006268 if (lex->getType()->hasIntegerRepresentation() &&
6269 rex->getType()->hasIntegerRepresentation())
Daniel Dunbar523aa602009-01-05 22:55:36 +00006270 return CheckVectorOperands(Loc, lex, rex);
6271 return InvalidOperands(Loc, lex, rex);
6272 }
Steve Naroff90045e82007-07-13 23:32:42 +00006273
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006274 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006275
Chris Lattner7ef655a2010-01-12 21:23:57 +00006276 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
6277 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006278
Chris Lattner7ef655a2010-01-12 21:23:57 +00006279 // Check for remainder by zero.
6280 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattnercb329c52010-01-12 21:30:55 +00006281 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
6282 << rex->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006283
Chris Lattner7ef655a2010-01-12 21:23:57 +00006284 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006285}
6286
Chris Lattner7ef655a2010-01-12 21:23:57 +00006287QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00006288 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006289 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6290 QualType compType = CheckVectorOperands(Loc, lex, rex);
6291 if (CompLHSTy) *CompLHSTy = compType;
6292 return compType;
6293 }
Steve Naroff49b45262007-07-13 16:58:59 +00006294
Eli Friedmanab3a8522009-03-28 01:22:36 +00006295 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00006296
Reid Spencer5f016e22007-07-11 17:01:13 +00006297 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00006298 if (lex->getType()->isArithmeticType() &&
6299 rex->getType()->isArithmeticType()) {
6300 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006301 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006302 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006303
Eli Friedmand72d16e2008-05-18 18:08:51 +00006304 // Put any potential pointer into PExp
6305 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006306 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00006307 std::swap(PExp, IExp);
6308
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006309 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006310
Eli Friedmand72d16e2008-05-18 18:08:51 +00006311 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00006312 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00006313
Chris Lattnerb5f15622009-04-24 23:50:08 +00006314 // Check for arithmetic on pointers to incomplete types.
6315 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006316 if (getLangOptions().CPlusPlus) {
6317 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006318 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006319 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006320 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006321
6322 // GNU extension: arithmetic on pointer to void
6323 Diag(Loc, diag::ext_gnu_void_ptr)
6324 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00006325 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006326 if (getLangOptions().CPlusPlus) {
6327 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6328 << lex->getType() << lex->getSourceRange();
6329 return QualType();
6330 }
6331
6332 // GNU extension: arithmetic on pointer to function
6333 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6334 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00006335 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00006336 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00006337 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00006338 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00006339 PExp->getType()->isObjCObjectPointerType()) &&
6340 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00006341 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6342 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00006343 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00006344 return QualType();
6345 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00006346 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00006347 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00006348 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6349 << PointeeTy << PExp->getSourceRange();
6350 return QualType();
6351 }
Mike Stump1eb44332009-09-09 15:08:12 +00006352
Eli Friedmanab3a8522009-03-28 01:22:36 +00006353 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00006354 QualType LHSTy = Context.isPromotableBitField(lex);
6355 if (LHSTy.isNull()) {
6356 LHSTy = lex->getType();
6357 if (LHSTy->isPromotableIntegerType())
6358 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00006359 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00006360 *CompLHSTy = LHSTy;
6361 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00006362 return PExp->getType();
6363 }
6364 }
6365
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006366 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006367}
6368
Chris Lattnereca7be62008-04-07 05:30:13 +00006369// C99 6.5.6
6370QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00006371 SourceLocation Loc, QualType* CompLHSTy) {
6372 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6373 QualType compType = CheckVectorOperands(Loc, lex, rex);
6374 if (CompLHSTy) *CompLHSTy = compType;
6375 return compType;
6376 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006377
Eli Friedmanab3a8522009-03-28 01:22:36 +00006378 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006379
Chris Lattner6e4ab612007-12-09 21:53:25 +00006380 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006381
Chris Lattner6e4ab612007-12-09 21:53:25 +00006382 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00006383 if (lex->getType()->isArithmeticType()
6384 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006385 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006386 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006387 }
Mike Stump1eb44332009-09-09 15:08:12 +00006388
Chris Lattner6e4ab612007-12-09 21:53:25 +00006389 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006390 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00006391 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006392
Douglas Gregore7450f52009-03-24 19:52:54 +00006393 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00006394
Douglas Gregore7450f52009-03-24 19:52:54 +00006395 bool ComplainAboutVoid = false;
6396 Expr *ComplainAboutFunc = 0;
6397 if (lpointee->isVoidType()) {
6398 if (getLangOptions().CPlusPlus) {
6399 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6400 << lex->getSourceRange() << rex->getSourceRange();
6401 return QualType();
6402 }
6403
6404 // GNU C extension: arithmetic on pointer to void
6405 ComplainAboutVoid = true;
6406 } else if (lpointee->isFunctionType()) {
6407 if (getLangOptions().CPlusPlus) {
6408 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00006409 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006410 return QualType();
6411 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006412
6413 // GNU C extension: arithmetic on pointer to function
6414 ComplainAboutFunc = lex;
6415 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00006416 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00006417 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00006418 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00006419 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00006420 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006421
Chris Lattnerb5f15622009-04-24 23:50:08 +00006422 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00006423 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00006424 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6425 << lpointee << lex->getSourceRange();
6426 return QualType();
6427 }
Mike Stump1eb44332009-09-09 15:08:12 +00006428
Chris Lattner6e4ab612007-12-09 21:53:25 +00006429 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00006430 if (rex->getType()->isIntegerType()) {
6431 if (ComplainAboutVoid)
6432 Diag(Loc, diag::ext_gnu_void_ptr)
6433 << lex->getSourceRange() << rex->getSourceRange();
6434 if (ComplainAboutFunc)
6435 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00006436 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00006437 << ComplainAboutFunc->getSourceRange();
6438
Eli Friedmanab3a8522009-03-28 01:22:36 +00006439 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006440 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006441 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006442
Chris Lattner6e4ab612007-12-09 21:53:25 +00006443 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006444 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006445 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006446
Douglas Gregore7450f52009-03-24 19:52:54 +00006447 // RHS must be a completely-type object type.
6448 // Handle the GNU void* extension.
6449 if (rpointee->isVoidType()) {
6450 if (getLangOptions().CPlusPlus) {
6451 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6452 << lex->getSourceRange() << rex->getSourceRange();
6453 return QualType();
6454 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006455
Douglas Gregore7450f52009-03-24 19:52:54 +00006456 ComplainAboutVoid = true;
6457 } else if (rpointee->isFunctionType()) {
6458 if (getLangOptions().CPlusPlus) {
6459 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00006460 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006461 return QualType();
6462 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006463
6464 // GNU extension: arithmetic on pointer to function
6465 if (!ComplainAboutFunc)
6466 ComplainAboutFunc = rex;
6467 } else if (!rpointee->isDependentType() &&
6468 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00006469 PDiag(diag::err_typecheck_sub_ptr_object)
6470 << rex->getSourceRange()
6471 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00006472 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006473
Eli Friedman88d936b2009-05-16 13:54:38 +00006474 if (getLangOptions().CPlusPlus) {
6475 // Pointee types must be the same: C++ [expr.add]
6476 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6477 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6478 << lex->getType() << rex->getType()
6479 << lex->getSourceRange() << rex->getSourceRange();
6480 return QualType();
6481 }
6482 } else {
6483 // Pointee types must be compatible C99 6.5.6p3
6484 if (!Context.typesAreCompatible(
6485 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6486 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6487 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6488 << lex->getType() << rex->getType()
6489 << lex->getSourceRange() << rex->getSourceRange();
6490 return QualType();
6491 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006492 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006493
Douglas Gregore7450f52009-03-24 19:52:54 +00006494 if (ComplainAboutVoid)
6495 Diag(Loc, diag::ext_gnu_void_ptr)
6496 << lex->getSourceRange() << rex->getSourceRange();
6497 if (ComplainAboutFunc)
6498 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00006499 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00006500 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006501
6502 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006503 return Context.getPointerDiffType();
6504 }
6505 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006506
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006507 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006508}
6509
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006510static bool isScopedEnumerationType(QualType T) {
6511 if (const EnumType *ET = dyn_cast<EnumType>(T))
6512 return ET->getDecl()->isScoped();
6513 return false;
6514}
6515
Chris Lattnereca7be62008-04-07 05:30:13 +00006516// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006517QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00006518 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00006519 // C99 6.5.7p2: Each of the operands shall have integer type.
Douglas Gregorf6094622010-07-23 15:58:24 +00006520 if (!lex->getType()->hasIntegerRepresentation() ||
6521 !rex->getType()->hasIntegerRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006522 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006523
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006524 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6525 // hasIntegerRepresentation() above instead of this.
6526 if (isScopedEnumerationType(lex->getType()) ||
6527 isScopedEnumerationType(rex->getType())) {
6528 return InvalidOperands(Loc, lex, rex);
6529 }
6530
Nate Begeman2207d792009-10-25 02:26:48 +00006531 // Vector shifts promote their scalar inputs to vector type.
6532 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6533 return CheckVectorOperands(Loc, lex, rex);
6534
Chris Lattnerca5eede2007-12-12 05:47:28 +00006535 // Shifts don't perform usual arithmetic conversions, they just do integer
6536 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006537
John McCall1bc80af2010-12-16 19:28:59 +00006538 // For the LHS, do usual unary conversions, but then reset them away
6539 // if this is a compound assignment.
6540 Expr *old_lex = lex;
6541 UsualUnaryConversions(lex);
6542 QualType LHSTy = lex->getType();
6543 if (isCompAssign) lex = old_lex;
6544
6545 // The RHS is simpler.
Chris Lattnerca5eede2007-12-12 05:47:28 +00006546 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006547
Ryan Flynnd0439682009-08-07 16:20:20 +00006548 // Sanity-check shift operands
6549 llvm::APSInt Right;
6550 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00006551 if (!rex->isValueDependent() &&
6552 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00006553 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00006554 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
6555 else {
6556 llvm::APInt LeftBits(Right.getBitWidth(),
6557 Context.getTypeSize(lex->getType()));
6558 if (Right.uge(LeftBits))
6559 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
6560 }
6561 }
6562
Chris Lattnerca5eede2007-12-12 05:47:28 +00006563 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00006564 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006565}
6566
Chandler Carruth99919472010-07-10 12:30:03 +00006567static bool IsWithinTemplateSpecialization(Decl *D) {
6568 if (DeclContext *DC = D->getDeclContext()) {
6569 if (isa<ClassTemplateSpecializationDecl>(DC))
6570 return true;
6571 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6572 return FD->isFunctionTemplateSpecialization();
6573 }
6574 return false;
6575}
6576
Douglas Gregor0c6db942009-05-04 06:07:12 +00006577// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006578QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00006579 unsigned OpaqueOpc, bool isRelational) {
John McCall2de56d12010-08-25 11:45:40 +00006580 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006581
Chris Lattner02dd4b12009-12-05 05:40:13 +00006582 // Handle vector comparisons separately.
Nate Begemanbe2341d2008-07-14 18:02:46 +00006583 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006584 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006585
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006586 QualType lType = lex->getType();
6587 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006588
Douglas Gregor8eee1192010-06-22 22:12:46 +00006589 if (!lType->hasFloatingRepresentation() &&
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006590 !(lType->isBlockPointerType() && isRelational) &&
6591 !lex->getLocStart().isMacroID() &&
6592 !rex->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006593 // For non-floating point types, check for self-comparisons of the form
6594 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6595 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006596 //
6597 // NOTE: Don't warn about comparison expressions resulting from macro
6598 // expansion. Also don't warn about comparisons which are only self
6599 // comparisons within a template specialization. The warnings should catch
6600 // obvious cases in the definition of the template anyways. The idea is to
6601 // warn when the typed comparison operator will always evaluate to the same
6602 // result.
John McCallf6a16482010-12-04 03:47:34 +00006603 Expr *LHSStripped = lex->IgnoreParenImpCasts();
6604 Expr *RHSStripped = rex->IgnoreParenImpCasts();
Chandler Carruth99919472010-07-10 12:30:03 +00006605 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006606 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006607 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006608 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006609 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6610 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006611 << (Opc == BO_EQ
6612 || Opc == BO_LE
6613 || Opc == BO_GE));
Douglas Gregord64fdd02010-06-08 19:50:34 +00006614 } else if (lType->isArrayType() && rType->isArrayType() &&
6615 !DRL->getDecl()->getType()->isReferenceType() &&
6616 !DRR->getDecl()->getType()->isReferenceType()) {
6617 // what is it always going to eval to?
6618 char always_evals_to;
6619 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006620 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006621 always_evals_to = 0; // false
6622 break;
John McCall2de56d12010-08-25 11:45:40 +00006623 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006624 always_evals_to = 1; // true
6625 break;
6626 default:
6627 // best we can say is 'a constant'
6628 always_evals_to = 2; // e.g. array1 <= array2
6629 break;
6630 }
6631 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6632 << 1 // array
6633 << always_evals_to);
6634 }
6635 }
Chandler Carruth99919472010-07-10 12:30:03 +00006636 }
Mike Stump1eb44332009-09-09 15:08:12 +00006637
Chris Lattner55660a72009-03-08 19:39:53 +00006638 if (isa<CastExpr>(LHSStripped))
6639 LHSStripped = LHSStripped->IgnoreParenCasts();
6640 if (isa<CastExpr>(RHSStripped))
6641 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006642
Chris Lattner55660a72009-03-08 19:39:53 +00006643 // Warn about comparisons against a string constant (unless the other
6644 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00006645 Expr *literalString = 0;
6646 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00006647 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006648 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006649 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00006650 literalString = lex;
6651 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006652 } else if ((isa<StringLiteral>(RHSStripped) ||
6653 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006654 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006655 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00006656 literalString = rex;
6657 literalStringStripped = RHSStripped;
6658 }
6659
6660 if (literalString) {
6661 std::string resultComparison;
6662 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006663 case BO_LT: resultComparison = ") < 0"; break;
6664 case BO_GT: resultComparison = ") > 0"; break;
6665 case BO_LE: resultComparison = ") <= 0"; break;
6666 case BO_GE: resultComparison = ") >= 0"; break;
6667 case BO_EQ: resultComparison = ") == 0"; break;
6668 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregora86b8322009-04-06 18:45:53 +00006669 default: assert(false && "Invalid comparison operator");
6670 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006671
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00006672 DiagRuntimeBehavior(Loc,
6673 PDiag(diag::warn_stringcompare)
6674 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00006675 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00006676 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00006677 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006678
Douglas Gregord64fdd02010-06-08 19:50:34 +00006679 // C99 6.5.8p3 / C99 6.5.9p4
6680 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
6681 UsualArithmeticConversions(lex, rex);
6682 else {
6683 UsualUnaryConversions(lex);
6684 UsualUnaryConversions(rex);
6685 }
6686
6687 lType = lex->getType();
6688 rType = rex->getType();
6689
Douglas Gregor447b69e2008-11-19 03:25:36 +00006690 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner02dd4b12009-12-05 05:40:13 +00006691 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00006692
Chris Lattnera5937dd2007-08-26 01:18:55 +00006693 if (isRelational) {
6694 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006695 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006696 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00006697 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006698 if (lType->hasFloatingRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006699 CheckFloatComparison(Loc,lex,rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006700
Chris Lattnera5937dd2007-08-26 01:18:55 +00006701 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006702 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006703 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006704
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006705 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006706 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006707 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006708 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006709
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006710 // All of the following pointer-related warnings are GCC extensions, except
6711 // when handling null pointer constants.
Steve Naroff77878cc2007-08-27 04:08:11 +00006712 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00006713 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00006714 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00006715 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00006716 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006717
Douglas Gregor0c6db942009-05-04 06:07:12 +00006718 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00006719 if (LCanPointeeTy == RCanPointeeTy)
6720 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006721 if (!isRelational &&
6722 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6723 // Valid unless comparison between non-null pointer and function pointer
6724 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006725 // In a SFINAE context, we treat this as a hard error to maintain
6726 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006727 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6728 && !LHSIsNull && !RHSIsNull) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006729 Diag(Loc,
6730 isSFINAEContext()?
6731 diag::err_typecheck_comparison_of_fptr_to_void
6732 : diag::ext_typecheck_comparison_of_fptr_to_void)
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006733 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006734
6735 if (isSFINAEContext())
6736 return QualType();
6737
John McCall2de56d12010-08-25 11:45:40 +00006738 ImpCastExprToType(rex, lType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006739 return ResultTy;
6740 }
6741 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006742
Douglas Gregor0c6db942009-05-04 06:07:12 +00006743 // C++ [expr.rel]p2:
6744 // [...] Pointer conversions (4.10) and qualification
6745 // conversions (4.4) are performed on pointer operands (or on
6746 // a pointer operand and a null pointer constant) to bring
6747 // them to their composite pointer type. [...]
6748 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00006749 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00006750 // comparisons of pointers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006751 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00006752 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006753 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor0c6db942009-05-04 06:07:12 +00006754 if (T.isNull()) {
6755 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6756 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6757 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006758 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006759 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006760 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006761 << lType << rType << T
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006762 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00006763 }
6764
John McCall2de56d12010-08-25 11:45:40 +00006765 ImpCastExprToType(lex, T, CK_BitCast);
6766 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00006767 return ResultTy;
6768 }
Eli Friedman3075e762009-08-23 00:27:47 +00006769 // C99 6.5.9p2 and C99 6.5.8p2
6770 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6771 RCanPointeeTy.getUnqualifiedType())) {
6772 // Valid unless a relational comparison of function pointers
6773 if (isRelational && LCanPointeeTy->isFunctionType()) {
6774 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
6775 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6776 }
6777 } else if (!isRelational &&
6778 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6779 // Valid unless comparison between non-null pointer and function pointer
6780 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6781 && !LHSIsNull && !RHSIsNull) {
6782 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
6783 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6784 }
6785 } else {
6786 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006787 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00006788 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006789 }
Eli Friedman3075e762009-08-23 00:27:47 +00006790 if (LCanPointeeTy != RCanPointeeTy)
John McCall2de56d12010-08-25 11:45:40 +00006791 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006792 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00006793 }
Mike Stump1eb44332009-09-09 15:08:12 +00006794
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006795 if (getLangOptions().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006796 // Comparison of nullptr_t with itself.
6797 if (lType->isNullPtrType() && rType->isNullPtrType())
6798 return ResultTy;
6799
Mike Stump1eb44332009-09-09 15:08:12 +00006800 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00006801 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00006802 if (RHSIsNull &&
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006803 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregor20b3e992009-08-24 17:42:35 +00006804 (!isRelational && lType->isMemberPointerType()))) {
Douglas Gregor443c2122010-08-07 13:36:37 +00006805 ImpCastExprToType(rex, lType,
6806 lType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006807 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006808 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006809 return ResultTy;
6810 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006811 if (LHSIsNull &&
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006812 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregor20b3e992009-08-24 17:42:35 +00006813 (!isRelational && rType->isMemberPointerType()))) {
Douglas Gregor443c2122010-08-07 13:36:37 +00006814 ImpCastExprToType(lex, rType,
6815 rType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006816 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006817 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006818 return ResultTy;
6819 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006820
6821 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00006822 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00006823 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6824 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00006825 // In addition, pointers to members can be compared, or a pointer to
6826 // member and a null pointer constant. Pointer to member conversions
6827 // (4.11) and qualification conversions (4.4) are performed to bring
6828 // them to a common type. If one operand is a null pointer constant,
6829 // the common type is the type of the other operand. Otherwise, the
6830 // common type is a pointer to member type similar (4.4) to the type
6831 // of one of the operands, with a cv-qualification signature (4.4)
6832 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00006833 // types.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006834 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00006835 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006836 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor20b3e992009-08-24 17:42:35 +00006837 if (T.isNull()) {
6838 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006839 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00006840 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006841 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006842 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006843 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006844 << lType << rType << T
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006845 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00006846 }
Mike Stump1eb44332009-09-09 15:08:12 +00006847
John McCall2de56d12010-08-25 11:45:40 +00006848 ImpCastExprToType(lex, T, CK_BitCast);
6849 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00006850 return ResultTy;
6851 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006852 }
Mike Stump1eb44332009-09-09 15:08:12 +00006853
Steve Naroff1c7d0672008-09-04 15:10:53 +00006854 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00006855 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00006856 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6857 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006858
Steve Naroff1c7d0672008-09-04 15:10:53 +00006859 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00006860 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006861 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00006862 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00006863 }
John McCall2de56d12010-08-25 11:45:40 +00006864 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006865 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006866 }
Steve Naroff59f53942008-09-28 01:11:11 +00006867 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00006868 if (!isRelational
6869 && ((lType->isBlockPointerType() && rType->isPointerType())
6870 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00006871 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00006872 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006873 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00006874 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006875 ->getPointeeType()->isVoidType())))
6876 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
6877 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00006878 }
John McCall2de56d12010-08-25 11:45:40 +00006879 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006880 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00006881 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00006882
Steve Naroff14108da2009-07-10 23:34:53 +00006883 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00006884 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00006885 const PointerType *LPT = lType->getAs<PointerType>();
6886 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006887 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00006888 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006889 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00006890 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006891
Steve Naroffa8069f12008-11-17 19:49:16 +00006892 if (!LPtrToVoid && !RPtrToVoid &&
6893 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006894 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00006895 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00006896 }
John McCall2de56d12010-08-25 11:45:40 +00006897 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006898 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00006899 }
Steve Naroff14108da2009-07-10 23:34:53 +00006900 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00006901 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00006902 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
6903 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00006904 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006905 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00006906 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00006907 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006908 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6909 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006910 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006911 bool isError = false;
6912 if ((LHSIsNull && lType->isIntegerType()) ||
6913 (RHSIsNull && rType->isIntegerType())) {
6914 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006915 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006916 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006917 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006918 else if (getLangOptions().CPlusPlus) {
6919 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6920 isError = true;
6921 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006922 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00006923
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006924 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00006925 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00006926 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006927 if (isError)
6928 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00006929 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006930
6931 if (lType->isIntegerType())
John McCall404cd162010-11-13 01:35:44 +00006932 ImpCastExprToType(lex, rType,
6933 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006934 else
John McCall404cd162010-11-13 01:35:44 +00006935 ImpCastExprToType(rex, lType,
6936 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006937 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006938 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006939
Steve Naroff39218df2008-09-04 16:56:14 +00006940 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00006941 if (!isRelational && RHSIsNull
6942 && lType->isBlockPointerType() && rType->isIntegerType()) {
John McCall404cd162010-11-13 01:35:44 +00006943 ImpCastExprToType(rex, lType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006944 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006945 }
Mike Stumpaf199f32009-05-07 18:43:07 +00006946 if (!isRelational && LHSIsNull
6947 && lType->isIntegerType() && rType->isBlockPointerType()) {
John McCall404cd162010-11-13 01:35:44 +00006948 ImpCastExprToType(lex, rType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006949 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006950 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006951 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006952}
6953
Nate Begemanbe2341d2008-07-14 18:02:46 +00006954/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00006955/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00006956/// like a scalar comparison, a vector comparison produces a vector of integer
6957/// types.
6958QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006959 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00006960 bool isRelational) {
6961 // Check to make sure we're operating on vectors of the same type and width,
6962 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006963 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00006964 if (vType.isNull())
6965 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006966
Anton Yartsevaa4fe052010-11-18 03:19:30 +00006967 // If AltiVec, the comparison results in a numeric type, i.e.
6968 // bool for C++, int for C
6969 if (getLangOptions().AltiVec)
6970 return (getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy);
6971
Nate Begemanbe2341d2008-07-14 18:02:46 +00006972 QualType lType = lex->getType();
6973 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006974
Nate Begemanbe2341d2008-07-14 18:02:46 +00006975 // For non-floating point types, check for self-comparisons of the form
6976 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6977 // often indicate logic errors in the program.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006978 if (!lType->hasFloatingRepresentation()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00006979 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
6980 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
6981 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregord64fdd02010-06-08 19:50:34 +00006982 DiagRuntimeBehavior(Loc,
6983 PDiag(diag::warn_comparison_always)
6984 << 0 // self-
6985 << 2 // "a constant"
6986 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00006987 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006988
Nate Begemanbe2341d2008-07-14 18:02:46 +00006989 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006990 if (!isRelational && lType->hasFloatingRepresentation()) {
6991 assert (rType->hasFloatingRepresentation());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006992 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00006993 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006994
Nate Begemanbe2341d2008-07-14 18:02:46 +00006995 // Return the type for the comparison, which is the same as vector type for
6996 // integer vectors, or an integer type of identical size and number of
6997 // elements for floating point vectors.
Douglas Gregorf6094622010-07-23 15:58:24 +00006998 if (lType->hasIntegerRepresentation())
Nate Begemanbe2341d2008-07-14 18:02:46 +00006999 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007000
John McCall183700f2009-09-21 23:43:11 +00007001 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00007002 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00007003 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007004 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00007005 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00007006 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7007
Mike Stumpeed9cac2009-02-19 03:04:26 +00007008 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00007009 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00007010 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7011}
7012
Reid Spencer5f016e22007-07-11 17:01:13 +00007013inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00007014 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Douglas Gregorf6094622010-07-23 15:58:24 +00007015 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
7016 if (lex->getType()->hasIntegerRepresentation() &&
7017 rex->getType()->hasIntegerRepresentation())
7018 return CheckVectorOperands(Loc, lex, rex);
7019
7020 return InvalidOperands(Loc, lex, rex);
7021 }
Steve Naroff90045e82007-07-13 23:32:42 +00007022
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007023 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007024
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007025 if (lex->getType()->isIntegralOrUnscopedEnumerationType() &&
7026 rex->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007027 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007028 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007029}
7030
7031inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner90a8f272010-07-13 19:41:32 +00007032 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
7033
7034 // Diagnose cases where the user write a logical and/or but probably meant a
7035 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7036 // is a constant.
7037 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
Eli Friedman787b0942010-07-27 19:14:53 +00007038 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
Chris Lattner23ef3e42010-07-15 00:26:43 +00007039 // Don't warn in macros.
Chris Lattnerb7690b42010-07-24 01:10:11 +00007040 !Loc.isMacroID()) {
7041 // If the RHS can be constant folded, and if it constant folds to something
7042 // that isn't 0 or 1 (which indicate a potential logical operation that
7043 // happened to fold to true/false) then warn.
7044 Expr::EvalResult Result;
7045 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
7046 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
7047 Diag(Loc, diag::warn_logical_instead_of_bitwise)
7048 << rex->getSourceRange()
John McCall2de56d12010-08-25 11:45:40 +00007049 << (Opc == BO_LAnd ? "&&" : "||")
7050 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattnerb7690b42010-07-24 01:10:11 +00007051 }
7052 }
Chris Lattner90a8f272010-07-13 19:41:32 +00007053
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007054 if (!Context.getLangOptions().CPlusPlus) {
7055 UsualUnaryConversions(lex);
7056 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007057
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007058 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
7059 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007060
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007061 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00007062 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007063
John McCall75f7c0f2010-06-04 00:29:51 +00007064 // The following is safe because we only use this method for
7065 // non-overloadable operands.
7066
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007067 // C++ [expr.log.and]p1
7068 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007069 // The operands are both contextually converted to type bool.
7070 if (PerformContextuallyConvertToBool(lex) ||
7071 PerformContextuallyConvertToBool(rex))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007072 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007073
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007074 // C++ [expr.log.and]p2
7075 // C++ [expr.log.or]p2
7076 // The result is a bool.
7077 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007078}
7079
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007080/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7081/// is a read-only property; return true if so. A readonly property expression
7082/// depends on various declarations and thus must be treated specially.
7083///
Mike Stump1eb44332009-09-09 15:08:12 +00007084static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007085 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7086 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCall12f78a62010-12-02 01:19:52 +00007087 if (PropExpr->isImplicitProperty()) return false;
7088
7089 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7090 QualType BaseType = PropExpr->isSuperReceiver() ?
7091 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007092 PropExpr->getBase()->getType();
7093
John McCall12f78a62010-12-02 01:19:52 +00007094 if (const ObjCObjectPointerType *OPT =
7095 BaseType->getAsObjCInterfacePointerType())
7096 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7097 if (S.isPropertyReadonly(PDecl, IFace))
7098 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007099 }
7100 return false;
7101}
7102
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007103/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7104/// emit an error and return true. If so, return false.
7105static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007106 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007107 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007108 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007109 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7110 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007111 if (IsLV == Expr::MLV_Valid)
7112 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007113
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007114 unsigned Diag = 0;
7115 bool NeedType = false;
7116 switch (IsLV) { // C99 6.5.16p2
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007117 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007118 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007119 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7120 NeedType = true;
7121 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007122 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007123 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7124 NeedType = true;
7125 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007126 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007127 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7128 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007129 case Expr::MLV_Valid:
7130 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007131 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007132 case Expr::MLV_MemberFunction:
7133 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007134 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7135 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007136 case Expr::MLV_IncompleteType:
7137 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007138 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007139 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00007140 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00007141 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007142 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7143 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00007144 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007145 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7146 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007147 case Expr::MLV_ReadonlyProperty:
7148 Diag = diag::error_readonly_property_assignment;
7149 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007150 case Expr::MLV_NoSetterProperty:
7151 Diag = diag::error_nosetter_property_assignment;
7152 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007153 case Expr::MLV_SubObjCPropertySetting:
7154 Diag = diag::error_no_subobject_property_setting;
7155 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007156 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007157
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007158 SourceRange Assign;
7159 if (Loc != OrigLoc)
7160 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007161 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007162 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007163 else
Mike Stump1eb44332009-09-09 15:08:12 +00007164 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007165 return true;
7166}
7167
7168
7169
7170// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007171QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
7172 SourceLocation Loc,
7173 QualType CompoundType) {
7174 // Verify that LHS is a modifiable lvalue, and emit error if not.
7175 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007176 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007177
7178 QualType LHSType = LHS->getType();
7179 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007180 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007181 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007182 QualType LHSTy(LHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007183 // Simple assignment "x = y".
John McCallf6a16482010-12-04 03:47:34 +00007184 if (LHS->getObjectKind() == OK_ObjCProperty)
7185 ConvertPropertyForLValue(LHS, RHS, LHSTy);
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007186 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007187 // Special case of NSObject attributes on c-style pointer types.
7188 if (ConvTy == IncompatiblePointer &&
7189 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007190 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007191 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007192 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007193 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007194
John McCallf89e55a2010-11-18 06:31:45 +00007195 if (ConvTy == Compatible &&
7196 getLangOptions().ObjCNonFragileABI &&
7197 LHSType->isObjCObjectType())
7198 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7199 << LHSType;
7200
Chris Lattner2c156472008-08-21 18:04:13 +00007201 // If the RHS is a unary plus or minus, check to see if they = and + are
7202 // right next to each other. If so, the user may have typo'd "x =+ 4"
7203 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007204 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00007205 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7206 RHSCheck = ICE->getSubExpr();
7207 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007208 if ((UO->getOpcode() == UO_Plus ||
7209 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007210 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007211 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00007212 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7213 // And there is a space or other character before the subexpr of the
7214 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00007215 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7216 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007217 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007218 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007219 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007220 }
Chris Lattner2c156472008-08-21 18:04:13 +00007221 }
7222 } else {
7223 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007224 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007225 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007226
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007227 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor68647482009-12-16 03:45:30 +00007228 RHS, AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007229 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007230
Chris Lattner8b5dec32010-07-07 06:14:23 +00007231
7232 // Check to see if the destination operand is a dereferenced null pointer. If
7233 // so, and if not volatile-qualified, this is undefined behavior that the
7234 // optimizer will delete, so warn about it. People sometimes try to use this
7235 // to get a deterministic trap and are surprised by clang's behavior. This
7236 // only handles the pattern "*null = whatever", which is a very syntactic
7237 // check.
7238 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
John McCall2de56d12010-08-25 11:45:40 +00007239 if (UO->getOpcode() == UO_Deref &&
Chris Lattner8b5dec32010-07-07 06:14:23 +00007240 UO->getSubExpr()->IgnoreParenCasts()->
7241 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
7242 !UO->getType().isVolatileQualified()) {
7243 Diag(UO->getOperatorLoc(), diag::warn_indirection_through_null)
7244 << UO->getSubExpr()->getSourceRange();
7245 Diag(UO->getOperatorLoc(), diag::note_indirection_through_null);
7246 }
7247
Ted Kremeneka0125d82011-02-16 01:57:07 +00007248 // Check for trivial buffer overflows.
7249 if (const ArraySubscriptExpr *ae
7250 = dyn_cast<ArraySubscriptExpr>(LHS->IgnoreParenCasts()))
7251 CheckArrayAccess(ae);
7252
Reid Spencer5f016e22007-07-11 17:01:13 +00007253 // C99 6.5.16p3: The type of an assignment expression is the type of the
7254 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007255 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007256 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7257 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007258 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007259 // operand.
John McCall2bf6f492010-10-12 02:19:57 +00007260 return (getLangOptions().CPlusPlus
7261 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007262}
7263
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007264// C99 6.5.17
John McCallf6a16482010-12-04 03:47:34 +00007265static QualType CheckCommaOperands(Sema &S, Expr *&LHS, Expr *&RHS,
John McCall09431682010-11-18 19:01:18 +00007266 SourceLocation Loc) {
7267 S.DiagnoseUnusedExprResult(LHS);
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00007268
John McCall09431682010-11-18 19:01:18 +00007269 ExprResult LHSResult = S.CheckPlaceholderExpr(LHS, Loc);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007270 if (LHSResult.isInvalid())
7271 return QualType();
7272
John McCall09431682010-11-18 19:01:18 +00007273 ExprResult RHSResult = S.CheckPlaceholderExpr(RHS, Loc);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007274 if (RHSResult.isInvalid())
7275 return QualType();
7276 RHS = RHSResult.take();
7277
John McCallcf2e5062010-10-12 07:14:40 +00007278 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7279 // operands, but not unary promotions.
7280 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007281
John McCallf6a16482010-12-04 03:47:34 +00007282 // So we treat the LHS as a ignored value, and in C++ we allow the
7283 // containing site to determine what should be done with the RHS.
7284 S.IgnoredValueConversions(LHS);
7285
7286 if (!S.getLangOptions().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007287 S.DefaultFunctionArrayLvalueConversion(RHS);
John McCallcf2e5062010-10-12 07:14:40 +00007288 if (!RHS->getType()->isVoidType())
John McCall09431682010-11-18 19:01:18 +00007289 S.RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007290 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007291
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007292 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007293}
7294
Steve Naroff49b45262007-07-13 16:58:59 +00007295/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7296/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007297static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7298 ExprValueKind &VK,
7299 SourceLocation OpLoc,
7300 bool isInc, bool isPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007301 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007302 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007303
Chris Lattner3528d352008-11-21 07:05:48 +00007304 QualType ResType = Op->getType();
7305 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007306
John McCall09431682010-11-18 19:01:18 +00007307 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007308 // Decrement of bool is not allowed.
7309 if (!isInc) {
John McCall09431682010-11-18 19:01:18 +00007310 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007311 return QualType();
7312 }
7313 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007314 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007315 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007316 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00007317 } else if (ResType->isAnyPointerType()) {
7318 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00007319
Chris Lattner3528d352008-11-21 07:05:48 +00007320 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00007321 if (PointeeTy->isVoidType()) {
John McCall09431682010-11-18 19:01:18 +00007322 if (S.getLangOptions().CPlusPlus) {
7323 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00007324 << Op->getSourceRange();
7325 return QualType();
7326 }
7327
7328 // Pointer to void is a GNU extension in C.
John McCall09431682010-11-18 19:01:18 +00007329 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00007330 } else if (PointeeTy->isFunctionType()) {
John McCall09431682010-11-18 19:01:18 +00007331 if (S.getLangOptions().CPlusPlus) {
7332 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00007333 << Op->getType() << Op->getSourceRange();
7334 return QualType();
7335 }
7336
John McCall09431682010-11-18 19:01:18 +00007337 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00007338 << ResType << Op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007339 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
7340 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00007341 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00007342 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007343 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007344 // Diagnose bad cases where we step over interface counts.
John McCall09431682010-11-18 19:01:18 +00007345 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7346 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007347 << PointeeTy << Op->getSourceRange();
7348 return QualType();
7349 }
Eli Friedman5b088a12010-01-03 00:20:48 +00007350 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007351 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007352 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007353 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007354 } else if (ResType->isPlaceholderType()) {
John McCall09431682010-11-18 19:01:18 +00007355 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007356 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007357 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7358 isInc, isPrefix);
Anton Yartsev683564a2011-02-07 02:17:30 +00007359 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7360 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007361 } else {
John McCall09431682010-11-18 19:01:18 +00007362 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00007363 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007364 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007365 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007366 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007367 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007368 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007369 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007370 // In C++, a prefix increment is the same type as the operand. Otherwise
7371 // (in C or with postfix), the increment is the unqualified type of the
7372 // operand.
John McCall09431682010-11-18 19:01:18 +00007373 if (isPrefix && S.getLangOptions().CPlusPlus) {
7374 VK = VK_LValue;
7375 return ResType;
7376 } else {
7377 VK = VK_RValue;
7378 return ResType.getUnqualifiedType();
7379 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007380}
7381
John McCallf6a16482010-12-04 03:47:34 +00007382void Sema::ConvertPropertyForRValue(Expr *&E) {
7383 assert(E->getValueKind() == VK_LValue &&
7384 E->getObjectKind() == OK_ObjCProperty);
7385 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7386
7387 ExprValueKind VK = VK_RValue;
7388 if (PRE->isImplicitProperty()) {
Fariborz Jahanian99130e52010-12-22 19:46:35 +00007389 if (const ObjCMethodDecl *GetterMethod =
7390 PRE->getImplicitPropertyGetter()) {
7391 QualType Result = GetterMethod->getResultType();
7392 VK = Expr::getValueKindForType(Result);
7393 }
7394 else {
7395 Diag(PRE->getLocation(), diag::err_getter_not_found)
7396 << PRE->getBase()->getType();
7397 }
John McCallf6a16482010-12-04 03:47:34 +00007398 }
7399
7400 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
7401 E, 0, VK);
John McCalldb67e2f2010-12-10 01:49:45 +00007402
7403 ExprResult Result = MaybeBindToTemporary(E);
7404 if (!Result.isInvalid())
7405 E = Result.take();
John McCallf6a16482010-12-04 03:47:34 +00007406}
7407
7408void Sema::ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType &LHSTy) {
7409 assert(LHS->getValueKind() == VK_LValue &&
7410 LHS->getObjectKind() == OK_ObjCProperty);
7411 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7412
7413 if (PRE->isImplicitProperty()) {
7414 // If using property-dot syntax notation for assignment, and there is a
7415 // setter, RHS expression is being passed to the setter argument. So,
7416 // type conversion (and comparison) is RHS to setter's argument type.
7417 if (const ObjCMethodDecl *SetterMD = PRE->getImplicitPropertySetter()) {
7418 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7419 LHSTy = (*P)->getType();
7420
7421 // Otherwise, if the getter returns an l-value, just call that.
7422 } else {
7423 QualType Result = PRE->getImplicitPropertyGetter()->getResultType();
7424 ExprValueKind VK = Expr::getValueKindForType(Result);
7425 if (VK == VK_LValue) {
7426 LHS = ImplicitCastExpr::Create(Context, LHS->getType(),
7427 CK_GetObjCProperty, LHS, 0, VK);
7428 return;
John McCall12f78a62010-12-02 01:19:52 +00007429 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007430 }
John McCallf6a16482010-12-04 03:47:34 +00007431 }
7432
7433 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007434 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007435 InitializedEntity::InitializeParameter(Context, LHSTy);
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007436 Expr *Arg = RHS;
7437 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(),
7438 Owned(Arg));
7439 if (!ArgE.isInvalid())
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007440 RHS = ArgE.takeAs<Expr>();
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007441 }
7442}
7443
7444
Anders Carlsson369dee42008-02-01 07:15:58 +00007445/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007446/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007447/// where the declaration is needed for type checking. We only need to
7448/// handle cases when the expression references a function designator
7449/// or is an lvalue. Here are some examples:
7450/// - &(x) => x
7451/// - &*****f => f for f a function designator.
7452/// - &s.xx => s
7453/// - &s.zz[1].yy -> s, if zz is an array
7454/// - *(x + 1) -> x, if x is an array
7455/// - &"123"[2] -> 0
7456/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007457static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007458 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007459 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007460 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007461 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007462 // If this is an arrow operator, the address is an offset from
7463 // the base's value, so the object the base refers to is
7464 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007465 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007466 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007467 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007468 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007469 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007470 // FIXME: This code shouldn't be necessary! We should catch the implicit
7471 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007472 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7473 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7474 if (ICE->getSubExpr()->getType()->isArrayType())
7475 return getPrimaryDecl(ICE->getSubExpr());
7476 }
7477 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007478 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007479 case Stmt::UnaryOperatorClass: {
7480 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007481
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007482 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007483 case UO_Real:
7484 case UO_Imag:
7485 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007486 return getPrimaryDecl(UO->getSubExpr());
7487 default:
7488 return 0;
7489 }
7490 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007491 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007492 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007493 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007494 // If the result of an implicit cast is an l-value, we care about
7495 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007496 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007497 default:
7498 return 0;
7499 }
7500}
7501
7502/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007503/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007504/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007505/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007506/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007507/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007508/// we allow the '&' but retain the overloaded-function type.
John McCall09431682010-11-18 19:01:18 +00007509static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7510 SourceLocation OpLoc) {
John McCall9c72c602010-08-27 09:08:28 +00007511 if (OrigOp->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007512 return S.Context.DependentTy;
7513 if (OrigOp->getType() == S.Context.OverloadTy)
7514 return S.Context.OverloadTy;
John McCall9c72c602010-08-27 09:08:28 +00007515
John McCall09431682010-11-18 19:01:18 +00007516 ExprResult PR = S.CheckPlaceholderExpr(OrigOp, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007517 if (PR.isInvalid()) return QualType();
7518 OrigOp = PR.take();
7519
John McCall9c72c602010-08-27 09:08:28 +00007520 // Make sure to ignore parentheses in subsequent checks
7521 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00007522
John McCall09431682010-11-18 19:01:18 +00007523 if (S.getLangOptions().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00007524 // Implement C99-only parts of addressof rules.
7525 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00007526 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00007527 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7528 // (assuming the deref expression is valid).
7529 return uOp->getSubExpr()->getType();
7530 }
7531 // Technically, there should be a check for array subscript
7532 // expressions here, but the result of one is always an lvalue anyway.
7533 }
John McCall5808ce42011-02-03 08:15:49 +00007534 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00007535 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00007536
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007537 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00007538 bool sfinae = S.isSFINAEContext();
7539 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7540 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00007541 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007542 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00007543 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00007544 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007545 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00007546 } else if (lval == Expr::LV_MemberFunction) {
7547 // If it's an instance method, make a member pointer.
7548 // The expression must have exactly the form &A::foo.
7549
7550 // If the underlying expression isn't a decl ref, give up.
7551 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007552 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007553 << OrigOp->getSourceRange();
7554 return QualType();
7555 }
7556 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7557 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7558
7559 // The id-expression was parenthesized.
7560 if (OrigOp != DRE) {
John McCall09431682010-11-18 19:01:18 +00007561 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007562 << OrigOp->getSourceRange();
7563
7564 // The method was named without a qualifier.
7565 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00007566 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007567 << op->getSourceRange();
7568 }
7569
John McCall09431682010-11-18 19:01:18 +00007570 return S.Context.getMemberPointerType(op->getType(),
7571 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00007572 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00007573 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007574 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00007575 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00007576 // FIXME: emit more specific diag...
John McCall09431682010-11-18 19:01:18 +00007577 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00007578 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007579 return QualType();
7580 }
John McCall7eb0a9e2010-11-24 05:12:34 +00007581 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007582 // The operand cannot be a bit-field
John McCall09431682010-11-18 19:01:18 +00007583 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman23d58ce2009-04-20 08:23:18 +00007584 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00007585 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00007586 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00007587 // The operand cannot be an element of a vector
John McCall09431682010-11-18 19:01:18 +00007588 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00007589 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00007590 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00007591 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007592 // cannot take address of a property expression.
John McCall09431682010-11-18 19:01:18 +00007593 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007594 << "property expression" << op->getSourceRange();
7595 return QualType();
Steve Naroffbcb2b612008-02-29 23:30:25 +00007596 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00007597 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00007598 // with the register storage-class specifier.
7599 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00007600 // in C++ it is not error to take address of a register
7601 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00007602 if (vd->getStorageClass() == SC_Register &&
John McCall09431682010-11-18 19:01:18 +00007603 !S.getLangOptions().CPlusPlus) {
7604 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007605 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007606 return QualType();
7607 }
John McCallba135432009-11-21 08:51:07 +00007608 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00007609 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00007610 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00007611 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00007612 // Could be a pointer to member, though, if there is an explicit
7613 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00007614 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00007615 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007616 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00007617 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00007618 S.Diag(OpLoc,
7619 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00007620 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007621 return QualType();
7622 }
Mike Stump1eb44332009-09-09 15:08:12 +00007623
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00007624 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7625 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00007626 return S.Context.getMemberPointerType(op->getType(),
7627 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007628 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00007629 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00007630 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00007631 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00007632 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00007633
Eli Friedman441cf102009-05-16 23:27:50 +00007634 if (lval == Expr::LV_IncompleteVoidType) {
7635 // Taking the address of a void variable is technically illegal, but we
7636 // allow it in cases which are otherwise valid.
7637 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00007638 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00007639 }
7640
Reid Spencer5f016e22007-07-11 17:01:13 +00007641 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00007642 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00007643 return S.Context.getObjCObjectPointerType(op->getType());
7644 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007645}
7646
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007647/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00007648static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7649 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00007650 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007651 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007652
John McCall09431682010-11-18 19:01:18 +00007653 S.UsualUnaryConversions(Op);
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007654 QualType OpTy = Op->getType();
7655 QualType Result;
7656
7657 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7658 // is an incomplete type or void. It would be possible to warn about
7659 // dereferencing a void pointer, but it's completely well-defined, and such a
7660 // warning is unlikely to catch any mistakes.
7661 if (const PointerType *PT = OpTy->getAs<PointerType>())
7662 Result = PT->getPointeeType();
7663 else if (const ObjCObjectPointerType *OPT =
7664 OpTy->getAs<ObjCObjectPointerType>())
7665 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00007666 else {
John McCall09431682010-11-18 19:01:18 +00007667 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007668 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007669 if (PR.take() != Op)
7670 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007671 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007672
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007673 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00007674 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007675 << OpTy << Op->getSourceRange();
7676 return QualType();
7677 }
John McCall09431682010-11-18 19:01:18 +00007678
7679 // Dereferences are usually l-values...
7680 VK = VK_LValue;
7681
7682 // ...except that certain expressions are never l-values in C.
7683 if (!S.getLangOptions().CPlusPlus &&
7684 IsCForbiddenLValueType(S.Context, Result))
7685 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007686
7687 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00007688}
7689
John McCall2de56d12010-08-25 11:45:40 +00007690static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007691 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007692 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007693 switch (Kind) {
7694 default: assert(0 && "Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00007695 case tok::periodstar: Opc = BO_PtrMemD; break;
7696 case tok::arrowstar: Opc = BO_PtrMemI; break;
7697 case tok::star: Opc = BO_Mul; break;
7698 case tok::slash: Opc = BO_Div; break;
7699 case tok::percent: Opc = BO_Rem; break;
7700 case tok::plus: Opc = BO_Add; break;
7701 case tok::minus: Opc = BO_Sub; break;
7702 case tok::lessless: Opc = BO_Shl; break;
7703 case tok::greatergreater: Opc = BO_Shr; break;
7704 case tok::lessequal: Opc = BO_LE; break;
7705 case tok::less: Opc = BO_LT; break;
7706 case tok::greaterequal: Opc = BO_GE; break;
7707 case tok::greater: Opc = BO_GT; break;
7708 case tok::exclaimequal: Opc = BO_NE; break;
7709 case tok::equalequal: Opc = BO_EQ; break;
7710 case tok::amp: Opc = BO_And; break;
7711 case tok::caret: Opc = BO_Xor; break;
7712 case tok::pipe: Opc = BO_Or; break;
7713 case tok::ampamp: Opc = BO_LAnd; break;
7714 case tok::pipepipe: Opc = BO_LOr; break;
7715 case tok::equal: Opc = BO_Assign; break;
7716 case tok::starequal: Opc = BO_MulAssign; break;
7717 case tok::slashequal: Opc = BO_DivAssign; break;
7718 case tok::percentequal: Opc = BO_RemAssign; break;
7719 case tok::plusequal: Opc = BO_AddAssign; break;
7720 case tok::minusequal: Opc = BO_SubAssign; break;
7721 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7722 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7723 case tok::ampequal: Opc = BO_AndAssign; break;
7724 case tok::caretequal: Opc = BO_XorAssign; break;
7725 case tok::pipeequal: Opc = BO_OrAssign; break;
7726 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007727 }
7728 return Opc;
7729}
7730
John McCall2de56d12010-08-25 11:45:40 +00007731static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007732 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007733 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007734 switch (Kind) {
7735 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00007736 case tok::plusplus: Opc = UO_PreInc; break;
7737 case tok::minusminus: Opc = UO_PreDec; break;
7738 case tok::amp: Opc = UO_AddrOf; break;
7739 case tok::star: Opc = UO_Deref; break;
7740 case tok::plus: Opc = UO_Plus; break;
7741 case tok::minus: Opc = UO_Minus; break;
7742 case tok::tilde: Opc = UO_Not; break;
7743 case tok::exclaim: Opc = UO_LNot; break;
7744 case tok::kw___real: Opc = UO_Real; break;
7745 case tok::kw___imag: Opc = UO_Imag; break;
7746 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007747 }
7748 return Opc;
7749}
7750
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007751/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7752/// This warning is only emitted for builtin assignment operations. It is also
7753/// suppressed in the event of macro expansions.
7754static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7755 SourceLocation OpLoc) {
7756 if (!S.ActiveTemplateInstantiations.empty())
7757 return;
7758 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7759 return;
7760 lhs = lhs->IgnoreParenImpCasts();
7761 rhs = rhs->IgnoreParenImpCasts();
7762 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7763 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7764 if (!LeftDeclRef || !RightDeclRef ||
7765 LeftDeclRef->getLocation().isMacroID() ||
7766 RightDeclRef->getLocation().isMacroID())
7767 return;
7768 const ValueDecl *LeftDecl =
7769 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7770 const ValueDecl *RightDecl =
7771 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7772 if (LeftDecl != RightDecl)
7773 return;
7774 if (LeftDecl->getType().isVolatileQualified())
7775 return;
7776 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7777 if (RefTy->getPointeeType().isVolatileQualified())
7778 return;
7779
7780 S.Diag(OpLoc, diag::warn_self_assignment)
7781 << LeftDeclRef->getType()
7782 << lhs->getSourceRange() << rhs->getSourceRange();
7783}
7784
Douglas Gregoreaebc752008-11-06 23:29:22 +00007785/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7786/// operator @p Opc at location @c TokLoc. This routine only supports
7787/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00007788ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00007789 BinaryOperatorKind Opc,
John McCall2de56d12010-08-25 11:45:40 +00007790 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00007791 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00007792 // The following two variables are used for compound assignment operators
7793 QualType CompLHSTy; // Type of LHS after promotions for computation
7794 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00007795 ExprValueKind VK = VK_RValue;
7796 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00007797
7798 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007799 case BO_Assign:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007800 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
John McCallf6a16482010-12-04 03:47:34 +00007801 if (getLangOptions().CPlusPlus &&
7802 lhs->getObjectKind() != OK_ObjCProperty) {
John McCall09431682010-11-18 19:01:18 +00007803 VK = lhs->getValueKind();
7804 OK = lhs->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007805 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007806 if (!ResultTy.isNull())
7807 DiagnoseSelfAssignment(*this, lhs, rhs, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007808 break;
John McCall2de56d12010-08-25 11:45:40 +00007809 case BO_PtrMemD:
7810 case BO_PtrMemI:
John McCallf89e55a2010-11-18 06:31:45 +00007811 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007812 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00007813 break;
John McCall2de56d12010-08-25 11:45:40 +00007814 case BO_Mul:
7815 case BO_Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00007816 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00007817 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007818 break;
John McCall2de56d12010-08-25 11:45:40 +00007819 case BO_Rem:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007820 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7821 break;
John McCall2de56d12010-08-25 11:45:40 +00007822 case BO_Add:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007823 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7824 break;
John McCall2de56d12010-08-25 11:45:40 +00007825 case BO_Sub:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007826 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7827 break;
John McCall2de56d12010-08-25 11:45:40 +00007828 case BO_Shl:
7829 case BO_Shr:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007830 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
7831 break;
John McCall2de56d12010-08-25 11:45:40 +00007832 case BO_LE:
7833 case BO_LT:
7834 case BO_GE:
7835 case BO_GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00007836 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007837 break;
John McCall2de56d12010-08-25 11:45:40 +00007838 case BO_EQ:
7839 case BO_NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00007840 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007841 break;
John McCall2de56d12010-08-25 11:45:40 +00007842 case BO_And:
7843 case BO_Xor:
7844 case BO_Or:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007845 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7846 break;
John McCall2de56d12010-08-25 11:45:40 +00007847 case BO_LAnd:
7848 case BO_LOr:
Chris Lattner90a8f272010-07-13 19:41:32 +00007849 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007850 break;
John McCall2de56d12010-08-25 11:45:40 +00007851 case BO_MulAssign:
7852 case BO_DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00007853 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00007854 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007855 CompLHSTy = CompResultTy;
7856 if (!CompResultTy.isNull())
7857 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007858 break;
John McCall2de56d12010-08-25 11:45:40 +00007859 case BO_RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007860 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7861 CompLHSTy = CompResultTy;
7862 if (!CompResultTy.isNull())
7863 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007864 break;
John McCall2de56d12010-08-25 11:45:40 +00007865 case BO_AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007866 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7867 if (!CompResultTy.isNull())
7868 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007869 break;
John McCall2de56d12010-08-25 11:45:40 +00007870 case BO_SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007871 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7872 if (!CompResultTy.isNull())
7873 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007874 break;
John McCall2de56d12010-08-25 11:45:40 +00007875 case BO_ShlAssign:
7876 case BO_ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007877 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
7878 CompLHSTy = CompResultTy;
7879 if (!CompResultTy.isNull())
7880 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007881 break;
John McCall2de56d12010-08-25 11:45:40 +00007882 case BO_AndAssign:
7883 case BO_XorAssign:
7884 case BO_OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007885 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7886 CompLHSTy = CompResultTy;
7887 if (!CompResultTy.isNull())
7888 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007889 break;
John McCall2de56d12010-08-25 11:45:40 +00007890 case BO_Comma:
John McCall09431682010-11-18 19:01:18 +00007891 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John McCallf89e55a2010-11-18 06:31:45 +00007892 if (getLangOptions().CPlusPlus) {
7893 VK = rhs->getValueKind();
7894 OK = rhs->getObjectKind();
7895 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00007896 break;
7897 }
7898 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00007899 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00007900 if (CompResultTy.isNull())
John McCallf89e55a2010-11-18 06:31:45 +00007901 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy,
7902 VK, OK, OpLoc));
7903
John McCallf6a16482010-12-04 03:47:34 +00007904 if (getLangOptions().CPlusPlus && lhs->getObjectKind() != OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00007905 VK = VK_LValue;
7906 OK = lhs->getObjectKind();
7907 }
7908 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
7909 VK, OK, CompLHSTy,
7910 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00007911}
7912
Sebastian Redlaee3c932009-10-27 12:10:02 +00007913/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
7914/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00007915static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7916 const PartialDiagnostic &PD,
Douglas Gregor55b38842010-04-14 16:09:52 +00007917 const PartialDiagnostic &FirstNote,
7918 SourceRange FirstParenRange,
7919 const PartialDiagnostic &SecondNote,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007920 SourceRange SecondParenRange) {
Douglas Gregor55b38842010-04-14 16:09:52 +00007921 Self.Diag(Loc, PD);
7922
7923 if (!FirstNote.getDiagID())
7924 return;
7925
7926 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
7927 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
7928 // We can't display the parentheses, so just return.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00007929 return;
7930 }
7931
Douglas Gregor55b38842010-04-14 16:09:52 +00007932 Self.Diag(Loc, FirstNote)
7933 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregor849b2432010-03-31 17:46:05 +00007934 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007935
Douglas Gregor55b38842010-04-14 16:09:52 +00007936 if (!SecondNote.getDiagID())
Douglas Gregor827feec2010-01-08 00:20:23 +00007937 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007938
Douglas Gregor827feec2010-01-08 00:20:23 +00007939 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
7940 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
7941 // We can't display the parentheses, so just dig the
7942 // warning/error and return.
Douglas Gregor55b38842010-04-14 16:09:52 +00007943 Self.Diag(Loc, SecondNote);
Douglas Gregor827feec2010-01-08 00:20:23 +00007944 return;
7945 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007946
Douglas Gregor55b38842010-04-14 16:09:52 +00007947 Self.Diag(Loc, SecondNote)
Douglas Gregor849b2432010-03-31 17:46:05 +00007948 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
7949 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl6b169ac2009-10-26 17:01:32 +00007950}
7951
Sebastian Redlaee3c932009-10-27 12:10:02 +00007952/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7953/// operators are mixed in a way that suggests that the programmer forgot that
7954/// comparison operators have higher precedence. The most typical example of
7955/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00007956static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007957 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00007958 typedef BinaryOperator BinOp;
7959 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7960 rhsopc = static_cast<BinOp::Opcode>(-1);
7961 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007962 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00007963 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007964 rhsopc = BO->getOpcode();
7965
7966 // Subs are not binary operators.
7967 if (lhsopc == -1 && rhsopc == -1)
7968 return;
7969
7970 // Bitwise operations are sometimes used as eager logical ops.
7971 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00007972 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7973 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007974 return;
7975
Sebastian Redlaee3c932009-10-27 12:10:02 +00007976 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00007977 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007978 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00007979 << SourceRange(lhs->getLocStart(), OpLoc)
7980 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007981 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00007982 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00007983 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
7984 Self.PDiag(diag::note_precedence_bitwise_silence)
7985 << BinOp::getOpcodeStr(lhsopc),
7986 lhs->getSourceRange());
Sebastian Redlaee3c932009-10-27 12:10:02 +00007987 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00007988 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007989 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00007990 << SourceRange(OpLoc, rhs->getLocEnd())
7991 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007992 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00007993 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00007994 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
7995 Self.PDiag(diag::note_precedence_bitwise_silence)
7996 << BinOp::getOpcodeStr(rhsopc),
7997 rhs->getSourceRange());
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007998}
7999
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008000/// \brief It accepts a '&&' expr that is inside a '||' one.
8001/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8002/// in parentheses.
8003static void
8004EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8005 Expr *E) {
8006 assert(isa<BinaryOperator>(E) &&
8007 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
8008 SuggestParentheses(Self, OpLoc,
8009 Self.PDiag(diag::warn_logical_and_in_logical_or)
8010 << E->getSourceRange(),
8011 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
8012 E->getSourceRange(),
8013 Self.PDiag(0), SourceRange());
8014}
8015
8016/// \brief Returns true if the given expression can be evaluated as a constant
8017/// 'true'.
8018static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8019 bool Res;
8020 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8021}
8022
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008023/// \brief Returns true if the given expression can be evaluated as a constant
8024/// 'false'.
8025static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8026 bool Res;
8027 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8028}
8029
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008030/// \brief Look for '&&' in the left hand of a '||' expr.
8031static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008032 Expr *OrLHS, Expr *OrRHS) {
8033 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008034 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008035 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8036 if (EvaluatesAsFalse(S, OrRHS))
8037 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008038 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8039 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8040 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8041 } else if (Bop->getOpcode() == BO_LOr) {
8042 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8043 // If it's "a || b && 1 || c" we didn't warn earlier for
8044 // "a || b && 1", but warn now.
8045 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8046 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8047 }
8048 }
8049 }
8050}
8051
8052/// \brief Look for '&&' in the right hand of a '||' expr.
8053static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008054 Expr *OrLHS, Expr *OrRHS) {
8055 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008056 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008057 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8058 if (EvaluatesAsFalse(S, OrLHS))
8059 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008060 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8061 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8062 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008063 }
8064 }
8065}
8066
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008067/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008068/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008069static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008070 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008071 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008072 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008073 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
8074
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008075 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8076 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008077 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008078 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
8079 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008080 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008081}
8082
Reid Spencer5f016e22007-07-11 17:01:13 +00008083// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008084ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008085 tok::TokenKind Kind,
8086 Expr *lhs, Expr *rhs) {
8087 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Narofff69936d2007-09-16 03:34:24 +00008088 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8089 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008090
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008091 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8092 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8093
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008094 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8095}
8096
John McCall60d7b3a2010-08-24 06:29:42 +00008097ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008098 BinaryOperatorKind Opc,
8099 Expr *lhs, Expr *rhs) {
John McCall01b2e4e2010-12-06 05:26:58 +00008100 if (getLangOptions().CPlusPlus) {
8101 bool UseBuiltinOperator;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008102
John McCall01b2e4e2010-12-06 05:26:58 +00008103 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8104 UseBuiltinOperator = false;
8105 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8106 UseBuiltinOperator = true;
8107 } else {
8108 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8109 !rhs->getType()->isOverloadableType();
8110 }
8111
8112 if (!UseBuiltinOperator) {
8113 // Find all of the overloaded operators visible from this
8114 // point. We perform both an operator-name lookup from the local
8115 // scope and an argument-dependent lookup based on the types of
8116 // the arguments.
8117 UnresolvedSet<16> Functions;
8118 OverloadedOperatorKind OverOp
8119 = BinaryOperator::getOverloadedOperator(Opc);
8120 if (S && OverOp != OO_None)
8121 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8122 Functions);
8123
8124 // Build the (potentially-overloaded, potentially-dependent)
8125 // binary operation.
8126 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8127 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008128 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008129
Douglas Gregoreaebc752008-11-06 23:29:22 +00008130 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008131 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00008132}
8133
John McCall60d7b3a2010-08-24 06:29:42 +00008134ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008135 UnaryOperatorKind Opc,
John McCall2cd11fe2010-10-12 02:09:17 +00008136 Expr *Input) {
John McCallf89e55a2010-11-18 06:31:45 +00008137 ExprValueKind VK = VK_RValue;
8138 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008139 QualType resultType;
8140 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008141 case UO_PreInc:
8142 case UO_PreDec:
8143 case UO_PostInc:
8144 case UO_PostDec:
John McCall09431682010-11-18 19:01:18 +00008145 resultType = CheckIncrementDecrementOperand(*this, Input, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008146 Opc == UO_PreInc ||
8147 Opc == UO_PostInc,
8148 Opc == UO_PreInc ||
8149 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008150 break;
John McCall2de56d12010-08-25 11:45:40 +00008151 case UO_AddrOf:
John McCall09431682010-11-18 19:01:18 +00008152 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008153 break;
John McCall2de56d12010-08-25 11:45:40 +00008154 case UO_Deref:
Douglas Gregora873dfc2010-02-03 00:27:59 +00008155 DefaultFunctionArrayLvalueConversion(Input);
John McCall09431682010-11-18 19:01:18 +00008156 resultType = CheckIndirectionOperand(*this, Input, VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008157 break;
John McCall2de56d12010-08-25 11:45:40 +00008158 case UO_Plus:
8159 case UO_Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00008160 UsualUnaryConversions(Input);
8161 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008162 if (resultType->isDependentType())
8163 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008164 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8165 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008166 break;
8167 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8168 resultType->isEnumeralType())
8169 break;
8170 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008171 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008172 resultType->isPointerType())
8173 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008174 else if (resultType->isPlaceholderType()) {
8175 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8176 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008177 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008178 }
Douglas Gregor74253732008-11-19 15:42:04 +00008179
Sebastian Redl0eb23302009-01-19 00:08:26 +00008180 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8181 << resultType << Input->getSourceRange());
John McCall2de56d12010-08-25 11:45:40 +00008182 case UO_Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00008183 UsualUnaryConversions(Input);
8184 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008185 if (resultType->isDependentType())
8186 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008187 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8188 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8189 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008190 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00008191 << resultType << Input->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008192 else if (resultType->hasIntegerRepresentation())
8193 break;
8194 else if (resultType->isPlaceholderType()) {
8195 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8196 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008197 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008198 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008199 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8200 << resultType << Input->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008201 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008202 break;
John McCall2de56d12010-08-25 11:45:40 +00008203 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008204 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregora873dfc2010-02-03 00:27:59 +00008205 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroffc80b4ee2007-07-16 21:54:35 +00008206 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008207 if (resultType->isDependentType())
8208 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008209 if (resultType->isScalarType()) { // C99 6.5.3.3p1
8210 // ok, fallthrough
8211 } else if (resultType->isPlaceholderType()) {
8212 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8213 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008214 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008215 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008216 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8217 << resultType << Input->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008218 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008219
Reid Spencer5f016e22007-07-11 17:01:13 +00008220 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008221 // In C++, it's bool. C++ 5.3.1p8
8222 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00008223 break;
John McCall2de56d12010-08-25 11:45:40 +00008224 case UO_Real:
8225 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008226 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCallf89e55a2010-11-18 06:31:45 +00008227 // _Real and _Imag map ordinary l-values into ordinary l-values.
8228 if (Input->getValueKind() != VK_RValue &&
8229 Input->getObjectKind() == OK_Ordinary)
8230 VK = Input->getValueKind();
Chris Lattnerdbb36972007-08-24 21:16:53 +00008231 break;
John McCall2de56d12010-08-25 11:45:40 +00008232 case UO_Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00008233 resultType = Input->getType();
John McCallf89e55a2010-11-18 06:31:45 +00008234 VK = Input->getValueKind();
8235 OK = Input->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008236 break;
8237 }
8238 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008239 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008240
John McCallf89e55a2010-11-18 06:31:45 +00008241 return Owned(new (Context) UnaryOperator(Input, Opc, resultType,
8242 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008243}
8244
John McCall60d7b3a2010-08-24 06:29:42 +00008245ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008246 UnaryOperatorKind Opc,
8247 Expr *Input) {
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00008248 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman957c0942010-09-05 23:15:52 +00008249 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008250 // Find all of the overloaded operators visible from this
8251 // point. We perform both an operator-name lookup from the local
8252 // scope and an argument-dependent lookup based on the types of
8253 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008254 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008255 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008256 if (S && OverOp != OO_None)
8257 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8258 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008259
John McCall9ae2f072010-08-23 23:25:46 +00008260 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008261 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008262
John McCall9ae2f072010-08-23 23:25:46 +00008263 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008264}
8265
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008266// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008267ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008268 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008269 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008270}
8271
Steve Naroff1b273c42007-09-16 14:56:35 +00008272/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
John McCall60d7b3a2010-08-24 06:29:42 +00008273ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008274 SourceLocation LabLoc,
8275 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00008276 // Look up the record for this label identifier.
John McCall781472f2010-08-25 08:40:02 +00008277 LabelStmt *&LabelDecl = getCurFunction()->LabelMap[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00008278
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00008279 // If we haven't seen this label yet, create a forward reference. It
8280 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00008281 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00008282 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008283
Argyrios Kyrtzidis355a9fe2010-09-19 21:21:25 +00008284 LabelDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008285 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00008286 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
8287 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008288}
8289
John McCall60d7b3a2010-08-24 06:29:42 +00008290ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008291Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008292 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008293 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8294 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8295
Douglas Gregordd8f5692010-03-10 04:54:39 +00008296 bool isFileScope
8297 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00008298 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00008299 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00008300
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008301 // FIXME: there are a variety of strange constraints to enforce here, for
8302 // example, it is not possible to goto into a stmt expression apparently.
8303 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008304
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008305 // If there are sub stmts in the compound stmt, take the type of the last one
8306 // as the type of the stmtexpr.
8307 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008308 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008309 if (!Compound->body_empty()) {
8310 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008311 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008312 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008313 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8314 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008315 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008316 }
8317 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00008318 // Do function/array conversion on the last expression, but not
8319 // lvalue-to-rvalue. However, initialize an unqualified type.
8320 DefaultFunctionArrayConversion(LastExpr);
8321 Ty = LastExpr->getType().getUnqualifiedType();
8322
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008323 if (!Ty->isDependentType() && !LastExpr->isTypeDependent()) {
8324 ExprResult Res = PerformCopyInitialization(
8325 InitializedEntity::InitializeResult(LPLoc,
8326 Ty,
8327 false),
8328 SourceLocation(),
8329 Owned(LastExpr));
8330 if (Res.isInvalid())
8331 return ExprError();
8332 if ((LastExpr = Res.takeAs<Expr>())) {
8333 if (!LastLabelStmt)
8334 Compound->setLastStmt(LastExpr);
8335 else
8336 LastLabelStmt->setSubStmt(LastExpr);
8337 StmtExprMayBindToTemp = true;
8338 }
8339 }
8340 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00008341 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008342
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008343 // FIXME: Check that expression type is complete/non-abstract; statement
8344 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008345 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8346 if (StmtExprMayBindToTemp)
8347 return MaybeBindToTemporary(ResStmtExpr);
8348 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008349}
Steve Naroffd34e9152007-08-01 22:05:33 +00008350
John McCall60d7b3a2010-08-24 06:29:42 +00008351ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008352 TypeSourceInfo *TInfo,
8353 OffsetOfComponent *CompPtr,
8354 unsigned NumComponents,
8355 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008356 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008357 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008358 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008359
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008360 // We must have at least one component that refers to the type, and the first
8361 // one is known to be a field designator. Verify that the ArgTy represents
8362 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00008363 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008364 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8365 << ArgTy << TypeRange);
8366
8367 // Type must be complete per C99 7.17p3 because a declaring a variable
8368 // with an incomplete type would be ill-formed.
8369 if (!Dependent
8370 && RequireCompleteType(BuiltinLoc, ArgTy,
8371 PDiag(diag::err_offsetof_incomplete_type)
8372 << TypeRange))
8373 return ExprError();
8374
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008375 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8376 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00008377 // FIXME: This diagnostic isn't actually visible because the location is in
8378 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008379 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008380 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8381 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008382
8383 bool DidWarnAboutNonPOD = false;
8384 QualType CurrentType = ArgTy;
8385 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8386 llvm::SmallVector<OffsetOfNode, 4> Comps;
8387 llvm::SmallVector<Expr*, 4> Exprs;
8388 for (unsigned i = 0; i != NumComponents; ++i) {
8389 const OffsetOfComponent &OC = CompPtr[i];
8390 if (OC.isBrackets) {
8391 // Offset of an array sub-field. TODO: Should we allow vector elements?
8392 if (!CurrentType->isDependentType()) {
8393 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8394 if(!AT)
8395 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8396 << CurrentType);
8397 CurrentType = AT->getElementType();
8398 } else
8399 CurrentType = Context.DependentTy;
8400
8401 // The expression must be an integral expression.
8402 // FIXME: An integral constant expression?
8403 Expr *Idx = static_cast<Expr*>(OC.U.E);
8404 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8405 !Idx->getType()->isIntegerType())
8406 return ExprError(Diag(Idx->getLocStart(),
8407 diag::err_typecheck_subscript_not_integer)
8408 << Idx->getSourceRange());
8409
8410 // Record this array index.
8411 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8412 Exprs.push_back(Idx);
8413 continue;
8414 }
8415
8416 // Offset of a field.
8417 if (CurrentType->isDependentType()) {
8418 // We have the offset of a field, but we can't look into the dependent
8419 // type. Just record the identifier of the field.
8420 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8421 CurrentType = Context.DependentTy;
8422 continue;
8423 }
8424
8425 // We need to have a complete type to look into.
8426 if (RequireCompleteType(OC.LocStart, CurrentType,
8427 diag::err_offsetof_incomplete_type))
8428 return ExprError();
8429
8430 // Look for the designated field.
8431 const RecordType *RC = CurrentType->getAs<RecordType>();
8432 if (!RC)
8433 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8434 << CurrentType);
8435 RecordDecl *RD = RC->getDecl();
8436
8437 // C++ [lib.support.types]p5:
8438 // The macro offsetof accepts a restricted set of type arguments in this
8439 // International Standard. type shall be a POD structure or a POD union
8440 // (clause 9).
8441 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8442 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
8443 DiagRuntimeBehavior(BuiltinLoc,
8444 PDiag(diag::warn_offsetof_non_pod_type)
8445 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8446 << CurrentType))
8447 DidWarnAboutNonPOD = true;
8448 }
8449
8450 // Look for the field.
8451 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8452 LookupQualifiedName(R, RD);
8453 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00008454 IndirectFieldDecl *IndirectMemberDecl = 0;
8455 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00008456 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00008457 MemberDecl = IndirectMemberDecl->getAnonField();
8458 }
8459
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008460 if (!MemberDecl)
8461 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8462 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8463 OC.LocEnd));
8464
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00008465 // C99 7.17p3:
8466 // (If the specified member is a bit-field, the behavior is undefined.)
8467 //
8468 // We diagnose this as an error.
8469 if (MemberDecl->getBitWidth()) {
8470 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8471 << MemberDecl->getDeclName()
8472 << SourceRange(BuiltinLoc, RParenLoc);
8473 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8474 return ExprError();
8475 }
Eli Friedman19410a72010-08-05 10:11:36 +00008476
8477 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00008478 if (IndirectMemberDecl)
8479 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00008480
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008481 // If the member was found in a base class, introduce OffsetOfNodes for
8482 // the base class indirections.
8483 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8484 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00008485 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008486 CXXBasePath &Path = Paths.front();
8487 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8488 B != BEnd; ++B)
8489 Comps.push_back(OffsetOfNode(B->Base));
8490 }
Eli Friedman19410a72010-08-05 10:11:36 +00008491
Francois Pichet87c2e122010-11-21 06:08:52 +00008492 if (IndirectMemberDecl) {
8493 for (IndirectFieldDecl::chain_iterator FI =
8494 IndirectMemberDecl->chain_begin(),
8495 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8496 assert(isa<FieldDecl>(*FI));
8497 Comps.push_back(OffsetOfNode(OC.LocStart,
8498 cast<FieldDecl>(*FI), OC.LocEnd));
8499 }
8500 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008501 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00008502
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008503 CurrentType = MemberDecl->getType().getNonReferenceType();
8504 }
8505
8506 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8507 TInfo, Comps.data(), Comps.size(),
8508 Exprs.data(), Exprs.size(), RParenLoc));
8509}
Mike Stumpeed9cac2009-02-19 03:04:26 +00008510
John McCall60d7b3a2010-08-24 06:29:42 +00008511ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00008512 SourceLocation BuiltinLoc,
8513 SourceLocation TypeLoc,
8514 ParsedType argty,
8515 OffsetOfComponent *CompPtr,
8516 unsigned NumComponents,
8517 SourceLocation RPLoc) {
8518
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008519 TypeSourceInfo *ArgTInfo;
8520 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8521 if (ArgTy.isNull())
8522 return ExprError();
8523
Eli Friedman5a15dc12010-08-05 10:15:45 +00008524 if (!ArgTInfo)
8525 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8526
8527 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8528 RPLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008529}
8530
8531
John McCall60d7b3a2010-08-24 06:29:42 +00008532ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008533 Expr *CondExpr,
8534 Expr *LHSExpr, Expr *RHSExpr,
8535 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00008536 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8537
John McCallf89e55a2010-11-18 06:31:45 +00008538 ExprValueKind VK = VK_RValue;
8539 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00008540 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00008541 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00008542 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00008543 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00008544 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00008545 } else {
8546 // The conditional expression is required to be a constant expression.
8547 llvm::APSInt condEval(32);
8548 SourceLocation ExpLoc;
8549 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00008550 return ExprError(Diag(ExpLoc,
8551 diag::err_typecheck_choose_expr_requires_constant)
8552 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00008553
Sebastian Redl28507842009-02-26 14:39:58 +00008554 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00008555 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8556
8557 resType = ActiveExpr->getType();
8558 ValueDependent = ActiveExpr->isValueDependent();
8559 VK = ActiveExpr->getValueKind();
8560 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00008561 }
8562
Sebastian Redlf53597f2009-03-15 17:47:39 +00008563 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00008564 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00008565 resType->isDependentType(),
8566 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00008567}
8568
Steve Naroff4eb206b2008-09-03 18:15:37 +00008569//===----------------------------------------------------------------------===//
8570// Clang Extensions.
8571//===----------------------------------------------------------------------===//
8572
8573/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00008574void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008575 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8576 PushBlockScope(BlockScope, Block);
8577 CurContext->addDecl(Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008578 if (BlockScope)
8579 PushDeclContext(BlockScope, Block);
8580 else
8581 CurContext = Block;
Steve Naroff090276f2008-10-10 01:28:17 +00008582}
8583
Mike Stump98eb8a72009-02-04 22:31:32 +00008584void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00008585 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00008586 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008587 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008588
John McCallbf1a0282010-06-04 23:28:52 +00008589 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00008590 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00008591
John McCall711c52b2011-01-05 12:14:39 +00008592 // GetTypeForDeclarator always produces a function type for a block
8593 // literal signature. Furthermore, it is always a FunctionProtoType
8594 // unless the function was written with a typedef.
8595 assert(T->isFunctionType() &&
8596 "GetTypeForDeclarator made a non-function block signature");
8597
8598 // Look for an explicit signature in that function type.
8599 FunctionProtoTypeLoc ExplicitSignature;
8600
8601 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8602 if (isa<FunctionProtoTypeLoc>(tmp)) {
8603 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8604
8605 // Check whether that explicit signature was synthesized by
8606 // GetTypeForDeclarator. If so, don't save that as part of the
8607 // written signature.
8608 if (ExplicitSignature.getLParenLoc() ==
8609 ExplicitSignature.getRParenLoc()) {
8610 // This would be much cheaper if we stored TypeLocs instead of
8611 // TypeSourceInfos.
8612 TypeLoc Result = ExplicitSignature.getResultLoc();
8613 unsigned Size = Result.getFullDataSize();
8614 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8615 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8616
8617 ExplicitSignature = FunctionProtoTypeLoc();
8618 }
John McCall82dc0092010-06-04 11:21:44 +00008619 }
Mike Stump1eb44332009-09-09 15:08:12 +00008620
John McCall711c52b2011-01-05 12:14:39 +00008621 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8622 CurBlock->FunctionType = T;
8623
8624 const FunctionType *Fn = T->getAs<FunctionType>();
8625 QualType RetTy = Fn->getResultType();
8626 bool isVariadic =
8627 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8628
John McCallc71a4912010-06-04 19:02:56 +00008629 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00008630
John McCall82dc0092010-06-04 11:21:44 +00008631 // Don't allow returning a objc interface by value.
8632 if (RetTy->isObjCObjectType()) {
8633 Diag(ParamInfo.getSourceRange().getBegin(),
8634 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8635 return;
8636 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008637
John McCall82dc0092010-06-04 11:21:44 +00008638 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00008639 // return type. TODO: what should we do with declarators like:
8640 // ^ * { ... }
8641 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00008642 if (RetTy != Context.DependentTy)
8643 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008644
John McCall82dc0092010-06-04 11:21:44 +00008645 // Push block parameters from the declarator if we had them.
John McCallc71a4912010-06-04 19:02:56 +00008646 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00008647 if (ExplicitSignature) {
8648 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8649 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008650 if (Param->getIdentifier() == 0 &&
8651 !Param->isImplicit() &&
8652 !Param->isInvalidDecl() &&
8653 !getLangOptions().CPlusPlus)
8654 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00008655 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008656 }
John McCall82dc0092010-06-04 11:21:44 +00008657
8658 // Fake up parameter variables if we have a typedef, like
8659 // ^ fntype { ... }
8660 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8661 for (FunctionProtoType::arg_type_iterator
8662 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8663 ParmVarDecl *Param =
8664 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8665 ParamInfo.getSourceRange().getBegin(),
8666 *I);
John McCallc71a4912010-06-04 19:02:56 +00008667 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00008668 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008669 }
John McCall82dc0092010-06-04 11:21:44 +00008670
John McCallc71a4912010-06-04 19:02:56 +00008671 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00008672 if (!Params.empty()) {
John McCallc71a4912010-06-04 19:02:56 +00008673 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregor82aa7132010-11-01 18:37:59 +00008674 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8675 CurBlock->TheDecl->param_end(),
8676 /*CheckParameterNames=*/false);
8677 }
8678
John McCall82dc0092010-06-04 11:21:44 +00008679 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00008680 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00008681
John McCallc71a4912010-06-04 19:02:56 +00008682 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00008683 Diag(ParamInfo.getAttributes()->getLoc(),
8684 diag::warn_attribute_sentinel_not_variadic) << 1;
8685 // FIXME: remove the attribute.
8686 }
8687
8688 // Put the parameter variables in scope. We can bail out immediately
8689 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00008690 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00008691 return;
8692
Steve Naroff090276f2008-10-10 01:28:17 +00008693 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00008694 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8695 (*AI)->setOwningFunction(CurBlock->TheDecl);
8696
Steve Naroff090276f2008-10-10 01:28:17 +00008697 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00008698 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00008699 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00008700
Steve Naroff090276f2008-10-10 01:28:17 +00008701 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00008702 }
John McCall7a9813c2010-01-22 00:28:27 +00008703 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008704}
8705
8706/// ActOnBlockError - If there is an error parsing a block, this callback
8707/// is invoked to pop the information about the block from the action impl.
8708void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00008709 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00008710 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008711 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008712}
8713
8714/// ActOnBlockStmtExpr - This is called when the body of a block statement
8715/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00008716ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
John McCall9ae2f072010-08-23 23:25:46 +00008717 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00008718 // If blocks are disabled, emit an error.
8719 if (!LangOpts.Blocks)
8720 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00008721
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008722 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008723
Steve Naroff090276f2008-10-10 01:28:17 +00008724 PopDeclContext();
8725
Steve Naroff4eb206b2008-09-03 18:15:37 +00008726 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00008727 if (!BSI->ReturnType.isNull())
8728 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008729
Mike Stump56925862009-07-28 22:04:01 +00008730 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008731 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00008732
John McCall469a1eb2011-02-02 13:00:07 +00008733 // Set the captured variables on the block.
John McCall6b5a61b2011-02-07 10:33:21 +00008734 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8735 BSI->CapturesCXXThis);
John McCall469a1eb2011-02-02 13:00:07 +00008736
John McCallc71a4912010-06-04 19:02:56 +00008737 // If the user wrote a function type in some form, try to use that.
8738 if (!BSI->FunctionType.isNull()) {
8739 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8740
8741 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8742 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8743
8744 // Turn protoless block types into nullary block types.
8745 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00008746 FunctionProtoType::ExtProtoInfo EPI;
8747 EPI.ExtInfo = Ext;
8748 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008749
8750 // Otherwise, if we don't need to change anything about the function type,
8751 // preserve its sugar structure.
8752 } else if (FTy->getResultType() == RetTy &&
8753 (!NoReturn || FTy->getNoReturnAttr())) {
8754 BlockTy = BSI->FunctionType;
8755
8756 // Otherwise, make the minimal modifications to the function type.
8757 } else {
8758 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00008759 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8760 EPI.TypeQuals = 0; // FIXME: silently?
8761 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00008762 BlockTy = Context.getFunctionType(RetTy,
8763 FPT->arg_type_begin(),
8764 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00008765 EPI);
John McCallc71a4912010-06-04 19:02:56 +00008766 }
8767
8768 // If we don't have a function type, just build one from nothing.
8769 } else {
John McCalle23cf432010-12-14 08:05:40 +00008770 FunctionProtoType::ExtProtoInfo EPI;
8771 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, 0, CC_Default);
8772 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008773 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008774
John McCallc71a4912010-06-04 19:02:56 +00008775 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8776 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00008777 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008778
Chris Lattner17a78302009-04-19 05:28:12 +00008779 // If needed, diagnose invalid gotos and switches in the block.
John McCall781472f2010-08-25 08:40:02 +00008780 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00008781 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00008782
John McCall9ae2f072010-08-23 23:25:46 +00008783 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Mike Stumpa3899eb2010-01-19 23:08:01 +00008784
8785 bool Good = true;
8786 // Check goto/label use.
8787 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
8788 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
8789 LabelStmt *L = I->second;
8790
8791 // Verify that we have no forward references left. If so, there was a goto
8792 // or address of a label taken, but no definition of it.
Argyrios Kyrtzidis355a9fe2010-09-19 21:21:25 +00008793 if (L->getSubStmt() != 0) {
8794 if (!L->isUsed())
8795 Diag(L->getIdentLoc(), diag::warn_unused_label) << L->getName();
Mike Stumpa3899eb2010-01-19 23:08:01 +00008796 continue;
Argyrios Kyrtzidis355a9fe2010-09-19 21:21:25 +00008797 }
Mike Stumpa3899eb2010-01-19 23:08:01 +00008798
8799 // Emit error.
8800 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
8801 Good = false;
8802 }
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008803 if (!Good) {
8804 PopFunctionOrBlockScope();
Mike Stumpa3899eb2010-01-19 23:08:01 +00008805 return ExprError();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008806 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008807
John McCall469a1eb2011-02-02 13:00:07 +00008808 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCalle0054f62010-08-25 05:56:39 +00008809
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00008810 // Issue any analysis-based warnings.
Ted Kremenekd064fdc2010-03-23 00:13:23 +00008811 const sema::AnalysisBasedWarnings::Policy &WP =
8812 AnalysisWarnings.getDefaultPolicy();
John McCalle0054f62010-08-25 05:56:39 +00008813 AnalysisWarnings.IssueWarnings(WP, Result);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00008814
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008815 PopFunctionOrBlockScope();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008816 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00008817}
8818
John McCall60d7b3a2010-08-24 06:29:42 +00008819ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallb3d87482010-08-24 05:47:05 +00008820 Expr *expr, ParsedType type,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008821 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008822 TypeSourceInfo *TInfo;
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008823 GetTypeFromParser(type, &TInfo);
John McCall9ae2f072010-08-23 23:25:46 +00008824 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008825}
8826
John McCall60d7b3a2010-08-24 06:29:42 +00008827ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00008828 Expr *E, TypeSourceInfo *TInfo,
8829 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008830 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00008831
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008832 // Get the va_list type
8833 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008834 if (VaListType->isArrayType()) {
8835 // Deal with implicit array decay; for example, on x86-64,
8836 // va_list is an array, but it's supposed to decay to
8837 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008838 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00008839 // Make sure the input expression also decays appropriately.
8840 UsualUnaryConversions(E);
8841 } else {
8842 // Otherwise, the va_list argument must be an l-value because
8843 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00008844 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00008845 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00008846 return ExprError();
8847 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008848
Douglas Gregordd027302009-05-19 23:10:31 +00008849 if (!E->isTypeDependent() &&
8850 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00008851 return ExprError(Diag(E->getLocStart(),
8852 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008853 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00008854 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008855
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008856 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00008857 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008858
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008859 QualType T = TInfo->getType().getNonLValueExprType(Context);
8860 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00008861}
8862
John McCall60d7b3a2010-08-24 06:29:42 +00008863ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008864 // The type of __null will be int or long, depending on the size of
8865 // pointers on the target.
8866 QualType Ty;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008867 unsigned pw = Context.Target.getPointerWidth(0);
8868 if (pw == Context.Target.getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008869 Ty = Context.IntTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008870 else if (pw == Context.Target.getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008871 Ty = Context.LongTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008872 else if (pw == Context.Target.getLongLongWidth())
8873 Ty = Context.LongLongTy;
8874 else {
8875 assert(!"I don't know size of pointer!");
8876 Ty = Context.IntTy;
8877 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008878
Sebastian Redlf53597f2009-03-15 17:47:39 +00008879 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008880}
8881
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008882static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00008883 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008884 if (!SemaRef.getLangOptions().ObjC1)
8885 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008886
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008887 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8888 if (!PT)
8889 return;
8890
8891 // Check if the destination is of type 'id'.
8892 if (!PT->isObjCIdType()) {
8893 // Check if the destination is the 'NSString' interface.
8894 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8895 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8896 return;
8897 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008898
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008899 // Strip off any parens and casts.
8900 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
8901 if (!SL || SL->isWide())
8902 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008903
Douglas Gregor849b2432010-03-31 17:46:05 +00008904 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008905}
8906
Chris Lattner5cf216b2008-01-04 18:04:52 +00008907bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8908 SourceLocation Loc,
8909 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00008910 Expr *SrcExpr, AssignmentAction Action,
8911 bool *Complained) {
8912 if (Complained)
8913 *Complained = false;
8914
Chris Lattner5cf216b2008-01-04 18:04:52 +00008915 // Decode the result (notice that AST's are still created for extensions).
8916 bool isInvalid = false;
8917 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00008918 FixItHint Hint;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008919
Chris Lattner5cf216b2008-01-04 18:04:52 +00008920 switch (ConvTy) {
8921 default: assert(0 && "Unknown conversion type");
8922 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008923 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00008924 DiagKind = diag::ext_typecheck_convert_pointer_int;
8925 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008926 case IntToPointer:
8927 DiagKind = diag::ext_typecheck_convert_int_pointer;
8928 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008929 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00008930 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00008931 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
8932 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00008933 case IncompatiblePointerSign:
8934 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8935 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008936 case FunctionVoidPointer:
8937 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8938 break;
John McCall86c05f32011-02-01 00:10:29 +00008939 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00008940 // Perform array-to-pointer decay if necessary.
8941 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8942
John McCall86c05f32011-02-01 00:10:29 +00008943 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8944 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8945 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8946 DiagKind = diag::err_typecheck_incompatible_address_space;
8947 break;
8948 }
8949
8950 llvm_unreachable("unknown error case for discarding qualifiers!");
8951 // fallthrough
8952 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00008953 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00008954 // If the qualifiers lost were because we were applying the
8955 // (deprecated) C++ conversion from a string literal to a char*
8956 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8957 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00008958 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00008959 // bit of refactoring (so that the second argument is an
8960 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00008961 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00008962 // C++ semantics.
8963 if (getLangOptions().CPlusPlus &&
8964 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8965 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008966 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8967 break;
Sean Huntc9132b62009-11-08 07:46:34 +00008968 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00008969 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00008970 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00008971 case IntToBlockPointer:
8972 DiagKind = diag::err_int_to_block_pointer;
8973 break;
8974 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00008975 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00008976 break;
Steve Naroff39579072008-10-14 22:18:38 +00008977 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00008978 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00008979 // it can give a more specific diagnostic.
8980 DiagKind = diag::warn_incompatible_qualified_id;
8981 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00008982 case IncompatibleVectors:
8983 DiagKind = diag::warn_incompatible_vectors;
8984 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008985 case Incompatible:
8986 DiagKind = diag::err_typecheck_convert_incompatible;
8987 isInvalid = true;
8988 break;
8989 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008990
Douglas Gregord4eea832010-04-09 00:35:39 +00008991 QualType FirstType, SecondType;
8992 switch (Action) {
8993 case AA_Assigning:
8994 case AA_Initializing:
8995 // The destination type comes first.
8996 FirstType = DstType;
8997 SecondType = SrcType;
8998 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008999
Douglas Gregord4eea832010-04-09 00:35:39 +00009000 case AA_Returning:
9001 case AA_Passing:
9002 case AA_Converting:
9003 case AA_Sending:
9004 case AA_Casting:
9005 // The source type comes first.
9006 FirstType = SrcType;
9007 SecondType = DstType;
9008 break;
9009 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009010
Douglas Gregord4eea832010-04-09 00:35:39 +00009011 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009012 << SrcExpr->getSourceRange() << Hint;
Douglas Gregora41a8c52010-04-22 00:20:18 +00009013 if (Complained)
9014 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009015 return isInvalid;
9016}
Anders Carlssone21555e2008-11-30 19:50:32 +00009017
Chris Lattner3bf68932009-04-25 21:59:05 +00009018bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009019 llvm::APSInt ICEResult;
9020 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9021 if (Result)
9022 *Result = ICEResult;
9023 return false;
9024 }
9025
Anders Carlssone21555e2008-11-30 19:50:32 +00009026 Expr::EvalResult EvalResult;
9027
Mike Stumpeed9cac2009-02-19 03:04:26 +00009028 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00009029 EvalResult.HasSideEffects) {
9030 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9031
9032 if (EvalResult.Diag) {
9033 // We only show the note if it's not the usual "invalid subexpression"
9034 // or if it's actually in a subexpression.
9035 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9036 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9037 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9038 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009039
Anders Carlssone21555e2008-11-30 19:50:32 +00009040 return true;
9041 }
9042
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009043 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9044 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00009045
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009046 if (EvalResult.Diag &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009047 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9048 != Diagnostic::Ignored)
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009049 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009050
Anders Carlssone21555e2008-11-30 19:50:32 +00009051 if (Result)
9052 *Result = EvalResult.Val.getInt();
9053 return false;
9054}
Douglas Gregore0762c92009-06-19 23:52:42 +00009055
Douglas Gregor2afce722009-11-26 00:44:06 +00009056void
Mike Stump1eb44332009-09-09 15:08:12 +00009057Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009058 ExprEvalContexts.push_back(
9059 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00009060}
9061
Mike Stump1eb44332009-09-09 15:08:12 +00009062void
Douglas Gregor2afce722009-11-26 00:44:06 +00009063Sema::PopExpressionEvaluationContext() {
9064 // Pop the current expression evaluation context off the stack.
9065 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9066 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009067
Douglas Gregor06d33692009-12-12 07:57:52 +00009068 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9069 if (Rec.PotentiallyReferenced) {
9070 // Mark any remaining declarations in the current position of the stack
9071 // as "referenced". If they were not meant to be referenced, semantic
9072 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009073 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00009074 I = Rec.PotentiallyReferenced->begin(),
9075 IEnd = Rec.PotentiallyReferenced->end();
9076 I != IEnd; ++I)
9077 MarkDeclarationReferenced(I->first, I->second);
9078 }
9079
9080 if (Rec.PotentiallyDiagnosed) {
9081 // Emit any pending diagnostics.
9082 for (PotentiallyEmittedDiagnostics::iterator
9083 I = Rec.PotentiallyDiagnosed->begin(),
9084 IEnd = Rec.PotentiallyDiagnosed->end();
9085 I != IEnd; ++I)
9086 Diag(I->first, I->second);
9087 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009088 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009089
9090 // When are coming out of an unevaluated context, clear out any
9091 // temporaries that we may have created as part of the evaluation of
9092 // the expression in that context: they aren't relevant because they
9093 // will never be constructed.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009094 if (Rec.Context == Unevaluated &&
Douglas Gregor2afce722009-11-26 00:44:06 +00009095 ExprTemporaries.size() > Rec.NumTemporaries)
9096 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9097 ExprTemporaries.end());
9098
9099 // Destroy the popped expression evaluation record.
9100 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009101}
Douglas Gregore0762c92009-06-19 23:52:42 +00009102
9103/// \brief Note that the given declaration was referenced in the source code.
9104///
9105/// This routine should be invoke whenever a given declaration is referenced
9106/// in the source code, and where that reference occurred. If this declaration
9107/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9108/// C99 6.9p3), then the declaration will be marked as used.
9109///
9110/// \param Loc the location where the declaration was referenced.
9111///
9112/// \param D the declaration that has been referenced by the source code.
9113void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9114 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00009115
Douglas Gregorc070cc62010-06-17 23:14:26 +00009116 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009117 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009118
Douglas Gregorb5352cf2009-10-08 21:35:42 +00009119 // Mark a parameter or variable declaration "used", regardless of whether we're in a
9120 // template or not. The reason for this is that unevaluated expressions
9121 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9122 // -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009123 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009124 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson2127ecc2010-10-22 23:37:08 +00009125 D->setUsed();
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009126 return;
9127 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009128
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009129 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9130 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009131
Douglas Gregore0762c92009-06-19 23:52:42 +00009132 // Do not mark anything as "used" within a dependent context; wait for
9133 // an instantiation.
9134 if (CurContext->isDependentContext())
9135 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009136
Douglas Gregor2afce722009-11-26 00:44:06 +00009137 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00009138 case Unevaluated:
9139 // We are in an expression that is not potentially evaluated; do nothing.
9140 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009141
Douglas Gregorac7610d2009-06-22 20:57:11 +00009142 case PotentiallyEvaluated:
9143 // We are in a potentially-evaluated expression, so this declaration is
9144 // "used"; handle this below.
9145 break;
Mike Stump1eb44332009-09-09 15:08:12 +00009146
Douglas Gregorac7610d2009-06-22 20:57:11 +00009147 case PotentiallyPotentiallyEvaluated:
9148 // We are in an expression that may be potentially evaluated; queue this
9149 // declaration reference until we know whether the expression is
9150 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00009151 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00009152 return;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009153
9154 case PotentiallyEvaluatedIfUsed:
9155 // Referenced declarations will only be used if the construct in the
9156 // containing expression is used.
9157 return;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009158 }
Mike Stump1eb44332009-09-09 15:08:12 +00009159
Douglas Gregore0762c92009-06-19 23:52:42 +00009160 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00009161 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009162 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00009163 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00009164 if (Constructor->getParent()->hasTrivialConstructor())
9165 return;
9166 if (!Constructor->isUsed(false))
9167 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00009168 } else if (Constructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00009169 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009170 if (!Constructor->isUsed(false))
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009171 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
9172 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009173
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009174 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009175 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009176 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009177 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009178 if (Destructor->isVirtual())
9179 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009180 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9181 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
9182 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009183 if (!MethodDecl->isUsed(false))
Douglas Gregor39957dc2010-05-01 15:04:51 +00009184 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009185 } else if (MethodDecl->isVirtual())
9186 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009187 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00009188 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00009189 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00009190 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00009191 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009192 bool AlreadyInstantiated = false;
9193 if (FunctionTemplateSpecializationInfo *SpecInfo
9194 = Function->getTemplateSpecializationInfo()) {
9195 if (SpecInfo->getPointOfInstantiation().isInvalid())
9196 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009197 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009198 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009199 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009200 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009201 = Function->getMemberSpecializationInfo()) {
9202 if (MSInfo->getPointOfInstantiation().isInvalid())
9203 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009204 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009205 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009206 AlreadyInstantiated = true;
9207 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009208
Douglas Gregor60406be2010-01-16 22:29:39 +00009209 if (!AlreadyInstantiated) {
9210 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9211 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9212 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9213 Loc));
9214 else
Chandler Carruth62c78d52010-08-25 08:44:16 +00009215 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor60406be2010-01-16 22:29:39 +00009216 }
Gabor Greif40181c42010-08-28 00:16:06 +00009217 } else // Walk redefinitions, as some of them may be instantiable.
9218 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9219 e(Function->redecls_end()); i != e; ++i) {
Gabor Greifbe9ebe32010-08-28 01:58:12 +00009220 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greif40181c42010-08-28 00:16:06 +00009221 MarkDeclarationReferenced(Loc, *i);
9222 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009223
Douglas Gregore0762c92009-06-19 23:52:42 +00009224 // FIXME: keep track of references to static functions
Argyrios Kyrtzidis58b52592010-08-25 10:34:54 +00009225
9226 // Recursive functions should be marked when used from another function.
9227 if (CurContext != Function)
9228 Function->setUsed(true);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009229
Douglas Gregore0762c92009-06-19 23:52:42 +00009230 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009231 }
Mike Stump1eb44332009-09-09 15:08:12 +00009232
Douglas Gregore0762c92009-06-19 23:52:42 +00009233 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00009234 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00009235 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009236 Var->getInstantiatedFromStaticDataMember()) {
9237 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9238 assert(MSInfo && "Missing member specialization information?");
9239 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9240 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9241 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth62c78d52010-08-25 08:44:16 +00009242 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009243 }
9244 }
Mike Stump1eb44332009-09-09 15:08:12 +00009245
Douglas Gregore0762c92009-06-19 23:52:42 +00009246 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00009247
Douglas Gregore0762c92009-06-19 23:52:42 +00009248 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00009249 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00009250 }
Douglas Gregore0762c92009-06-19 23:52:42 +00009251}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009252
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009253namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009254 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009255 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009256 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009257 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9258 Sema &S;
9259 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009260
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009261 public:
9262 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009263
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009264 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009265
9266 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9267 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009268 };
9269}
9270
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009271bool MarkReferencedDecls::TraverseTemplateArgument(
9272 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009273 if (Arg.getKind() == TemplateArgument::Declaration) {
9274 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9275 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009276
9277 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009278}
9279
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009280bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009281 if (ClassTemplateSpecializationDecl *Spec
9282 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9283 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +00009284 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009285 }
9286
Chandler Carruthe3e210c2010-06-10 10:31:57 +00009287 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009288}
9289
9290void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9291 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009292 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009293}
9294
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009295namespace {
9296 /// \brief Helper class that marks all of the declarations referenced by
9297 /// potentially-evaluated subexpressions as "referenced".
9298 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9299 Sema &S;
9300
9301 public:
9302 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9303
9304 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9305
9306 void VisitDeclRefExpr(DeclRefExpr *E) {
9307 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9308 }
9309
9310 void VisitMemberExpr(MemberExpr *E) {
9311 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009312 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009313 }
9314
9315 void VisitCXXNewExpr(CXXNewExpr *E) {
9316 if (E->getConstructor())
9317 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9318 if (E->getOperatorNew())
9319 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9320 if (E->getOperatorDelete())
9321 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009322 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009323 }
9324
9325 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9326 if (E->getOperatorDelete())
9327 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +00009328 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9329 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9330 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9331 S.MarkDeclarationReferenced(E->getLocStart(),
9332 S.LookupDestructor(Record));
9333 }
9334
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009335 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009336 }
9337
9338 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9339 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009340 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009341 }
9342
9343 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9344 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9345 }
Douglas Gregor102ff972010-10-19 17:17:35 +00009346
9347 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9348 Visit(E->getExpr());
9349 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009350 };
9351}
9352
9353/// \brief Mark any declarations that appear within this expression or any
9354/// potentially-evaluated subexpressions as "referenced".
9355void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9356 EvaluatedExprMarker(*this).Visit(E);
9357}
9358
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009359/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9360/// of the program being compiled.
9361///
9362/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009363/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009364/// possibility that the code will actually be executable. Code in sizeof()
9365/// expressions, code used only during overload resolution, etc., are not
9366/// potentially evaluated. This routine will suppress such diagnostics or,
9367/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009368/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009369/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009370///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009371/// This routine should be used for all diagnostics that describe the run-time
9372/// behavior of a program, such as passing a non-POD value through an ellipsis.
9373/// Failure to do so will likely result in spurious diagnostics or failures
9374/// during overload resolution or within sizeof/alignof/typeof/typeid.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009375bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009376 const PartialDiagnostic &PD) {
9377 switch (ExprEvalContexts.back().Context ) {
9378 case Unevaluated:
9379 // The argument will never be evaluated, so don't complain.
9380 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009381
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009382 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009383 case PotentiallyEvaluatedIfUsed:
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009384 Diag(Loc, PD);
9385 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009386
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009387 case PotentiallyPotentiallyEvaluated:
9388 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9389 break;
9390 }
9391
9392 return false;
9393}
9394
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009395bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9396 CallExpr *CE, FunctionDecl *FD) {
9397 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9398 return false;
9399
9400 PartialDiagnostic Note =
9401 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9402 << FD->getDeclName() : PDiag();
9403 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009404
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009405 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009406 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009407 PDiag(diag::err_call_function_incomplete_return)
9408 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009409 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009410 << CE->getSourceRange(),
9411 std::make_pair(NoteLoc, Note)))
9412 return true;
9413
9414 return false;
9415}
9416
Douglas Gregor92c3a042011-01-19 16:50:08 +00009417// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +00009418// will prevent this condition from triggering, which is what we want.
9419void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9420 SourceLocation Loc;
9421
John McCalla52ef082009-11-11 02:41:58 +00009422 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +00009423 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +00009424
John McCall5a881bb2009-10-12 21:59:07 +00009425 if (isa<BinaryOperator>(E)) {
9426 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +00009427 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +00009428 return;
9429
Douglas Gregor92c3a042011-01-19 16:50:08 +00009430 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9431
John McCallc8d8ac52009-11-12 00:06:05 +00009432 // Greylist some idioms by putting them into a warning subcategory.
9433 if (ObjCMessageExpr *ME
9434 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9435 Selector Sel = ME->getSelector();
9436
John McCallc8d8ac52009-11-12 00:06:05 +00009437 // self = [<foo> init...]
9438 if (isSelfExpr(Op->getLHS())
9439 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
9440 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9441
9442 // <foo> = [<bar> nextObject]
9443 else if (Sel.isUnarySelector() &&
9444 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
9445 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9446 }
John McCalla52ef082009-11-11 02:41:58 +00009447
John McCall5a881bb2009-10-12 21:59:07 +00009448 Loc = Op->getOperatorLoc();
9449 } else if (isa<CXXOperatorCallExpr>(E)) {
9450 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +00009451 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +00009452 return;
9453
Douglas Gregor92c3a042011-01-19 16:50:08 +00009454 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +00009455 Loc = Op->getOperatorLoc();
9456 } else {
9457 // Not an assignment.
9458 return;
9459 }
9460
John McCall5a881bb2009-10-12 21:59:07 +00009461 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00009462 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009463
Douglas Gregor55b38842010-04-14 16:09:52 +00009464 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +00009465
9466 if (IsOrAssign)
9467 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9468 << FixItHint::CreateReplacement(Loc, "!=");
9469 else
9470 Diag(Loc, diag::note_condition_assign_to_comparison)
9471 << FixItHint::CreateReplacement(Loc, "==");
9472
Douglas Gregor55b38842010-04-14 16:09:52 +00009473 Diag(Loc, diag::note_condition_assign_silence)
9474 << FixItHint::CreateInsertion(Open, "(")
9475 << FixItHint::CreateInsertion(Close, ")");
John McCall5a881bb2009-10-12 21:59:07 +00009476}
9477
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009478/// \brief Redundant parentheses over an equality comparison can indicate
9479/// that the user intended an assignment used as condition.
9480void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009481 // Don't warn if the parens came from a macro.
9482 SourceLocation parenLoc = parenE->getLocStart();
9483 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9484 return;
9485
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009486 Expr *E = parenE->IgnoreParens();
9487
9488 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +00009489 if (opE->getOpcode() == BO_EQ &&
9490 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9491 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009492 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +00009493
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009494 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
9495 Diag(Loc, diag::note_equality_comparison_to_assign)
9496 << FixItHint::CreateReplacement(Loc, "=");
9497 Diag(Loc, diag::note_equality_comparison_silence)
9498 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9499 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009500 }
9501}
9502
John McCall5a881bb2009-10-12 21:59:07 +00009503bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
9504 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009505 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9506 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +00009507
9508 if (!E->isTypeDependent()) {
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00009509 if (E->isBoundMemberFunction(Context))
9510 return Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9511 << E->getSourceRange();
9512
John McCallf6a16482010-12-04 03:47:34 +00009513 if (getLangOptions().CPlusPlus)
9514 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9515
9516 DefaultFunctionArrayLvalueConversion(E);
John McCallabc56c72010-12-04 06:09:13 +00009517
9518 QualType T = E->getType();
John McCallf6a16482010-12-04 03:47:34 +00009519 if (!T->isScalarType()) // C99 6.8.4.1p1
9520 return Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9521 << T << E->getSourceRange();
John McCall5a881bb2009-10-12 21:59:07 +00009522 }
9523
9524 return false;
9525}
Douglas Gregor586596f2010-05-06 17:25:47 +00009526
John McCall60d7b3a2010-08-24 06:29:42 +00009527ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9528 Expr *Sub) {
Douglas Gregoreecf38f2010-05-06 21:39:56 +00009529 if (!Sub)
Douglas Gregor586596f2010-05-06 17:25:47 +00009530 return ExprError();
9531
Douglas Gregorff331c12010-07-25 18:17:45 +00009532 if (CheckBooleanCondition(Sub, Loc))
Douglas Gregor586596f2010-05-06 17:25:47 +00009533 return ExprError();
Douglas Gregor586596f2010-05-06 17:25:47 +00009534
9535 return Owned(Sub);
9536}
John McCall2a984ca2010-10-12 00:20:44 +00009537
9538/// Check for operands with placeholder types and complain if found.
9539/// Returns true if there was an error and no recovery was possible.
9540ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) {
9541 const BuiltinType *BT = E->getType()->getAs<BuiltinType>();
9542 if (!BT || !BT->isPlaceholderType()) return Owned(E);
9543
9544 // If this is overload, check for a single overload.
9545 if (BT->getKind() == BuiltinType::Overload) {
9546 if (FunctionDecl *Specialization
9547 = ResolveSingleFunctionTemplateSpecialization(E)) {
9548 // The access doesn't really matter in this case.
9549 DeclAccessPair Found = DeclAccessPair::make(Specialization,
9550 Specialization->getAccess());
9551 E = FixOverloadedFunctionReference(E, Found, Specialization);
9552 if (!E) return ExprError();
9553 return Owned(E);
9554 }
9555
John McCall2cd11fe2010-10-12 02:09:17 +00009556 Diag(Loc, diag::err_ovl_unresolvable) << E->getSourceRange();
John McCall2a984ca2010-10-12 00:20:44 +00009557 return ExprError();
9558 }
9559
9560 // Otherwise it's a use of undeduced auto.
9561 assert(BT->getKind() == BuiltinType::UndeducedAuto);
9562
9563 DeclRefExpr *DRE = cast<DeclRefExpr>(E->IgnoreParens());
9564 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
9565 << DRE->getDecl() << E->getSourceRange();
9566 return ExprError();
9567}