blob: 902afac0a7a80c324b08058578b5ee9563c093d1 [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
297 E = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
298 E, 0, VK_RValue);
299}
300
301void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
302 DefaultFunctionArrayConversion(E);
303 DefaultLvalueConversion(E);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000304}
305
306
Chris Lattnere7a2e912008-07-25 21:10:04 +0000307/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000308/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnere7a2e912008-07-25 21:10:04 +0000309/// sometimes surpressed. For example, the array->pointer conversion doesn't
310/// apply if the array is an argument to the sizeof or address (&) operators.
311/// In these instances, this routine should *not* be called.
John McCall0ae287a2010-12-01 04:43:34 +0000312Expr *Sema::UsualUnaryConversions(Expr *&E) {
313 // First, convert to an r-value.
314 DefaultFunctionArrayLvalueConversion(E);
315
316 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000317 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCall0ae287a2010-12-01 04:43:34 +0000318
319 // Try to perform integral promotions if the object has a theoretically
320 // promotable type.
321 if (Ty->isIntegralOrUnscopedEnumerationType()) {
322 // C99 6.3.1.1p2:
323 //
324 // The following may be used in an expression wherever an int or
325 // unsigned int may be used:
326 // - an object or expression with an integer type whose integer
327 // conversion rank is less than or equal to the rank of int
328 // and unsigned int.
329 // - A bit-field of type _Bool, int, signed int, or unsigned int.
330 //
331 // If an int can represent all values of the original type, the
332 // value is converted to an int; otherwise, it is converted to an
333 // unsigned int. These are called the integer promotions. All
334 // other types are unchanged by the integer promotions.
335
336 QualType PTy = Context.isPromotableBitField(E);
337 if (!PTy.isNull()) {
338 ImpCastExprToType(E, PTy, CK_IntegralCast);
339 return E;
340 }
341 if (Ty->isPromotableIntegerType()) {
342 QualType PT = Context.getPromotedIntegerType(Ty);
343 ImpCastExprToType(E, PT, CK_IntegralCast);
344 return E;
345 }
Eli Friedman04e83572009-08-20 04:21:42 +0000346 }
347
John McCall0ae287a2010-12-01 04:43:34 +0000348 return E;
Chris Lattnere7a2e912008-07-25 21:10:04 +0000349}
350
Chris Lattner05faf172008-07-25 22:25:12 +0000351/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000352/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000353/// double. All other argument types are converted by UsualUnaryConversions().
354void Sema::DefaultArgumentPromotion(Expr *&Expr) {
355 QualType Ty = Expr->getType();
356 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000357
John McCall40c29132010-12-06 18:36:11 +0000358 UsualUnaryConversions(Expr);
359
Chris Lattner05faf172008-07-25 22:25:12 +0000360 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000361 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John McCall40c29132010-12-06 18:36:11 +0000362 return ImpCastExprToType(Expr, Context.DoubleTy, CK_FloatingCast);
Chris Lattner05faf172008-07-25 22:25:12 +0000363}
364
Chris Lattner312531a2009-04-12 08:11:20 +0000365/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
366/// will warn if the resulting type is not a POD type, and rejects ObjC
367/// interfaces passed by value. This returns true if the argument type is
368/// completely illegal.
Chris Lattner40378332010-05-16 04:01:30 +0000369bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
370 FunctionDecl *FDecl) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000371 DefaultArgumentPromotion(Expr);
Mike Stump1eb44332009-09-09 15:08:12 +0000372
Chris Lattner40378332010-05-16 04:01:30 +0000373 // __builtin_va_start takes the second argument as a "varargs" argument, but
374 // it doesn't actually do anything with it. It doesn't need to be non-pod
375 // etc.
376 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
377 return false;
378
John McCallc12c5bb2010-05-15 11:32:37 +0000379 if (Expr->getType()->isObjCObjectType() &&
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000380 DiagRuntimeBehavior(Expr->getLocStart(),
381 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
382 << Expr->getType() << CT))
383 return true;
Douglas Gregor75b699a2009-12-12 07:25:49 +0000384
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000385 if (!Expr->getType()->isPODType() &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000386 DiagRuntimeBehavior(Expr->getLocStart(),
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000387 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
388 << Expr->getType() << CT))
389 return true;
Chris Lattner312531a2009-04-12 08:11:20 +0000390
391 return false;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000392}
393
Chris Lattnere7a2e912008-07-25 21:10:04 +0000394/// UsualArithmeticConversions - Performs various conversions that are common to
395/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000396/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000397/// responsible for emitting appropriate error diagnostics.
398/// FIXME: verify the conversion rules for "complex int" are consistent with
399/// GCC.
400QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
401 bool isCompAssign) {
Eli Friedmanab3a8522009-03-28 01:22:36 +0000402 if (!isCompAssign)
Chris Lattnere7a2e912008-07-25 21:10:04 +0000403 UsualUnaryConversions(lhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000404
405 UsualUnaryConversions(rhsExpr);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000406
Mike Stump1eb44332009-09-09 15:08:12 +0000407 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000408 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000409 QualType lhs =
410 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000411 QualType rhs =
Chris Lattnerb77792e2008-07-26 22:17:49 +0000412 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000413
414 // If both types are identical, no conversion is needed.
415 if (lhs == rhs)
416 return lhs;
417
418 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
419 // The caller can deal with this (e.g. pointer + int).
420 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
421 return lhs;
422
John McCallcf33b242010-11-13 08:17:45 +0000423 // Apply unary and bitfield promotions to the LHS's type.
424 QualType lhs_unpromoted = lhs;
425 if (lhs->isPromotableIntegerType())
426 lhs = Context.getPromotedIntegerType(lhs);
Eli Friedman04e83572009-08-20 04:21:42 +0000427 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000428 if (!LHSBitfieldPromoteTy.isNull())
429 lhs = LHSBitfieldPromoteTy;
John McCallcf33b242010-11-13 08:17:45 +0000430 if (lhs != lhs_unpromoted && !isCompAssign)
431 ImpCastExprToType(lhsExpr, lhs, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000432
John McCallcf33b242010-11-13 08:17:45 +0000433 // If both types are identical, no conversion is needed.
434 if (lhs == rhs)
435 return lhs;
436
437 // At this point, we have two different arithmetic types.
438
439 // Handle complex types first (C99 6.3.1.8p1).
440 bool LHSComplexFloat = lhs->isComplexType();
441 bool RHSComplexFloat = rhs->isComplexType();
442 if (LHSComplexFloat || RHSComplexFloat) {
443 // if we have an integer operand, the result is the complex type.
444
John McCall2bb5d002010-11-13 09:02:35 +0000445 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
446 if (rhs->isIntegerType()) {
447 QualType fp = cast<ComplexType>(lhs)->getElementType();
448 ImpCastExprToType(rhsExpr, fp, CK_IntegralToFloating);
449 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
450 } else {
451 assert(rhs->isComplexIntegerType());
John McCallf3ea8cf2010-11-14 08:17:51 +0000452 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000453 }
John McCallcf33b242010-11-13 08:17:45 +0000454 return lhs;
455 }
456
John McCall2bb5d002010-11-13 09:02:35 +0000457 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
458 if (!isCompAssign) {
459 // int -> float -> _Complex float
460 if (lhs->isIntegerType()) {
461 QualType fp = cast<ComplexType>(rhs)->getElementType();
462 ImpCastExprToType(lhsExpr, fp, CK_IntegralToFloating);
463 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
464 } else {
465 assert(lhs->isComplexIntegerType());
John McCallf3ea8cf2010-11-14 08:17:51 +0000466 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000467 }
468 }
John McCallcf33b242010-11-13 08:17:45 +0000469 return rhs;
470 }
471
472 // This handles complex/complex, complex/float, or float/complex.
473 // When both operands are complex, the shorter operand is converted to the
474 // type of the longer, and that is the type of the result. This corresponds
475 // to what is done when combining two real floating-point operands.
476 // The fun begins when size promotion occur across type domains.
477 // From H&S 6.3.4: When one operand is complex and the other is a real
478 // floating-point type, the less precise type is converted, within it's
479 // real or complex domain, to the precision of the other type. For example,
480 // when combining a "long double" with a "double _Complex", the
481 // "double _Complex" is promoted to "long double _Complex".
482 int order = Context.getFloatingTypeOrder(lhs, rhs);
483
484 // If both are complex, just cast to the more precise type.
485 if (LHSComplexFloat && RHSComplexFloat) {
486 if (order > 0) {
487 // _Complex float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000488 ImpCastExprToType(rhsExpr, lhs, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000489 return lhs;
490
491 } else if (order < 0) {
492 // _Complex float -> _Complex double
493 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000494 ImpCastExprToType(lhsExpr, rhs, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000495 return rhs;
496 }
497 return lhs;
498 }
499
500 // If just the LHS is complex, the RHS needs to be converted,
501 // and the LHS might need to be promoted.
502 if (LHSComplexFloat) {
503 if (order > 0) { // LHS is wider
504 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000505 QualType fp = cast<ComplexType>(lhs)->getElementType();
506 ImpCastExprToType(rhsExpr, fp, CK_FloatingCast);
507 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000508 return lhs;
509 }
510
511 // RHS is at least as wide. Find its corresponding complex type.
512 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
513
514 // double -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000515 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000516
517 // _Complex float -> _Complex double
518 if (!isCompAssign && order < 0)
John McCall2bb5d002010-11-13 09:02:35 +0000519 ImpCastExprToType(lhsExpr, result, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000520
521 return result;
522 }
523
524 // Just the RHS is complex, so the LHS needs to be converted
525 // and the RHS might need to be promoted.
526 assert(RHSComplexFloat);
527
528 if (order < 0) { // RHS is wider
529 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000530 if (!isCompAssign) {
531 ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast);
532 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
533 }
John McCallcf33b242010-11-13 08:17:45 +0000534 return rhs;
535 }
536
537 // LHS is at least as wide. Find its corresponding complex type.
538 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
539
540 // double -> _Complex double
541 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000542 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000543
544 // _Complex float -> _Complex double
545 if (order > 0)
John McCall2bb5d002010-11-13 09:02:35 +0000546 ImpCastExprToType(rhsExpr, result, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000547
548 return result;
549 }
550
551 // Now handle "real" floating types (i.e. float, double, long double).
552 bool LHSFloat = lhs->isRealFloatingType();
553 bool RHSFloat = rhs->isRealFloatingType();
554 if (LHSFloat || RHSFloat) {
555 // If we have two real floating types, convert the smaller operand
556 // to the bigger result.
557 if (LHSFloat && RHSFloat) {
558 int order = Context.getFloatingTypeOrder(lhs, rhs);
559 if (order > 0) {
560 ImpCastExprToType(rhsExpr, lhs, CK_FloatingCast);
561 return lhs;
562 }
563
564 assert(order < 0 && "illegal float comparison");
565 if (!isCompAssign)
566 ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast);
567 return rhs;
568 }
569
570 // If we have an integer operand, the result is the real floating type.
571 if (LHSFloat) {
572 if (rhs->isIntegerType()) {
573 // Convert rhs to the lhs floating point type.
574 ImpCastExprToType(rhsExpr, lhs, CK_IntegralToFloating);
575 return lhs;
576 }
577
578 // Convert both sides to the appropriate complex float.
579 assert(rhs->isComplexIntegerType());
580 QualType result = Context.getComplexType(lhs);
581
582 // _Complex int -> _Complex float
John McCallf3ea8cf2010-11-14 08:17:51 +0000583 ImpCastExprToType(rhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000584
585 // float -> _Complex float
586 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000587 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000588
589 return result;
590 }
591
592 assert(RHSFloat);
593 if (lhs->isIntegerType()) {
594 // Convert lhs to the rhs floating point type.
595 if (!isCompAssign)
596 ImpCastExprToType(lhsExpr, rhs, CK_IntegralToFloating);
597 return rhs;
598 }
599
600 // Convert both sides to the appropriate complex float.
601 assert(lhs->isComplexIntegerType());
602 QualType result = Context.getComplexType(rhs);
603
604 // _Complex int -> _Complex float
605 if (!isCompAssign)
John McCallf3ea8cf2010-11-14 08:17:51 +0000606 ImpCastExprToType(lhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000607
608 // float -> _Complex float
John McCall2bb5d002010-11-13 09:02:35 +0000609 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000610
611 return result;
612 }
613
614 // Handle GCC complex int extension.
615 // FIXME: if the operands are (int, _Complex long), we currently
616 // don't promote the complex. Also, signedness?
617 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
618 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
619 if (lhsComplexInt && rhsComplexInt) {
620 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
621 rhsComplexInt->getElementType());
622 assert(order && "inequal types with equal element ordering");
623 if (order > 0) {
624 // _Complex int -> _Complex long
John McCall2bb5d002010-11-13 09:02:35 +0000625 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000626 return lhs;
627 }
628
629 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000630 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000631 return rhs;
632 } else if (lhsComplexInt) {
633 // int -> _Complex int
John McCall2bb5d002010-11-13 09:02:35 +0000634 ImpCastExprToType(rhsExpr, lhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000635 return lhs;
636 } else if (rhsComplexInt) {
637 // int -> _Complex int
638 if (!isCompAssign)
John McCall2bb5d002010-11-13 09:02:35 +0000639 ImpCastExprToType(lhsExpr, rhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000640 return rhs;
641 }
642
643 // Finally, we have two differing integer types.
644 // The rules for this case are in C99 6.3.1.8
645 int compare = Context.getIntegerTypeOrder(lhs, rhs);
646 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
647 rhsSigned = rhs->hasSignedIntegerRepresentation();
648 if (lhsSigned == rhsSigned) {
649 // Same signedness; use the higher-ranked type
650 if (compare >= 0) {
651 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
652 return lhs;
653 } else if (!isCompAssign)
654 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
655 return rhs;
656 } else if (compare != (lhsSigned ? 1 : -1)) {
657 // The unsigned type has greater than or equal rank to the
658 // signed type, so use the unsigned type
659 if (rhsSigned) {
660 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
661 return lhs;
662 } else if (!isCompAssign)
663 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
664 return rhs;
665 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
666 // The two types are different widths; if we are here, that
667 // means the signed type is larger than the unsigned type, so
668 // use the signed type.
669 if (lhsSigned) {
670 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
671 return lhs;
672 } else if (!isCompAssign)
673 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
674 return rhs;
675 } else {
676 // The signed type is higher-ranked than the unsigned type,
677 // but isn't actually any bigger (like unsigned int and long
678 // on most 32-bit systems). Use the unsigned type corresponding
679 // to the signed type.
680 QualType result =
681 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
682 ImpCastExprToType(rhsExpr, result, CK_IntegralCast);
683 if (!isCompAssign)
684 ImpCastExprToType(lhsExpr, result, CK_IntegralCast);
685 return result;
686 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000687}
688
Chris Lattnere7a2e912008-07-25 21:10:04 +0000689//===----------------------------------------------------------------------===//
690// Semantic Analysis for various Expression Types
691//===----------------------------------------------------------------------===//
692
693
Steve Narofff69936d2007-09-16 03:34:24 +0000694/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000695/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
696/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
697/// multiple tokens. However, the common case is that StringToks points to one
698/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000699///
John McCall60d7b3a2010-08-24 06:29:42 +0000700ExprResult
Sean Hunt6cf75022010-08-30 17:47:05 +0000701Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000702 assert(NumStringToks && "Must have at least one string!");
703
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000704 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000705 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000706 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000707
708 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
709 for (unsigned i = 0; i != NumStringToks; ++i)
710 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000711
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000712 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000713 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000714 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000715
716 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +0000717 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +0000718 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000719
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000720 // Get an array type for the string, according to C99 6.4.5. This includes
721 // the nul terminator character as well as the string length for pascal
722 // strings.
723 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000724 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000725 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000726
Reid Spencer5f016e22007-07-11 17:01:13 +0000727 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sean Hunt6cf75022010-08-30 17:47:05 +0000728 return Owned(StringLiteral::Create(Context, Literal.GetString(),
729 Literal.GetStringLength(),
730 Literal.AnyWide, StrTy,
731 &StringTokLocs[0],
732 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000733}
734
Chris Lattner639e2d32008-10-20 05:16:36 +0000735/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
736/// CurBlock to VD should cause it to be snapshotted (as we do for auto
737/// variables defined outside the block) or false if this is not needed (e.g.
738/// for values inside the block or for globals).
739///
Douglas Gregor076ceb02010-03-01 20:44:28 +0000740/// This also keeps the 'hasBlockDeclRefExprs' in the BlockScopeInfo records
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000741/// up-to-date.
742///
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000743static bool ShouldSnapshotBlockValueReference(Sema &S, BlockScopeInfo *CurBlock,
Chris Lattner639e2d32008-10-20 05:16:36 +0000744 ValueDecl *VD) {
745 // If the value is defined inside the block, we couldn't snapshot it even if
746 // we wanted to.
747 if (CurBlock->TheDecl == VD->getDeclContext())
748 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000749
Chris Lattner639e2d32008-10-20 05:16:36 +0000750 // If this is an enum constant or function, it is constant, don't snapshot.
751 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
752 return false;
753
754 // If this is a reference to an extern, static, or global variable, no need to
755 // snapshot it.
756 // FIXME: What about 'const' variables in C++?
757 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000758 if (!Var->hasLocalStorage())
759 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000761 // Blocks that have these can't be constant.
762 CurBlock->hasBlockDeclRefExprs = true;
763
764 // If we have nested blocks, the decl may be declared in an outer block (in
765 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
766 // be defined outside all of the current blocks (in which case the blocks do
767 // all get the bit). Walk the nesting chain.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000768 for (unsigned I = S.FunctionScopes.size() - 1; I; --I) {
769 BlockScopeInfo *NextBlock = dyn_cast<BlockScopeInfo>(S.FunctionScopes[I]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000770
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000771 if (!NextBlock)
772 continue;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000773
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000774 // If we found the defining block for the variable, don't mark the block as
775 // having a reference outside it.
776 if (NextBlock->TheDecl == VD->getDeclContext())
777 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000779 // Otherwise, the DeclRef from the inner block causes the outer one to need
780 // a snapshot as well.
781 NextBlock->hasBlockDeclRefExprs = true;
782 }
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Chris Lattner639e2d32008-10-20 05:16:36 +0000784 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000785}
786
Chris Lattner639e2d32008-10-20 05:16:36 +0000787
John McCall60d7b3a2010-08-24 06:29:42 +0000788ExprResult
John McCallf89e55a2010-11-18 06:31:45 +0000789Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
790 SourceLocation Loc, const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000791 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +0000792 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +0000793}
794
795/// BuildDeclRefExpr - Build a DeclRefExpr.
John McCall60d7b3a2010-08-24 06:29:42 +0000796ExprResult
Abramo Bagnara25777432010-08-11 22:01:17 +0000797Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty,
John McCallf89e55a2010-11-18 06:31:45 +0000798 ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +0000799 const DeclarationNameInfo &NameInfo,
800 const CXXScopeSpec *SS) {
Anders Carlssone2bb2242009-06-26 19:16:07 +0000801 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000802 Diag(NameInfo.getLoc(),
Mike Stump1eb44332009-09-09 15:08:12 +0000803 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlssone2bb2242009-06-26 19:16:07 +0000804 << D->getDeclName();
805 return ExprError();
806 }
Mike Stump1eb44332009-09-09 15:08:12 +0000807
Anders Carlssone41590d2009-06-24 00:10:43 +0000808 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Douglas Gregor15dedf02010-04-27 21:10:04 +0000809 if (isa<NonTypeTemplateParmDecl>(VD)) {
810 // Non-type template parameters can be referenced anywhere they are
811 // visible.
Douglas Gregor63982352010-07-13 18:40:04 +0000812 Ty = Ty.getNonLValueExprType(Context);
Douglas Gregor15dedf02010-04-27 21:10:04 +0000813 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
Anders Carlssone41590d2009-06-24 00:10:43 +0000814 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
815 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000816 Diag(NameInfo.getLoc(),
817 diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlssone41590d2009-06-24 00:10:43 +0000818 << D->getIdentifier() << FD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +0000819 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlssone41590d2009-06-24 00:10:43 +0000820 << D->getIdentifier();
821 return ExprError();
822 }
823 }
John McCall09431682010-11-18 19:01:18 +0000824
825 // This ridiculousness brought to you by 'extern void x;' and the
826 // GNU compiler collection.
827 } else if (!getLangOptions().CPlusPlus && !Ty.hasQualifiers() &&
828 Ty->isVoidType()) {
829 VK = VK_RValue;
Anders Carlssone41590d2009-06-24 00:10:43 +0000830 }
831 }
Mike Stump1eb44332009-09-09 15:08:12 +0000832
Abramo Bagnara25777432010-08-11 22:01:17 +0000833 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +0000834
John McCall7eb0a9e2010-11-24 05:12:34 +0000835 Expr *E = DeclRefExpr::Create(Context,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000836 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
John McCall7eb0a9e2010-11-24 05:12:34 +0000837 SS? SS->getRange() : SourceRange(),
838 D, NameInfo, Ty, VK);
839
840 // Just in case we're building an illegal pointer-to-member.
841 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
842 E->setObjectKind(OK_BitField);
843
844 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +0000845}
846
John McCalldfa1edb2010-11-23 20:48:44 +0000847static ExprResult
848BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
849 const CXXScopeSpec &SS, FieldDecl *Field,
850 DeclAccessPair FoundDecl,
851 const DeclarationNameInfo &MemberNameInfo);
852
John McCall60d7b3a2010-08-24 06:29:42 +0000853ExprResult
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000854Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
Francois Pichet87c2e122010-11-21 06:08:52 +0000855 IndirectFieldDecl *IndirectField,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000856 Expr *BaseObjectExpr,
857 SourceLocation OpLoc) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000858 // Build the expression that refers to the base object, from
859 // which we will build a sequence of member references to each
860 // of the anonymous union objects and, eventually, the field we
861 // found via name lookup.
862 bool BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000863 Qualifiers BaseQuals;
Francois Pichet87c2e122010-11-21 06:08:52 +0000864 VarDecl *BaseObject = IndirectField->getVarDecl();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000865 if (BaseObject) {
866 // BaseObject is an anonymous struct/union variable (and is,
867 // therefore, not part of another non-anonymous record).
Douglas Gregore0762c92009-06-19 23:52:42 +0000868 MarkDeclarationReferenced(Loc, BaseObject);
John McCallf89e55a2010-11-18 06:31:45 +0000869 BaseObjectExpr =
870 new (Context) DeclRefExpr(BaseObject, BaseObject->getType(),
871 VK_LValue, Loc);
John McCall0953e762009-09-24 19:53:00 +0000872 BaseQuals
873 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000874 } else if (BaseObjectExpr) {
875 // The caller provided the base object expression. Determine
876 // whether its a pointer and whether it adds any qualifiers to the
877 // anonymous struct/union fields we're looking into.
878 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000879 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000880 BaseObjectIsPointer = true;
881 ObjectType = ObjectPtr->getPointeeType();
882 }
John McCall0953e762009-09-24 19:53:00 +0000883 BaseQuals
884 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000885 } else {
886 // We've found a member of an anonymous struct/union that is
887 // inside a non-anonymous struct/union, so in a well-formed
888 // program our base object expression is "this".
John McCallea1471e2010-05-20 01:18:31 +0000889 DeclContext *DC = getFunctionLevelDeclContext();
890 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000891 if (!MD->isStatic()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000892 QualType AnonFieldType
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000893 = Context.getTagDeclType(
Francois Pichet87c2e122010-11-21 06:08:52 +0000894 cast<RecordDecl>(
895 (*IndirectField->chain_begin())->getDeclContext()));
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000896 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +0000897 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000898 == Context.getCanonicalType(ThisType)) ||
899 IsDerivedFrom(ThisType, AnonFieldType)) {
900 // Our base object expression is "this".
Douglas Gregor8aa5f402009-12-24 20:23:34 +0000901 BaseObjectExpr = new (Context) CXXThisExpr(Loc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000902 MD->getThisType(Context),
903 /*isImplicit=*/true);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000904 BaseObjectIsPointer = true;
905 }
906 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000907 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
Francois Pichet87c2e122010-11-21 06:08:52 +0000908 << IndirectField->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000909 }
John McCall0953e762009-09-24 19:53:00 +0000910 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000911 }
912
Mike Stump1eb44332009-09-09 15:08:12 +0000913 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000914 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
Francois Pichet87c2e122010-11-21 06:08:52 +0000915 << IndirectField->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000916 }
917
918 // Build the implicit member references to the field of the
919 // anonymous struct/union.
920 Expr *Result = BaseObjectExpr;
John McCalldfa1edb2010-11-23 20:48:44 +0000921
Francois Pichet87c2e122010-11-21 06:08:52 +0000922 IndirectFieldDecl::chain_iterator FI = IndirectField->chain_begin(),
923 FEnd = IndirectField->chain_end();
John McCalldfa1edb2010-11-23 20:48:44 +0000924
Francois Pichet87c2e122010-11-21 06:08:52 +0000925 // Skip the first VarDecl if present.
926 if (BaseObject)
927 FI++;
928 for (; FI != FEnd; FI++) {
929 FieldDecl *Field = cast<FieldDecl>(*FI);
John McCall0953e762009-09-24 19:53:00 +0000930
John McCalldfa1edb2010-11-23 20:48:44 +0000931 // FIXME: the first access can be qualified
932 CXXScopeSpec SS;
John McCall0953e762009-09-24 19:53:00 +0000933
John McCalldfa1edb2010-11-23 20:48:44 +0000934 // FIXME: these are somewhat meaningless
935 DeclarationNameInfo MemberNameInfo(Field->getDeclName(), Loc);
936 DeclAccessPair FoundDecl = DeclAccessPair::make(Field, Field->getAccess());
John McCall0953e762009-09-24 19:53:00 +0000937
John McCalldfa1edb2010-11-23 20:48:44 +0000938 Result = BuildFieldReferenceExpr(*this, Result, BaseObjectIsPointer,
939 SS, Field, FoundDecl, MemberNameInfo)
940 .take();
John McCall0953e762009-09-24 19:53:00 +0000941
John McCalldfa1edb2010-11-23 20:48:44 +0000942 // All the implicit accesses are dot-accesses.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000943 BaseObjectIsPointer = false;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000944 }
945
Sebastian Redlcd965b92009-01-18 18:53:16 +0000946 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000947}
948
Abramo Bagnara25777432010-08-11 22:01:17 +0000949/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +0000950/// possibly a list of template arguments.
951///
952/// If this produces template arguments, it is permitted to call
953/// DecomposeTemplateName.
954///
955/// This actually loses a lot of source location information for
956/// non-standard name kinds; we should consider preserving that in
957/// some way.
958static void DecomposeUnqualifiedId(Sema &SemaRef,
959 const UnqualifiedId &Id,
960 TemplateArgumentListInfo &Buffer,
Abramo Bagnara25777432010-08-11 22:01:17 +0000961 DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +0000962 const TemplateArgumentListInfo *&TemplateArgs) {
963 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
964 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
965 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
966
967 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
968 Id.TemplateId->getTemplateArgs(),
969 Id.TemplateId->NumArgs);
970 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
971 TemplateArgsPtr.release();
972
John McCall2b5289b2010-08-23 07:28:44 +0000973 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +0000974 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
975 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +0000976 TemplateArgs = &Buffer;
977 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +0000978 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +0000979 TemplateArgs = 0;
980 }
981}
982
John McCall4c72d3e2010-02-08 19:26:07 +0000983/// Determines whether the given record is "fully-formed" at the given
984/// location, i.e. whether a qualified lookup into it is assured of
985/// getting consistent results already.
John McCall129e2df2009-11-30 22:42:35 +0000986static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
John McCall4c72d3e2010-02-08 19:26:07 +0000987 if (!Record->hasDefinition())
988 return false;
989
John McCall129e2df2009-11-30 22:42:35 +0000990 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
991 E = Record->bases_end(); I != E; ++I) {
992 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
993 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
994 if (!BaseRT) return false;
995
996 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall4c72d3e2010-02-08 19:26:07 +0000997 if (!BaseRecord->hasDefinition() ||
John McCall129e2df2009-11-30 22:42:35 +0000998 !IsFullyFormedScope(SemaRef, BaseRecord))
999 return false;
1000 }
1001
1002 return true;
1003}
1004
John McCallaa81e162009-12-01 22:10:20 +00001005/// Determines if the given class is provably not derived from all of
1006/// the prospective base classes.
1007static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1008 CXXRecordDecl *Record,
1009 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCallb1b42562009-12-01 22:28:41 +00001010 if (Bases.count(Record->getCanonicalDecl()))
John McCallaa81e162009-12-01 22:10:20 +00001011 return false;
1012
Douglas Gregor952b0172010-02-11 01:04:33 +00001013 RecordDecl *RD = Record->getDefinition();
John McCallb1b42562009-12-01 22:28:41 +00001014 if (!RD) return false;
1015 Record = cast<CXXRecordDecl>(RD);
1016
John McCallaa81e162009-12-01 22:10:20 +00001017 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1018 E = Record->bases_end(); I != E; ++I) {
1019 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1020 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1021 if (!BaseRT) return false;
1022
1023 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCallaa81e162009-12-01 22:10:20 +00001024 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1025 return false;
1026 }
1027
1028 return true;
1029}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001030
John McCallaa81e162009-12-01 22:10:20 +00001031enum IMAKind {
1032 /// The reference is definitely not an instance member access.
1033 IMA_Static,
1034
1035 /// The reference may be an implicit instance member access.
1036 IMA_Mixed,
1037
1038 /// The reference may be to an instance member, but it is invalid if
1039 /// so, because the context is not an instance method.
1040 IMA_Mixed_StaticContext,
1041
1042 /// The reference may be to an instance member, but it is invalid if
1043 /// so, because the context is from an unrelated class.
1044 IMA_Mixed_Unrelated,
1045
1046 /// The reference is definitely an implicit instance member access.
1047 IMA_Instance,
1048
1049 /// The reference may be to an unresolved using declaration.
1050 IMA_Unresolved,
1051
1052 /// The reference may be to an unresolved using declaration and the
1053 /// context is not an instance method.
1054 IMA_Unresolved_StaticContext,
1055
John McCallaa81e162009-12-01 22:10:20 +00001056 /// All possible referrents are instance members and the current
1057 /// context is not an instance method.
1058 IMA_Error_StaticContext,
1059
1060 /// All possible referrents are instance members of an unrelated
1061 /// class.
1062 IMA_Error_Unrelated
1063};
1064
1065/// The given lookup names class member(s) and is not being used for
1066/// an address-of-member expression. Classify the type of access
1067/// according to whether it's possible that this reference names an
1068/// instance member. This is best-effort; it is okay to
1069/// conservatively answer "yes", in which case some errors will simply
1070/// not be caught until template-instantiation.
1071static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1072 const LookupResult &R) {
John McCall3b4294e2009-12-16 12:17:52 +00001073 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCallaa81e162009-12-01 22:10:20 +00001074
John McCallea1471e2010-05-20 01:18:31 +00001075 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCallaa81e162009-12-01 22:10:20 +00001076 bool isStaticContext =
John McCallea1471e2010-05-20 01:18:31 +00001077 (!isa<CXXMethodDecl>(DC) ||
1078 cast<CXXMethodDecl>(DC)->isStatic());
John McCallaa81e162009-12-01 22:10:20 +00001079
1080 if (R.isUnresolvableResult())
1081 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1082
1083 // Collect all the declaring classes of instance members we find.
1084 bool hasNonInstance = false;
Sebastian Redlf9780002010-11-26 16:28:07 +00001085 bool hasField = false;
John McCallaa81e162009-12-01 22:10:20 +00001086 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1087 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall161755a2010-04-06 21:38:20 +00001088 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00001089
John McCall161755a2010-04-06 21:38:20 +00001090 if (D->isCXXInstanceMember()) {
Sebastian Redlf9780002010-11-26 16:28:07 +00001091 if (dyn_cast<FieldDecl>(D))
1092 hasField = true;
1093
John McCallaa81e162009-12-01 22:10:20 +00001094 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCallaa81e162009-12-01 22:10:20 +00001095 Classes.insert(R->getCanonicalDecl());
1096 }
1097 else
1098 hasNonInstance = true;
1099 }
1100
1101 // If we didn't find any instance members, it can't be an implicit
1102 // member reference.
1103 if (Classes.empty())
1104 return IMA_Static;
1105
1106 // If the current context is not an instance method, it can't be
1107 // an implicit member reference.
Sebastian Redlf9780002010-11-26 16:28:07 +00001108 if (isStaticContext) {
1109 if (hasNonInstance)
1110 return IMA_Mixed_StaticContext;
1111
1112 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1113 // C++0x [expr.prim.general]p10:
1114 // An id-expression that denotes a non-static data member or non-static
1115 // member function of a class can only be used:
1116 // (...)
1117 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1118 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1119 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1120 if (isUnevaluatedExpression)
1121 return IMA_Mixed_StaticContext;
1122 }
1123
1124 return IMA_Error_StaticContext;
1125 }
John McCallaa81e162009-12-01 22:10:20 +00001126
1127 // If we can prove that the current context is unrelated to all the
1128 // declaring classes, it can't be an implicit member reference (in
1129 // which case it's an error if any of those members are selected).
1130 if (IsProvablyNotDerivedFrom(SemaRef,
John McCallea1471e2010-05-20 01:18:31 +00001131 cast<CXXMethodDecl>(DC)->getParent(),
John McCallaa81e162009-12-01 22:10:20 +00001132 Classes))
1133 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1134
1135 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1136}
1137
1138/// Diagnose a reference to a field with no object available.
1139static void DiagnoseInstanceReference(Sema &SemaRef,
1140 const CXXScopeSpec &SS,
1141 const LookupResult &R) {
1142 SourceLocation Loc = R.getNameLoc();
1143 SourceRange Range(Loc);
1144 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1145
1146 if (R.getAsSingle<FieldDecl>()) {
1147 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1148 if (MD->isStatic()) {
1149 // "invalid use of member 'x' in static member function"
1150 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
1151 << Range << R.getLookupName();
1152 return;
1153 }
1154 }
1155
1156 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
1157 << R.getLookupName() << Range;
1158 return;
1159 }
1160
1161 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +00001162}
1163
John McCall578b69b2009-12-16 08:11:27 +00001164/// Diagnose an empty lookup.
1165///
1166/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001167bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1168 CorrectTypoContext CTC) {
John McCall578b69b2009-12-16 08:11:27 +00001169 DeclarationName Name = R.getLookupName();
1170
John McCall578b69b2009-12-16 08:11:27 +00001171 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001172 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001173 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1174 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001175 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001176 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001177 diagnostic_suggest = diag::err_undeclared_use_suggest;
1178 }
John McCall578b69b2009-12-16 08:11:27 +00001179
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001180 // If the original lookup was an unqualified lookup, fake an
1181 // unqualified lookup. This is useful when (for example) the
1182 // original lookup would not have found something because it was a
1183 // dependent name.
Nick Lewycky03d98c52010-07-06 19:51:49 +00001184 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001185 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +00001186 if (isa<CXXRecordDecl>(DC)) {
1187 LookupQualifiedName(R, DC);
1188
1189 if (!R.empty()) {
1190 // Don't give errors about ambiguities in this lookup.
1191 R.suppressDiagnostics();
1192
1193 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1194 bool isInstance = CurMethod &&
1195 CurMethod->isInstance() &&
1196 DC == CurMethod->getParent();
1197
1198 // Give a code modification hint to insert 'this->'.
1199 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1200 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +00001201 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +00001202 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1203 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001204 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +00001205 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +00001206 if (DepMethod) {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001207 Diag(R.getNameLoc(), diagnostic) << Name
1208 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1209 QualType DepThisType = DepMethod->getThisType(Context);
1210 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1211 R.getNameLoc(), DepThisType, false);
1212 TemplateArgumentListInfo TList;
1213 if (ULE->hasExplicitTemplateArgs())
1214 ULE->copyTemplateArgumentsInto(TList);
1215 CXXDependentScopeMemberExpr *DepExpr =
1216 CXXDependentScopeMemberExpr::Create(
1217 Context, DepThis, DepThisType, true, SourceLocation(),
1218 ULE->getQualifier(), ULE->getQualifierRange(), NULL,
1219 R.getLookupNameInfo(), &TList);
1220 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +00001221 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001222 // FIXME: we should be able to handle this case too. It is correct
1223 // to add this-> here. This is a workaround for PR7947.
1224 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +00001225 }
Nick Lewycky03d98c52010-07-06 19:51:49 +00001226 } else {
John McCall578b69b2009-12-16 08:11:27 +00001227 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001228 }
John McCall578b69b2009-12-16 08:11:27 +00001229
1230 // Do we really want to note all of these?
1231 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1232 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1233
1234 // Tell the callee to try to recover.
1235 return false;
1236 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001237
1238 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001239 }
1240 }
1241
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001242 // We didn't find anything, so try to correct for a typo.
Douglas Gregoraaf87162010-04-14 20:04:41 +00001243 DeclarationName Corrected;
Daniel Dunbardc32cdf2010-06-02 15:46:52 +00001244 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001245 if (!R.empty()) {
1246 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1247 if (SS.isEmpty())
1248 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1249 << FixItHint::CreateReplacement(R.getNameLoc(),
1250 R.getLookupName().getAsString());
1251 else
1252 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1253 << Name << computeDeclContext(SS, false) << R.getLookupName()
1254 << SS.getRange()
1255 << FixItHint::CreateReplacement(R.getNameLoc(),
1256 R.getLookupName().getAsString());
1257 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1258 Diag(ND->getLocation(), diag::note_previous_decl)
1259 << ND->getDeclName();
1260
1261 // Tell the callee to try to recover.
1262 return false;
1263 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001264
Douglas Gregoraaf87162010-04-14 20:04:41 +00001265 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1266 // FIXME: If we ended up with a typo for a type name or
1267 // Objective-C class name, we're in trouble because the parser
1268 // is in the wrong place to recover. Suggest the typo
1269 // correction, but don't make it a fix-it since we're not going
1270 // to recover well anyway.
1271 if (SS.isEmpty())
1272 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1273 else
1274 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1275 << Name << computeDeclContext(SS, false) << R.getLookupName()
1276 << SS.getRange();
1277
1278 // Don't try to recover; it won't work.
1279 return true;
1280 }
1281 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001282 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001283 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001284 if (SS.isEmpty())
Douglas Gregoraaf87162010-04-14 20:04:41 +00001285 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001286 else
Douglas Gregord203a162010-01-01 00:15:04 +00001287 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001288 << Name << computeDeclContext(SS, false) << Corrected
1289 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001290 return true;
1291 }
Douglas Gregord203a162010-01-01 00:15:04 +00001292 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001293 }
1294
1295 // Emit a special diagnostic for failed member lookups.
1296 // FIXME: computing the declaration context might fail here (?)
1297 if (!SS.isEmpty()) {
1298 Diag(R.getNameLoc(), diag::err_no_member)
1299 << Name << computeDeclContext(SS, false)
1300 << SS.getRange();
1301 return true;
1302 }
1303
John McCall578b69b2009-12-16 08:11:27 +00001304 // Give up, we can't recover.
1305 Diag(R.getNameLoc(), diagnostic) << Name;
1306 return true;
1307}
1308
Douglas Gregorca45da02010-11-02 20:36:02 +00001309ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1310 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001311 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1312 if (!IDecl)
1313 return 0;
1314 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1315 if (!ClassImpDecl)
1316 return 0;
Douglas Gregorca45da02010-11-02 20:36:02 +00001317 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001318 if (!property)
1319 return 0;
1320 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregorca45da02010-11-02 20:36:02 +00001321 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1322 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001323 return 0;
1324 return property;
1325}
1326
Douglas Gregorca45da02010-11-02 20:36:02 +00001327bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1328 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1329 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1330 if (!IDecl)
1331 return false;
1332 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1333 if (!ClassImpDecl)
1334 return false;
1335 if (ObjCPropertyImplDecl *PIDecl
1336 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1337 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1338 PIDecl->getPropertyIvarDecl())
1339 return false;
1340
1341 return true;
1342}
1343
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001344static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001345 LookupResult &Lookup,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001346 IdentifierInfo *II,
1347 SourceLocation NameLoc) {
1348 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001349 bool LookForIvars;
1350 if (Lookup.empty())
1351 LookForIvars = true;
1352 else if (CurMeth->isClassMethod())
1353 LookForIvars = false;
1354 else
1355 LookForIvars = (Lookup.isSingleResult() &&
1356 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1357 if (!LookForIvars)
1358 return 0;
1359
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001360 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1361 if (!IDecl)
1362 return 0;
1363 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001364 if (!ClassImpDecl)
1365 return 0;
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001366 bool DynamicImplSeen = false;
1367 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1368 if (!property)
1369 return 0;
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001370 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001371 DynamicImplSeen =
1372 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001373 // property implementation has a designated ivar. No need to assume a new
1374 // one.
1375 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1376 return 0;
1377 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001378 if (!DynamicImplSeen) {
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001379 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1380 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001381 NameLoc,
1382 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian75049662010-12-15 23:29:04 +00001383 ObjCIvarDecl::Private,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001384 (Expr *)0, true);
1385 ClassImpDecl->addDecl(Ivar);
1386 IDecl->makeDeclVisibleInContext(Ivar, false);
1387 property->setPropertyIvarDecl(Ivar);
1388 return Ivar;
1389 }
1390 return 0;
1391}
1392
John McCall60d7b3a2010-08-24 06:29:42 +00001393ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001394 CXXScopeSpec &SS,
1395 UnqualifiedId &Id,
1396 bool HasTrailingLParen,
1397 bool isAddressOfOperand) {
John McCallf7a1a742009-11-24 19:00:30 +00001398 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1399 "cannot be direct & operand and have a trailing lparen");
1400
1401 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001402 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001403
John McCall129e2df2009-11-30 22:42:35 +00001404 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001405
1406 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001407 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001408 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnara25777432010-08-11 22:01:17 +00001409 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001410
Abramo Bagnara25777432010-08-11 22:01:17 +00001411 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001412 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001413 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001414
John McCallf7a1a742009-11-24 19:00:30 +00001415 // C++ [temp.dep.expr]p3:
1416 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001417 // -- an identifier that was declared with a dependent type,
1418 // (note: handled after lookup)
1419 // -- a template-id that is dependent,
1420 // (note: handled in BuildTemplateIdExpr)
1421 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001422 // -- a nested-name-specifier that contains a class-name that
1423 // names a dependent type.
1424 // Determine whether this is a member of an unknown specialization;
1425 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001426 bool DependentID = false;
1427 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1428 Name.getCXXNameType()->isDependentType()) {
1429 DependentID = true;
1430 } else if (SS.isSet()) {
1431 DeclContext *DC = computeDeclContext(SS, false);
1432 if (DC) {
1433 if (RequireCompleteDeclContext(SS, DC))
1434 return ExprError();
1435 // FIXME: We should be checking whether DC is the current instantiation.
1436 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
1437 DependentID = !IsFullyFormedScope(*this, RD);
1438 } else {
1439 DependentID = true;
1440 }
1441 }
1442
1443 if (DependentID) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001444 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001445 TemplateArgs);
1446 }
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001447 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001448 // Perform the required lookup.
Abramo Bagnara25777432010-08-11 22:01:17 +00001449 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001450 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001451 // Lookup the template name again to correctly establish the context in
1452 // which it was found. This is really unfortunate as we already did the
1453 // lookup to determine that it was a template name in the first place. If
1454 // this becomes a performance hit, we can work harder to preserve those
1455 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001456 bool MemberOfUnknownSpecialization;
1457 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1458 MemberOfUnknownSpecialization);
John McCallf7a1a742009-11-24 19:00:30 +00001459 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001460 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001461 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001462
John McCallf7a1a742009-11-24 19:00:30 +00001463 // If this reference is in an Objective-C method, then we need to do
1464 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001465 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001466 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001467 if (E.isInvalid())
1468 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001469
John McCallf7a1a742009-11-24 19:00:30 +00001470 Expr *Ex = E.takeAs<Expr>();
1471 if (Ex) return Owned(Ex);
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001472 // Synthesize ivars lazily
Fariborz Jahaniane776f882011-01-03 18:08:02 +00001473 if (getLangOptions().ObjCDefaultSynthProperties &&
1474 getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahaniande267602010-11-17 19:41:23 +00001475 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1476 if (const ObjCPropertyDecl *Property =
1477 canSynthesizeProvisionalIvar(II)) {
1478 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1479 Diag(Property->getLocation(), diag::note_property_declare);
1480 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001481 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1482 isAddressOfOperand);
Fariborz Jahaniande267602010-11-17 19:41:23 +00001483 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001484 }
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001485 // for further use, this must be set to false if in class method.
1486 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001487 }
Chris Lattner8a934232008-03-31 00:36:02 +00001488 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001489
John McCallf7a1a742009-11-24 19:00:30 +00001490 if (R.isAmbiguous())
1491 return ExprError();
1492
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001493 // Determine whether this name might be a candidate for
1494 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001495 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001496
John McCallf7a1a742009-11-24 19:00:30 +00001497 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001498 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001499 // in C90, extension in C99, forbidden in C++).
1500 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1501 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1502 if (D) R.addDecl(D);
1503 }
1504
1505 // If this name wasn't predeclared and if this is not a function
1506 // call, diagnose the problem.
1507 if (R.empty()) {
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001508 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001509 return ExprError();
1510
1511 assert(!R.empty() &&
1512 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001513
1514 // If we found an Objective-C instance variable, let
1515 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001516 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001517 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1518 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001519 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001520 assert(E.isInvalid() || E.get());
1521 return move(E);
1522 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001523 }
1524 }
Mike Stump1eb44332009-09-09 15:08:12 +00001525
John McCallf7a1a742009-11-24 19:00:30 +00001526 // This is guaranteed from this point on.
1527 assert(!R.empty() || ADL);
1528
1529 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001530 if (getLangOptions().ObjCNonFragileABI && IvarLookupFollowUp &&
Fariborz Jahaniane776f882011-01-03 18:08:02 +00001531 !(getLangOptions().ObjCDefaultSynthProperties &&
1532 getLangOptions().ObjCNonFragileABI2) &&
Fariborz Jahanianb1d58e32010-07-29 16:53:53 +00001533 Var->isFileVarDecl()) {
Douglas Gregorca45da02010-11-02 20:36:02 +00001534 ObjCPropertyDecl *Property = canSynthesizeProvisionalIvar(II);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001535 if (Property) {
1536 Diag(NameLoc, diag::warn_ivar_variable_conflict) << Var->getDeclName();
1537 Diag(Property->getLocation(), diag::note_property_declare);
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001538 Diag(Var->getLocation(), diag::note_global_declared_at);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001539 }
1540 }
John McCallf7a1a742009-11-24 19:00:30 +00001541 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +00001542 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1543 // C99 DR 316 says that, if a function type comes from a
1544 // function definition (without a prototype), that type is only
1545 // used for checking compatibility. Therefore, when referencing
1546 // the function, we pretend that we don't have the full function
1547 // type.
John McCallf7a1a742009-11-24 19:00:30 +00001548 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor751f9a42009-06-30 15:47:41 +00001549 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001550
Douglas Gregor751f9a42009-06-30 15:47:41 +00001551 QualType T = Func->getType();
1552 QualType NoProtoType = T;
John McCall183700f2009-09-21 23:43:11 +00001553 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Eli Friedman9a0fcfe2010-05-17 02:50:18 +00001554 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType(),
1555 Proto->getExtInfo());
John McCallf89e55a2010-11-18 06:31:45 +00001556 // Note that functions are r-values in C.
1557 return BuildDeclRefExpr(Func, NoProtoType, VK_RValue, NameLoc, &SS);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001558 }
1559 }
Mike Stump1eb44332009-09-09 15:08:12 +00001560
John McCallaa81e162009-12-01 22:10:20 +00001561 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001562 // C++ [class.mfct.non-static]p3:
1563 // When an id-expression that is not part of a class member access
1564 // syntax and not used to form a pointer to member is used in the
1565 // body of a non-static member function of class X, if name lookup
1566 // resolves the name in the id-expression to a non-static non-type
1567 // member of some class C, the id-expression is transformed into a
1568 // class member access expression using (*this) as the
1569 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001570 //
1571 // But we don't actually need to do this for '&' operands if R
1572 // resolved to a function or overloaded function set, because the
1573 // expression is ill-formed if it actually works out to be a
1574 // non-static member function:
1575 //
1576 // C++ [expr.ref]p4:
1577 // Otherwise, if E1.E2 refers to a non-static member function. . .
1578 // [t]he expression can be used only as the left-hand operand of a
1579 // member function call.
1580 //
1581 // There are other safeguards against such uses, but it's important
1582 // to get this right here so that we don't end up making a
1583 // spuriously dependent expression if we're inside a dependent
1584 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001585 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001586 bool MightBeImplicitMember;
1587 if (!isAddressOfOperand)
1588 MightBeImplicitMember = true;
1589 else if (!SS.isEmpty())
1590 MightBeImplicitMember = false;
1591 else if (R.isOverloadedResult())
1592 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001593 else if (R.isUnresolvableResult())
1594 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001595 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001596 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1597 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001598
1599 if (MightBeImplicitMember)
John McCall3b4294e2009-12-16 12:17:52 +00001600 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001601 }
1602
John McCallf7a1a742009-11-24 19:00:30 +00001603 if (TemplateArgs)
1604 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001605
John McCallf7a1a742009-11-24 19:00:30 +00001606 return BuildDeclarationNameExpr(SS, R, ADL);
1607}
1608
John McCall3b4294e2009-12-16 12:17:52 +00001609/// Builds an expression which might be an implicit member expression.
John McCall60d7b3a2010-08-24 06:29:42 +00001610ExprResult
John McCall3b4294e2009-12-16 12:17:52 +00001611Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1612 LookupResult &R,
1613 const TemplateArgumentListInfo *TemplateArgs) {
1614 switch (ClassifyImplicitMemberAccess(*this, R)) {
1615 case IMA_Instance:
1616 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1617
John McCall3b4294e2009-12-16 12:17:52 +00001618 case IMA_Mixed:
1619 case IMA_Mixed_Unrelated:
1620 case IMA_Unresolved:
1621 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1622
1623 case IMA_Static:
1624 case IMA_Mixed_StaticContext:
1625 case IMA_Unresolved_StaticContext:
1626 if (TemplateArgs)
1627 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1628 return BuildDeclarationNameExpr(SS, R, false);
1629
1630 case IMA_Error_StaticContext:
1631 case IMA_Error_Unrelated:
1632 DiagnoseInstanceReference(*this, SS, R);
1633 return ExprError();
1634 }
1635
1636 llvm_unreachable("unexpected instance member access kind");
1637 return ExprError();
1638}
1639
John McCall129e2df2009-11-30 22:42:35 +00001640/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1641/// declaration name, generally during template instantiation.
1642/// There's a large number of things which don't need to be done along
1643/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001644ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001645Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001646 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001647 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001648 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00001649 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00001650
John McCall77bb1aa2010-05-01 00:40:08 +00001651 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001652 return ExprError();
1653
Abramo Bagnara25777432010-08-11 22:01:17 +00001654 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001655 LookupQualifiedName(R, DC);
1656
1657 if (R.isAmbiguous())
1658 return ExprError();
1659
1660 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001661 Diag(NameInfo.getLoc(), diag::err_no_member)
1662 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001663 return ExprError();
1664 }
1665
1666 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1667}
1668
1669/// LookupInObjCMethod - The parser has read a name in, and Sema has
1670/// detected that we're currently inside an ObjC method. Perform some
1671/// additional lookup.
1672///
1673/// Ideally, most of this would be done by lookup, but there's
1674/// actually quite a lot of extra work involved.
1675///
1676/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001677ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001678Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001679 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001680 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001681 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001682
John McCallf7a1a742009-11-24 19:00:30 +00001683 // There are two cases to handle here. 1) scoped lookup could have failed,
1684 // in which case we should look for an ivar. 2) scoped lookup could have
1685 // found a decl, but that decl is outside the current instance method (i.e.
1686 // a global variable). In these two cases, we do a lookup for an ivar with
1687 // this name, if the lookup sucedes, we replace it our current decl.
1688
1689 // If we're in a class method, we don't normally want to look for
1690 // ivars. But if we don't find anything else, and there's an
1691 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001692 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001693
1694 bool LookForIvars;
1695 if (Lookup.empty())
1696 LookForIvars = true;
1697 else if (IsClassMethod)
1698 LookForIvars = false;
1699 else
1700 LookForIvars = (Lookup.isSingleResult() &&
1701 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001702 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001703 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001704 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001705 ObjCInterfaceDecl *ClassDeclared;
1706 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1707 // Diagnose using an ivar in a class method.
1708 if (IsClassMethod)
1709 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1710 << IV->getDeclName());
1711
1712 // If we're referencing an invalid decl, just return this as a silent
1713 // error node. The error diagnostic was already emitted on the decl.
1714 if (IV->isInvalidDecl())
1715 return ExprError();
1716
1717 // Check if referencing a field with __attribute__((deprecated)).
1718 if (DiagnoseUseOfDecl(IV, Loc))
1719 return ExprError();
1720
1721 // Diagnose the use of an ivar outside of the declaring class.
1722 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1723 ClassDeclared != IFace)
1724 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1725
1726 // FIXME: This should use a new expr for a direct reference, don't
1727 // turn this into Self->ivar, just return a BareIVarExpr or something.
1728 IdentifierInfo &II = Context.Idents.get("self");
1729 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001730 SelfName.setIdentifier(&II, SourceLocation());
John McCallf7a1a742009-11-24 19:00:30 +00001731 CXXScopeSpec SelfScopeSpec;
John McCall60d7b3a2010-08-24 06:29:42 +00001732 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001733 SelfName, false, false);
1734 if (SelfExpr.isInvalid())
1735 return ExprError();
1736
John McCall409fa9a2010-12-06 20:48:59 +00001737 Expr *SelfE = SelfExpr.take();
1738 DefaultLvalueConversion(SelfE);
1739
John McCallf7a1a742009-11-24 19:00:30 +00001740 MarkDeclarationReferenced(Loc, IV);
1741 return Owned(new (Context)
1742 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John McCall409fa9a2010-12-06 20:48:59 +00001743 SelfE, true, true));
John McCallf7a1a742009-11-24 19:00:30 +00001744 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001745 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001746 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00001747 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001748 ObjCInterfaceDecl *ClassDeclared;
1749 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1750 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1751 IFace == ClassDeclared)
1752 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1753 }
1754 }
1755
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001756 if (Lookup.empty() && II && AllowBuiltinCreation) {
1757 // FIXME. Consolidate this with similar code in LookupName.
1758 if (unsigned BuiltinID = II->getBuiltinID()) {
1759 if (!(getLangOptions().CPlusPlus &&
1760 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1761 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1762 S, Lookup.isForRedeclaration(),
1763 Lookup.getNameLoc());
1764 if (D) Lookup.addDecl(D);
1765 }
1766 }
1767 }
John McCallf7a1a742009-11-24 19:00:30 +00001768 // Sentinel value saying that we didn't do anything special.
1769 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001770}
John McCallba135432009-11-21 08:51:07 +00001771
John McCall6bb80172010-03-30 21:47:33 +00001772/// \brief Cast a base object to a member's actual type.
1773///
1774/// Logically this happens in three phases:
1775///
1776/// * First we cast from the base type to the naming class.
1777/// The naming class is the class into which we were looking
1778/// when we found the member; it's the qualifier type if a
1779/// qualifier was provided, and otherwise it's the base type.
1780///
1781/// * Next we cast from the naming class to the declaring class.
1782/// If the member we found was brought into a class's scope by
1783/// a using declaration, this is that class; otherwise it's
1784/// the class declaring the member.
1785///
1786/// * Finally we cast from the declaring class to the "true"
1787/// declaring class of the member. This conversion does not
1788/// obey access control.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001789bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00001790Sema::PerformObjectMemberConversion(Expr *&From,
1791 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00001792 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001793 NamedDecl *Member) {
1794 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1795 if (!RD)
1796 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001797
Douglas Gregor5fccd362010-03-03 23:55:11 +00001798 QualType DestRecordType;
1799 QualType DestType;
1800 QualType FromRecordType;
1801 QualType FromType = From->getType();
1802 bool PointerConversions = false;
1803 if (isa<FieldDecl>(Member)) {
1804 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001805
Douglas Gregor5fccd362010-03-03 23:55:11 +00001806 if (FromType->getAs<PointerType>()) {
1807 DestType = Context.getPointerType(DestRecordType);
1808 FromRecordType = FromType->getPointeeType();
1809 PointerConversions = true;
1810 } else {
1811 DestType = DestRecordType;
1812 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001813 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001814 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1815 if (Method->isStatic())
1816 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001817
Douglas Gregor5fccd362010-03-03 23:55:11 +00001818 DestType = Method->getThisType(Context);
1819 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001820
Douglas Gregor5fccd362010-03-03 23:55:11 +00001821 if (FromType->getAs<PointerType>()) {
1822 FromRecordType = FromType->getPointeeType();
1823 PointerConversions = true;
1824 } else {
1825 FromRecordType = FromType;
1826 DestType = DestRecordType;
1827 }
1828 } else {
1829 // No conversion necessary.
1830 return false;
1831 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001832
Douglas Gregor5fccd362010-03-03 23:55:11 +00001833 if (DestType->isDependentType() || FromType->isDependentType())
1834 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001835
Douglas Gregor5fccd362010-03-03 23:55:11 +00001836 // If the unqualified types are the same, no conversion is necessary.
1837 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1838 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001839
John McCall6bb80172010-03-30 21:47:33 +00001840 SourceRange FromRange = From->getSourceRange();
1841 SourceLocation FromLoc = FromRange.getBegin();
1842
John McCall5baba9d2010-08-25 10:28:54 +00001843 ExprValueKind VK = CastCategory(From);
Sebastian Redl906082e2010-07-20 04:20:21 +00001844
Douglas Gregor5fccd362010-03-03 23:55:11 +00001845 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001846 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00001847 // class name.
1848 //
1849 // If the member was a qualified name and the qualified referred to a
1850 // specific base subobject type, we'll cast to that intermediate type
1851 // first and then to the object in which the member is declared. That allows
1852 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1853 //
1854 // class Base { public: int x; };
1855 // class Derived1 : public Base { };
1856 // class Derived2 : public Base { };
1857 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1858 //
1859 // void VeryDerived::f() {
1860 // x = 17; // error: ambiguous base subobjects
1861 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1862 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001863 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00001864 QualType QType = QualType(Qualifier->getAsType(), 0);
1865 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1866 assert(QType->isRecordType() && "lookup done with non-record type");
1867
1868 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1869
1870 // In C++98, the qualifier type doesn't actually have to be a base
1871 // type of the object type, in which case we just ignore it.
1872 // Otherwise build the appropriate casts.
1873 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00001874 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00001875 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00001876 FromLoc, FromRange, &BasePath))
John McCall6bb80172010-03-30 21:47:33 +00001877 return true;
1878
Douglas Gregor5fccd362010-03-03 23:55:11 +00001879 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00001880 QType = Context.getPointerType(QType);
John McCall5baba9d2010-08-25 10:28:54 +00001881 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
1882 VK, &BasePath);
John McCall6bb80172010-03-30 21:47:33 +00001883
1884 FromType = QType;
1885 FromRecordType = QRecordType;
1886
1887 // If the qualifier type was the same as the destination type,
1888 // we're done.
1889 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1890 return false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00001891 }
1892 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001893
John McCall6bb80172010-03-30 21:47:33 +00001894 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00001895
John McCall6bb80172010-03-30 21:47:33 +00001896 // If we actually found the member through a using declaration, cast
1897 // down to the using declaration's type.
1898 //
1899 // Pointer equality is fine here because only one declaration of a
1900 // class ever has member declarations.
1901 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
1902 assert(isa<UsingShadowDecl>(FoundDecl));
1903 QualType URecordType = Context.getTypeDeclType(
1904 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
1905
1906 // We only need to do this if the naming-class to declaring-class
1907 // conversion is non-trivial.
1908 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
1909 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00001910 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00001911 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00001912 FromLoc, FromRange, &BasePath))
John McCall6bb80172010-03-30 21:47:33 +00001913 return true;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001914
John McCall6bb80172010-03-30 21:47:33 +00001915 QualType UType = URecordType;
1916 if (PointerConversions)
1917 UType = Context.getPointerType(UType);
John McCall2de56d12010-08-25 11:45:40 +00001918 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00001919 VK, &BasePath);
John McCall6bb80172010-03-30 21:47:33 +00001920 FromType = UType;
1921 FromRecordType = URecordType;
1922 }
1923
1924 // We don't do access control for the conversion from the
1925 // declaring class to the true declaring class.
1926 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00001927 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001928
John McCallf871d0c2010-08-07 06:22:56 +00001929 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00001930 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
1931 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00001932 IgnoreAccess))
Douglas Gregor5fccd362010-03-03 23:55:11 +00001933 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001934
John McCall2de56d12010-08-25 11:45:40 +00001935 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00001936 VK, &BasePath);
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001937 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001938}
Douglas Gregor751f9a42009-06-30 15:47:41 +00001939
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001940/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00001941static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00001942 const CXXScopeSpec &SS, ValueDecl *Member,
John McCall161755a2010-04-06 21:38:20 +00001943 DeclAccessPair FoundDecl,
Abramo Bagnara25777432010-08-11 22:01:17 +00001944 const DeclarationNameInfo &MemberNameInfo,
1945 QualType Ty,
John McCallf89e55a2010-11-18 06:31:45 +00001946 ExprValueKind VK, ExprObjectKind OK,
John McCallf7a1a742009-11-24 19:00:30 +00001947 const TemplateArgumentListInfo *TemplateArgs = 0) {
1948 NestedNameSpecifier *Qualifier = 0;
1949 SourceRange QualifierRange;
John McCall129e2df2009-11-30 22:42:35 +00001950 if (SS.isSet()) {
1951 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1952 QualifierRange = SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001953 }
Mike Stump1eb44332009-09-09 15:08:12 +00001954
John McCallf7a1a742009-11-24 19:00:30 +00001955 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
Abramo Bagnara25777432010-08-11 22:01:17 +00001956 Member, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00001957 TemplateArgs, Ty, VK, OK);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00001958}
1959
John McCalldfa1edb2010-11-23 20:48:44 +00001960static ExprResult
1961BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1962 const CXXScopeSpec &SS, FieldDecl *Field,
1963 DeclAccessPair FoundDecl,
1964 const DeclarationNameInfo &MemberNameInfo) {
1965 // x.a is an l-value if 'a' has a reference type. Otherwise:
1966 // x.a is an l-value/x-value/pr-value if the base is (and note
1967 // that *x is always an l-value), except that if the base isn't
1968 // an ordinary object then we must have an rvalue.
1969 ExprValueKind VK = VK_LValue;
1970 ExprObjectKind OK = OK_Ordinary;
1971 if (!IsArrow) {
1972 if (BaseExpr->getObjectKind() == OK_Ordinary)
1973 VK = BaseExpr->getValueKind();
1974 else
1975 VK = VK_RValue;
1976 }
1977 if (VK != VK_RValue && Field->isBitField())
1978 OK = OK_BitField;
1979
1980 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1981 QualType MemberType = Field->getType();
1982 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1983 MemberType = Ref->getPointeeType();
1984 VK = VK_LValue;
1985 } else {
1986 QualType BaseType = BaseExpr->getType();
1987 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1988
1989 Qualifiers BaseQuals = BaseType.getQualifiers();
1990
1991 // GC attributes are never picked up by members.
1992 BaseQuals.removeObjCGCAttr();
1993
1994 // CVR attributes from the base are picked up by members,
1995 // except that 'mutable' members don't pick up 'const'.
1996 if (Field->isMutable()) BaseQuals.removeConst();
1997
1998 Qualifiers MemberQuals
1999 = S.Context.getCanonicalType(MemberType).getQualifiers();
2000
2001 // TR 18037 does not allow fields to be declared with address spaces.
2002 assert(!MemberQuals.hasAddressSpace());
2003
2004 Qualifiers Combined = BaseQuals + MemberQuals;
2005 if (Combined != MemberQuals)
2006 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2007 }
2008
2009 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
2010 if (S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2011 FoundDecl, Field))
2012 return ExprError();
2013 return S.Owned(BuildMemberExpr(S.Context, BaseExpr, IsArrow, SS,
2014 Field, FoundDecl, MemberNameInfo,
2015 MemberType, VK, OK));
2016}
2017
John McCallaa81e162009-12-01 22:10:20 +00002018/// Builds an implicit member access expression. The current context
2019/// is known to be an instance method, and the given unqualified lookup
2020/// set is known to contain only instance members, at least one of which
2021/// is from an appropriate type.
John McCall60d7b3a2010-08-24 06:29:42 +00002022ExprResult
John McCallaa81e162009-12-01 22:10:20 +00002023Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2024 LookupResult &R,
2025 const TemplateArgumentListInfo *TemplateArgs,
2026 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00002027 assert(!R.empty() && !R.isAmbiguous());
2028
John McCallba135432009-11-21 08:51:07 +00002029 SourceLocation Loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00002030
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002031 // We may have found a field within an anonymous union or struct
2032 // (C++ [class.union]).
Douglas Gregore961afb2009-10-22 07:08:30 +00002033 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCallf7a1a742009-11-24 19:00:30 +00002034 // FIXME: template-ids inside anonymous structs?
Francois Pichet87c2e122010-11-21 06:08:52 +00002035 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
2036 return BuildAnonymousStructUnionMemberReference(Loc, FD);
2037
Sebastian Redlcd965b92009-01-18 18:53:16 +00002038
John McCallaa81e162009-12-01 22:10:20 +00002039 // If this is known to be an instance access, go ahead and build a
2040 // 'this' expression now.
John McCallea1471e2010-05-20 01:18:31 +00002041 DeclContext *DC = getFunctionLevelDeclContext();
2042 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCallaa81e162009-12-01 22:10:20 +00002043 Expr *This = 0; // null signifies implicit access
2044 if (IsKnownInstance) {
Douglas Gregor828a1972010-01-07 23:12:05 +00002045 SourceLocation Loc = R.getNameLoc();
2046 if (SS.getRange().isValid())
2047 Loc = SS.getRange().getBegin();
2048 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
Douglas Gregor88a35142008-12-22 05:46:06 +00002049 }
2050
John McCall9ae2f072010-08-23 23:25:46 +00002051 return BuildMemberReferenceExpr(This, ThisType,
John McCallaa81e162009-12-01 22:10:20 +00002052 /*OpLoc*/ SourceLocation(),
2053 /*IsArrow*/ true,
John McCallc2233c52010-01-15 08:34:02 +00002054 SS,
2055 /*FirstQualifierInScope*/ 0,
2056 R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00002057}
2058
John McCallf7a1a742009-11-24 19:00:30 +00002059bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002060 const LookupResult &R,
2061 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002062 // Only when used directly as the postfix-expression of a call.
2063 if (!HasTrailingLParen)
2064 return false;
2065
2066 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002067 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002068 return false;
2069
2070 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00002071 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002072 return false;
2073
2074 // Turn off ADL when we find certain kinds of declarations during
2075 // normal lookup:
2076 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2077 NamedDecl *D = *I;
2078
2079 // C++0x [basic.lookup.argdep]p3:
2080 // -- a declaration of a class member
2081 // Since using decls preserve this property, we check this on the
2082 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002083 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002084 return false;
2085
2086 // C++0x [basic.lookup.argdep]p3:
2087 // -- a block-scope function declaration that is not a
2088 // using-declaration
2089 // NOTE: we also trigger this for function templates (in fact, we
2090 // don't check the decl type at all, since all other decl types
2091 // turn off ADL anyway).
2092 if (isa<UsingShadowDecl>(D))
2093 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2094 else if (D->getDeclContext()->isFunctionOrMethod())
2095 return false;
2096
2097 // C++0x [basic.lookup.argdep]p3:
2098 // -- a declaration that is neither a function or a function
2099 // template
2100 // And also for builtin functions.
2101 if (isa<FunctionDecl>(D)) {
2102 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2103
2104 // But also builtin functions.
2105 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2106 return false;
2107 } else if (!isa<FunctionTemplateDecl>(D))
2108 return false;
2109 }
2110
2111 return true;
2112}
2113
2114
John McCallba135432009-11-21 08:51:07 +00002115/// Diagnoses obvious problems with the use of the given declaration
2116/// as an expression. This is only actually called for lookups that
2117/// were not overloaded, and it doesn't promise that the declaration
2118/// will in fact be used.
2119static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2120 if (isa<TypedefDecl>(D)) {
2121 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2122 return true;
2123 }
2124
2125 if (isa<ObjCInterfaceDecl>(D)) {
2126 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2127 return true;
2128 }
2129
2130 if (isa<NamespaceDecl>(D)) {
2131 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2132 return true;
2133 }
2134
2135 return false;
2136}
2137
John McCall60d7b3a2010-08-24 06:29:42 +00002138ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002139Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002140 LookupResult &R,
2141 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002142 // If this is a single, fully-resolved result and we don't need ADL,
2143 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002144 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002145 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2146 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002147
2148 // We only need to check the declaration if there's exactly one
2149 // result, because in the overloaded case the results can only be
2150 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002151 if (R.isSingleResult() &&
2152 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002153 return ExprError();
2154
John McCallc373d482010-01-27 01:50:18 +00002155 // Otherwise, just build an unresolved lookup expression. Suppress
2156 // any lookup-related diagnostics; we'll hash these out later, when
2157 // we've picked a target.
2158 R.suppressDiagnostics();
2159
John McCallba135432009-11-21 08:51:07 +00002160 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002161 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00002162 (NestedNameSpecifier*) SS.getScopeRep(),
Abramo Bagnara25777432010-08-11 22:01:17 +00002163 SS.getRange(), R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002164 NeedsADL, R.isOverloadedResult(),
2165 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002166
2167 return Owned(ULE);
2168}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002169
John McCallf89e55a2010-11-18 06:31:45 +00002170static ExprValueKind getValueKindForDecl(ASTContext &Context,
2171 const ValueDecl *D) {
John McCall09431682010-11-18 19:01:18 +00002172 // FIXME: It's not clear to me why NonTypeTemplateParmDecl is a VarDecl.
2173 if (isa<VarDecl>(D) && !isa<NonTypeTemplateParmDecl>(D)) return VK_LValue;
2174 if (isa<FieldDecl>(D)) return VK_LValue;
John McCallf89e55a2010-11-18 06:31:45 +00002175 if (!Context.getLangOptions().CPlusPlus) return VK_RValue;
2176 if (isa<FunctionDecl>(D)) {
2177 if (isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance())
2178 return VK_RValue;
2179 return VK_LValue;
2180 }
2181 return Expr::getValueKindForType(D->getType());
2182}
2183
John McCallba135432009-11-21 08:51:07 +00002184
2185/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002186ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002187Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002188 const DeclarationNameInfo &NameInfo,
2189 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002190 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002191 assert(!isa<FunctionTemplateDecl>(D) &&
2192 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002193
Abramo Bagnara25777432010-08-11 22:01:17 +00002194 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002195 if (CheckDeclInExpr(*this, Loc, D))
2196 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002197
Douglas Gregor9af2f522009-12-01 16:58:18 +00002198 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2199 // Specifically diagnose references to class templates that are missing
2200 // a template argument list.
2201 Diag(Loc, diag::err_template_decl_ref)
2202 << Template << SS.getRange();
2203 Diag(Template->getLocation(), diag::note_template_decl_here);
2204 return ExprError();
2205 }
2206
2207 // Make sure that we're referring to a value.
2208 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2209 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002210 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002211 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002212 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002213 return ExprError();
2214 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002215
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002216 // Check whether this declaration can be used. Note that we suppress
2217 // this check when we're going to perform argument-dependent lookup
2218 // on this function name, because this might not be the function
2219 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002220 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002221 return ExprError();
2222
Steve Naroffdd972f22008-09-05 22:11:13 +00002223 // Only create DeclRefExpr's for valid Decl's.
2224 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002225 return ExprError();
2226
Francois Pichet87c2e122010-11-21 06:08:52 +00002227 // Handle anonymous.
2228 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(VD))
2229 return BuildAnonymousStructUnionMemberReference(Loc, FD);
2230
John McCallf89e55a2010-11-18 06:31:45 +00002231 ExprValueKind VK = getValueKindForDecl(Context, VD);
2232
Chris Lattner639e2d32008-10-20 05:16:36 +00002233 // If the identifier reference is inside a block, and it refers to a value
2234 // that is outside the block, create a BlockDeclRefExpr instead of a
2235 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2236 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00002237 //
Chris Lattner639e2d32008-10-20 05:16:36 +00002238 // We do not do this for things like enum constants, global variables, etc,
2239 // as they do not get snapshotted.
2240 //
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002241 if (getCurBlock() &&
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00002242 ShouldSnapshotBlockValueReference(*this, getCurBlock(), VD)) {
Mike Stump0d6fd572010-01-05 02:56:35 +00002243 if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
2244 Diag(Loc, diag::err_ref_vm_type);
2245 Diag(D->getLocation(), diag::note_declared_at);
2246 return ExprError();
2247 }
2248
Fariborz Jahanian8596bbe2010-03-16 23:39:51 +00002249 if (VD->getType()->isArrayType()) {
Mike Stump28497342010-01-05 03:10:36 +00002250 Diag(Loc, diag::err_ref_array_type);
2251 Diag(D->getLocation(), diag::note_declared_at);
2252 return ExprError();
2253 }
2254
Douglas Gregore0762c92009-06-19 23:52:42 +00002255 MarkDeclarationReferenced(Loc, VD);
Eli Friedman5fdeae12009-03-22 23:00:19 +00002256 QualType ExprTy = VD->getType().getNonReferenceType();
John McCallf89e55a2010-11-18 06:31:45 +00002257
Steve Naroff090276f2008-10-10 01:28:17 +00002258 // The BlocksAttr indicates the variable is bound by-reference.
Fariborz Jahaniane2204552010-11-16 19:29:39 +00002259 bool byrefVar = (VD->getAttr<BlocksAttr>() != 0);
Fariborz Jahanian52bc56a2010-07-12 17:26:57 +00002260 QualType T = VD->getType();
Fariborz Jahaniane2204552010-11-16 19:29:39 +00002261 BlockDeclRefExpr *BDRE;
2262
2263 if (!byrefVar) {
2264 // This is to record that a 'const' was actually synthesize and added.
2265 bool constAdded = !ExprTy.isConstQualified();
2266 // Variable will be bound by-copy, make it const within the closure.
2267 ExprTy.addConst();
John McCallf89e55a2010-11-18 06:31:45 +00002268 BDRE = new (Context) BlockDeclRefExpr(VD, ExprTy, VK,
2269 Loc, false, constAdded);
Fariborz Jahaniane2204552010-11-16 19:29:39 +00002270 }
2271 else
John McCallf89e55a2010-11-18 06:31:45 +00002272 BDRE = new (Context) BlockDeclRefExpr(VD, ExprTy, VK, Loc, true);
Fariborz Jahaniane2204552010-11-16 19:29:39 +00002273
Fariborz Jahanian833f42e2010-07-09 22:21:32 +00002274 if (getLangOptions().CPlusPlus) {
2275 if (!T->isDependentType() && !T->isReferenceType()) {
2276 Expr *E = new (Context)
2277 DeclRefExpr(const_cast<ValueDecl*>(BDRE->getDecl()), T,
John McCallf89e55a2010-11-18 06:31:45 +00002278 VK, SourceLocation());
Fariborz Jahaniane27e9d62010-11-11 00:11:38 +00002279 if (T->getAs<RecordType>())
2280 if (!T->isUnionType()) {
2281 ExprResult Res = PerformCopyInitialization(
Fariborz Jahanian833f42e2010-07-09 22:21:32 +00002282 InitializedEntity::InitializeBlock(VD->getLocation(),
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002283 T, false),
Fariborz Jahanian833f42e2010-07-09 22:21:32 +00002284 SourceLocation(),
2285 Owned(E));
Fariborz Jahaniane27e9d62010-11-11 00:11:38 +00002286 if (!Res.isInvalid()) {
Douglas Gregor53c374f2010-12-07 00:41:46 +00002287 Res = MaybeCreateExprWithCleanups(Res);
Fariborz Jahaniane27e9d62010-11-11 00:11:38 +00002288 Expr *Init = Res.takeAs<Expr>();
2289 BDRE->setCopyConstructorExpr(Init);
2290 }
Fariborz Jahanian833f42e2010-07-09 22:21:32 +00002291 }
Fariborz Jahanian59da45a2010-06-04 21:35:44 +00002292 }
2293 }
2294 return Owned(BDRE);
Steve Naroff090276f2008-10-10 01:28:17 +00002295 }
2296 // If this reference is not in a block or if the referenced variable is
2297 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +00002298
John McCallf89e55a2010-11-18 06:31:45 +00002299 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00002300 NameInfo, &SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00002301}
2302
John McCall60d7b3a2010-08-24 06:29:42 +00002303ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Sebastian Redlcd965b92009-01-18 18:53:16 +00002304 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002305 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002306
Reid Spencer5f016e22007-07-11 17:01:13 +00002307 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00002308 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002309 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2310 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2311 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002312 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002313
Chris Lattnerfa28b302008-01-12 08:14:25 +00002314 // Pre-defined identifiers are of type char[x], where x is the length of the
2315 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002316
Anders Carlsson3a082d82009-09-08 18:24:21 +00002317 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002318 if (!currentDecl && getCurBlock())
2319 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002320 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002321 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002322 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002323 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002324
Anders Carlsson773f3972009-09-11 01:22:35 +00002325 QualType ResTy;
2326 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2327 ResTy = Context.DependentTy;
2328 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002329 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002330
Anders Carlsson773f3972009-09-11 01:22:35 +00002331 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00002332 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002333 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2334 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002335 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002336}
2337
John McCall60d7b3a2010-08-24 06:29:42 +00002338ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002339 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002340 bool Invalid = false;
2341 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2342 if (Invalid)
2343 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002344
Benjamin Kramerddeea562010-02-27 13:44:12 +00002345 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2346 PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00002347 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002348 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002349
Chris Lattnere8337df2009-12-30 21:19:39 +00002350 QualType Ty;
2351 if (!getLangOptions().CPlusPlus)
2352 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2353 else if (Literal.isWide())
2354 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedman136b0cd2010-02-03 18:21:45 +00002355 else if (Literal.isMultiChar())
2356 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002357 else
2358 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002359
Sebastian Redle91b3bc2009-01-20 22:23:13 +00002360 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2361 Literal.isWide(),
Chris Lattnere8337df2009-12-30 21:19:39 +00002362 Ty, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002363}
2364
John McCall60d7b3a2010-08-24 06:29:42 +00002365ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002366 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00002367 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2368 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002369 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00002370 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002371 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00002372 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002373 }
Ted Kremenek28396602009-01-13 23:19:12 +00002374
Reid Spencer5f016e22007-07-11 17:01:13 +00002375 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002376 // Add padding so that NumericLiteralParser can overread by one character.
2377 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002378 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002379
Reid Spencer5f016e22007-07-11 17:01:13 +00002380 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002381 bool Invalid = false;
2382 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2383 if (Invalid)
2384 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002385
Mike Stump1eb44332009-09-09 15:08:12 +00002386 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002387 Tok.getLocation(), PP);
2388 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002389 return ExprError();
2390
Chris Lattner5d661452007-08-26 03:42:43 +00002391 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002392
Chris Lattner5d661452007-08-26 03:42:43 +00002393 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002394 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002395 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002396 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002397 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002398 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002399 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002400 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002401
2402 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2403
John McCall94c939d2009-12-24 09:08:04 +00002404 using llvm::APFloat;
2405 APFloat Val(Format);
2406
2407 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00002408
2409 // Overflow is always an error, but underflow is only an error if
2410 // we underflowed to zero (APFloat reports denormals as underflow).
2411 if ((result & APFloat::opOverflow) ||
2412 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00002413 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002414 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00002415 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00002416 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00002417 APFloat::getLargest(Format).toString(buffer);
2418 } else {
John McCall2a0d7572010-02-26 23:35:57 +00002419 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00002420 APFloat::getSmallest(Format).toString(buffer);
2421 }
2422
2423 Diag(Tok.getLocation(), diagnostic)
2424 << Ty
2425 << llvm::StringRef(buffer.data(), buffer.size());
2426 }
2427
2428 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002429 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002430
Peter Collingbourne09821362010-12-04 01:50:56 +00002431 if (getLangOptions().SinglePrecisionConstants && Ty == Context.DoubleTy)
2432 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2433
Chris Lattner5d661452007-08-26 03:42:43 +00002434 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002435 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002436 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002437 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002438
Neil Boothb9449512007-08-29 22:00:19 +00002439 // long long is a C99 feature.
2440 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00002441 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00002442 Diag(Tok.getLocation(), diag::ext_longlong);
2443
Reid Spencer5f016e22007-07-11 17:01:13 +00002444 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00002445 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002446
Reid Spencer5f016e22007-07-11 17:01:13 +00002447 if (Literal.GetIntegerValue(ResultVal)) {
2448 // If this value didn't fit into uintmax_t, warn and force to ull.
2449 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002450 Ty = Context.UnsignedLongLongTy;
2451 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002452 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002453 } else {
2454 // If this value fits into a ULL, try to figure out what else it fits into
2455 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002456
Reid Spencer5f016e22007-07-11 17:01:13 +00002457 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2458 // be an unsigned int.
2459 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2460
2461 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002462 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002463 if (!Literal.isLong && !Literal.isLongLong) {
2464 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002465 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002466
Reid Spencer5f016e22007-07-11 17:01:13 +00002467 // Does it fit in a unsigned int?
2468 if (ResultVal.isIntN(IntSize)) {
2469 // Does it fit in a signed int?
2470 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002471 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002472 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002473 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002474 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002475 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002476 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002477
Reid Spencer5f016e22007-07-11 17:01:13 +00002478 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002479 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002480 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002481
Reid Spencer5f016e22007-07-11 17:01:13 +00002482 // Does it fit in a unsigned long?
2483 if (ResultVal.isIntN(LongSize)) {
2484 // Does it fit in a signed long?
2485 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002486 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002487 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002488 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002489 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002490 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002491 }
2492
Reid Spencer5f016e22007-07-11 17:01:13 +00002493 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002494 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002495 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002496
Reid Spencer5f016e22007-07-11 17:01:13 +00002497 // Does it fit in a unsigned long long?
2498 if (ResultVal.isIntN(LongLongSize)) {
2499 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002500 // To be compatible with MSVC, hex integer literals ending with the
2501 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002502 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2503 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002504 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002505 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002506 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002507 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002508 }
2509 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002510
Reid Spencer5f016e22007-07-11 17:01:13 +00002511 // If we still couldn't decide a type, we probably have something that
2512 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002513 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002514 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002515 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002516 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002517 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002518
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002519 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002520 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002521 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002522 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002523 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002524
Chris Lattner5d661452007-08-26 03:42:43 +00002525 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2526 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002527 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002528 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002529
2530 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002531}
2532
John McCall60d7b3a2010-08-24 06:29:42 +00002533ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCall9ae2f072010-08-23 23:25:46 +00002534 SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002535 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002536 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002537}
2538
2539/// The UsualUnaryConversions() function is *not* called by this routine.
2540/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00002541bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00002542 SourceLocation OpLoc,
John McCall2a984ca2010-10-12 00:20:44 +00002543 SourceRange ExprRange,
Sebastian Redl05189992008-11-11 17:56:53 +00002544 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00002545 if (exprType->isDependentType())
2546 return false;
2547
Sebastian Redl5d484e82009-11-23 17:18:46 +00002548 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2549 // the result is the size of the referenced type."
2550 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2551 // result shall be the alignment of the referenced type."
2552 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2553 exprType = Ref->getPointeeType();
2554
Reid Spencer5f016e22007-07-11 17:01:13 +00002555 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00002556 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002557 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00002558 if (isSizeof)
2559 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2560 return false;
2561 }
Mike Stump1eb44332009-09-09 15:08:12 +00002562
Chris Lattner1efaa952009-04-24 00:30:45 +00002563 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00002564 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002565 Diag(OpLoc, diag::ext_sizeof_void_type)
2566 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00002567 return false;
2568 }
Mike Stump1eb44332009-09-09 15:08:12 +00002569
Chris Lattner1efaa952009-04-24 00:30:45 +00002570 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00002571 PDiag(diag::err_sizeof_alignof_incomplete_type)
2572 << int(!isSizeof) << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00002573 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002574
Chris Lattner1efaa952009-04-24 00:30:45 +00002575 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCallc12c5bb2010-05-15 11:32:37 +00002576 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002577 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00002578 << exprType << isSizeof << ExprRange;
2579 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00002580 }
Mike Stump1eb44332009-09-09 15:08:12 +00002581
Chris Lattner1efaa952009-04-24 00:30:45 +00002582 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002583}
2584
John McCall2a984ca2010-10-12 00:20:44 +00002585static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2586 SourceRange ExprRange) {
Chris Lattner31e21e02009-01-24 20:17:12 +00002587 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00002588
Mike Stump1eb44332009-09-09 15:08:12 +00002589 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00002590 if (isa<DeclRefExpr>(E))
2591 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00002592
2593 // Cannot know anything else if the expression is dependent.
2594 if (E->isTypeDependent())
2595 return false;
2596
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002597 if (E->getBitField()) {
John McCall2a984ca2010-10-12 00:20:44 +00002598 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002599 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00002600 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002601
2602 // Alignment of a field access is always okay, so long as it isn't a
2603 // bit-field.
2604 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00002605 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002606 return false;
2607
John McCall2a984ca2010-10-12 00:20:44 +00002608 return S.CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
Chris Lattner31e21e02009-01-24 20:17:12 +00002609}
2610
Douglas Gregorba498172009-03-13 21:01:28 +00002611/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002612ExprResult
John McCalla93c9342009-12-07 02:54:59 +00002613Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall5ab75172009-11-04 07:28:41 +00002614 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00002615 bool isSizeOf, SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00002616 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00002617 return ExprError();
2618
John McCalla93c9342009-12-07 02:54:59 +00002619 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00002620
Douglas Gregorba498172009-03-13 21:01:28 +00002621 if (!T->isDependentType() &&
2622 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2623 return ExprError();
2624
2625 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCalla93c9342009-12-07 02:54:59 +00002626 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00002627 Context.getSizeType(), OpLoc,
2628 R.getEnd()));
2629}
2630
2631/// \brief Build a sizeof or alignof expression given an expression
2632/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002633ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00002634Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00002635 bool isSizeOf, SourceRange R) {
2636 // Verify that the operand is valid.
2637 bool isInvalid = false;
2638 if (E->isTypeDependent()) {
2639 // Delay type-checking for type-dependent expressions.
2640 } else if (!isSizeOf) {
John McCall2a984ca2010-10-12 00:20:44 +00002641 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002642 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00002643 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2644 isInvalid = true;
John McCall2cd11fe2010-10-12 02:09:17 +00002645 } else if (E->getType()->isPlaceholderType()) {
2646 ExprResult PE = CheckPlaceholderExpr(E, OpLoc);
2647 if (PE.isInvalid()) return ExprError();
2648 return CreateSizeOfAlignOfExpr(PE.take(), OpLoc, isSizeOf, R);
Douglas Gregorba498172009-03-13 21:01:28 +00002649 } else {
2650 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2651 }
2652
2653 if (isInvalid)
2654 return ExprError();
2655
2656 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2657 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2658 Context.getSizeType(), OpLoc,
2659 R.getEnd()));
2660}
2661
Sebastian Redl05189992008-11-11 17:56:53 +00002662/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2663/// the same for @c alignof and @c __alignof
2664/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00002665ExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00002666Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2667 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002668 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002669 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002670
Sebastian Redl05189992008-11-11 17:56:53 +00002671 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00002672 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00002673 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
John McCalla93c9342009-12-07 02:54:59 +00002674 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00002675 }
Sebastian Redl05189992008-11-11 17:56:53 +00002676
Douglas Gregorba498172009-03-13 21:01:28 +00002677 Expr *ArgEx = (Expr *)TyOrEx;
John McCall60d7b3a2010-08-24 06:29:42 +00002678 ExprResult Result
Douglas Gregorba498172009-03-13 21:01:28 +00002679 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2680
Douglas Gregorba498172009-03-13 21:01:28 +00002681 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002682}
2683
John McCall09431682010-11-18 19:01:18 +00002684static QualType CheckRealImagOperand(Sema &S, Expr *&V, SourceLocation Loc,
2685 bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00002686 if (V->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00002687 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002688
John McCallf6a16482010-12-04 03:47:34 +00002689 // _Real and _Imag are only l-values for normal l-values.
2690 if (V->getObjectKind() != OK_Ordinary)
John McCall409fa9a2010-12-06 20:48:59 +00002691 S.DefaultLvalueConversion(V);
John McCallf6a16482010-12-04 03:47:34 +00002692
Chris Lattnercc26ed72007-08-26 05:39:26 +00002693 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00002694 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00002695 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002696
Chris Lattnercc26ed72007-08-26 05:39:26 +00002697 // Otherwise they pass through real integer and floating point types here.
2698 if (V->getType()->isArithmeticType())
2699 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002700
John McCall2cd11fe2010-10-12 02:09:17 +00002701 // Test for placeholders.
John McCall09431682010-11-18 19:01:18 +00002702 ExprResult PR = S.CheckPlaceholderExpr(V, Loc);
John McCall2cd11fe2010-10-12 02:09:17 +00002703 if (PR.isInvalid()) return QualType();
2704 if (PR.take() != V) {
2705 V = PR.take();
John McCall09431682010-11-18 19:01:18 +00002706 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall2cd11fe2010-10-12 02:09:17 +00002707 }
2708
Chris Lattnercc26ed72007-08-26 05:39:26 +00002709 // Reject anything else.
John McCall09431682010-11-18 19:01:18 +00002710 S.Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
Chris Lattnerba27e2a2009-02-17 08:12:06 +00002711 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00002712 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00002713}
2714
2715
Reid Spencer5f016e22007-07-11 17:01:13 +00002716
John McCall60d7b3a2010-08-24 06:29:42 +00002717ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00002718Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002719 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00002720 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00002721 switch (Kind) {
2722 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00002723 case tok::plusplus: Opc = UO_PostInc; break;
2724 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002725 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002726
John McCall9ae2f072010-08-23 23:25:46 +00002727 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00002728}
2729
John McCall09431682010-11-18 19:01:18 +00002730/// Expressions of certain arbitrary types are forbidden by C from
2731/// having l-value type. These are:
2732/// - 'void', but not qualified void
2733/// - function types
2734///
2735/// The exact rule here is C99 6.3.2.1:
2736/// An lvalue is an expression with an object type or an incomplete
2737/// type other than void.
2738static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
2739 return ((T->isVoidType() && !T.hasQualifiers()) ||
2740 T->isFunctionType());
2741}
2742
John McCall60d7b3a2010-08-24 06:29:42 +00002743ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002744Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2745 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00002746 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00002747 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00002748 if (Result.isInvalid()) return ExprError();
2749 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00002750
John McCall9ae2f072010-08-23 23:25:46 +00002751 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00002752
Douglas Gregor337c6b92008-11-19 17:17:41 +00002753 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002754 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002755 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00002756 Context.DependentTy,
2757 VK_LValue, OK_Ordinary,
2758 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002759 }
2760
Mike Stump1eb44332009-09-09 15:08:12 +00002761 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00002762 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00002763 LHSExp->getType()->isEnumeralType() ||
2764 RHSExp->getType()->isRecordType() ||
2765 RHSExp->getType()->isEnumeralType())) {
John McCall9ae2f072010-08-23 23:25:46 +00002766 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00002767 }
2768
John McCall9ae2f072010-08-23 23:25:46 +00002769 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00002770}
2771
2772
John McCall60d7b3a2010-08-24 06:29:42 +00002773ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002774Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2775 Expr *Idx, SourceLocation RLoc) {
2776 Expr *LHSExp = Base;
2777 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00002778
Chris Lattner12d9ff62007-07-16 00:14:47 +00002779 // Perform default conversions.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002780 if (!LHSExp->getType()->getAs<VectorType>())
2781 DefaultFunctionArrayLvalueConversion(LHSExp);
2782 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002783
Chris Lattner12d9ff62007-07-16 00:14:47 +00002784 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00002785 ExprValueKind VK = VK_LValue;
2786 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00002787
Reid Spencer5f016e22007-07-11 17:01:13 +00002788 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002789 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00002790 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00002791 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00002792 Expr *BaseExpr, *IndexExpr;
2793 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00002794 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2795 BaseExpr = LHSExp;
2796 IndexExpr = RHSExp;
2797 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00002798 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00002799 BaseExpr = LHSExp;
2800 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002801 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002802 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00002803 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00002804 BaseExpr = RHSExp;
2805 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002806 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002807 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00002808 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002809 BaseExpr = LHSExp;
2810 IndexExpr = RHSExp;
2811 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002812 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00002813 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002814 // Handle the uncommon case of "123[Ptr]".
2815 BaseExpr = RHSExp;
2816 IndexExpr = LHSExp;
2817 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00002818 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00002819 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00002820 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00002821 VK = LHSExp->getValueKind();
2822 if (VK != VK_RValue)
2823 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00002824
Chris Lattner12d9ff62007-07-16 00:14:47 +00002825 // FIXME: need to deal with const...
2826 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002827 } else if (LHSTy->isArrayType()) {
2828 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00002829 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002830 // wasn't promoted because of the C90 rule that doesn't
2831 // allow promoting non-lvalue arrays. Warn, then
2832 // force the promotion here.
2833 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2834 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002835 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
John McCall2de56d12010-08-25 11:45:40 +00002836 CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002837 LHSTy = LHSExp->getType();
2838
2839 BaseExpr = LHSExp;
2840 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00002841 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002842 } else if (RHSTy->isArrayType()) {
2843 // Same as previous, except for 123[f().a] case
2844 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2845 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002846 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
John McCall2de56d12010-08-25 11:45:40 +00002847 CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002848 RHSTy = RHSExp->getType();
2849
2850 BaseExpr = RHSExp;
2851 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00002852 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002853 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00002854 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2855 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002856 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002857 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00002858 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00002859 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2860 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002861
Daniel Dunbar7e88a602009-09-17 06:31:17 +00002862 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00002863 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2864 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00002865 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2866
Douglas Gregore7450f52009-03-24 19:52:54 +00002867 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00002868 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2869 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00002870 // incomplete types are not object types.
2871 if (ResultType->isFunctionType()) {
2872 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2873 << ResultType << BaseExpr->getSourceRange();
2874 return ExprError();
2875 }
Mike Stump1eb44332009-09-09 15:08:12 +00002876
Abramo Bagnara46358452010-09-13 06:50:07 +00002877 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
2878 // GNU extension: subscripting on pointer to void
2879 Diag(LLoc, diag::ext_gnu_void_ptr)
2880 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00002881
2882 // C forbids expressions of unqualified void type from being l-values.
2883 // See IsCForbiddenLValueType.
2884 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00002885 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002886 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002887 PDiag(diag::err_subscript_incomplete_type)
2888 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00002889 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002890
Chris Lattner1efaa952009-04-24 00:30:45 +00002891 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00002892 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002893 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2894 << ResultType << BaseExpr->getSourceRange();
2895 return ExprError();
2896 }
Mike Stump1eb44332009-09-09 15:08:12 +00002897
John McCall09431682010-11-18 19:01:18 +00002898 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
2899 !IsCForbiddenLValueType(Context, ResultType));
2900
Mike Stumpeed9cac2009-02-19 03:04:26 +00002901 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00002902 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002903}
2904
John McCall09431682010-11-18 19:01:18 +00002905/// Check an ext-vector component access expression.
2906///
2907/// VK should be set in advance to the value kind of the base
2908/// expression.
2909static QualType
2910CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
2911 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002912 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00002913 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2914 // see FIXME there.
2915 //
2916 // FIXME: This logic can be greatly simplified by splitting it along
2917 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00002918 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00002919
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002920 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00002921 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002922
Mike Stumpeed9cac2009-02-19 03:04:26 +00002923 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00002924 // special names that indicate a subset of exactly half the elements are
2925 // to be selected.
2926 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002927
Nate Begeman353417a2009-01-18 01:47:54 +00002928 // This flag determines whether or not CompName has an 's' char prefix,
2929 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00002930 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00002931
John McCall09431682010-11-18 19:01:18 +00002932 bool HasRepeated = false;
2933 bool HasIndex[16] = {};
2934
2935 int Idx;
2936
Nate Begeman8a997642008-05-09 06:41:27 +00002937 // Check that we've found one of the special components, or that the component
2938 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002939 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00002940 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2941 HalvingSwizzle = true;
John McCall09431682010-11-18 19:01:18 +00002942 } else if (!HexSwizzle &&
2943 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
2944 do {
2945 if (HasIndex[Idx]) HasRepeated = true;
2946 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00002947 compStr++;
John McCall09431682010-11-18 19:01:18 +00002948 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
2949 } else {
2950 if (HexSwizzle) compStr++;
2951 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
2952 if (HasIndex[Idx]) HasRepeated = true;
2953 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00002954 compStr++;
John McCall09431682010-11-18 19:01:18 +00002955 }
Chris Lattner88dca042007-08-02 22:33:49 +00002956 }
Nate Begeman353417a2009-01-18 01:47:54 +00002957
Mike Stumpeed9cac2009-02-19 03:04:26 +00002958 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002959 // We didn't get to the end of the string. This means the component names
2960 // didn't come from the same set *or* we encountered an illegal name.
John McCall09431682010-11-18 19:01:18 +00002961 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00002962 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002963 return QualType();
2964 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002965
Nate Begeman353417a2009-01-18 01:47:54 +00002966 // Ensure no component accessor exceeds the width of the vector type it
2967 // operates on.
2968 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00002969 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002970
2971 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002972 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002973
2974 while (*compStr) {
2975 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall09431682010-11-18 19:01:18 +00002976 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begeman353417a2009-01-18 01:47:54 +00002977 << baseType << SourceRange(CompLoc);
2978 return QualType();
2979 }
2980 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002981 }
Nate Begeman8a997642008-05-09 06:41:27 +00002982
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002983 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002984 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002985 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00002986 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00002987 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman0479a0b2009-12-15 18:13:04 +00002988 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00002989 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00002990 if (HexSwizzle)
2991 CompSize--;
2992
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002993 if (CompSize == 1)
2994 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002995
John McCall09431682010-11-18 19:01:18 +00002996 if (HasRepeated) VK = VK_RValue;
2997
2998 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002999 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00003000 // diagostics look bad. We want extended vector types to appear built-in.
John McCall09431682010-11-18 19:01:18 +00003001 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3002 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3003 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00003004 }
3005 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003006}
3007
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003008static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00003009 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003010 const Selector &Sel,
3011 ASTContext &Context) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003012 if (Member)
3013 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3014 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003015 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003016 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00003017
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003018 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3019 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003020 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3021 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003022 return D;
3023 }
3024 return 0;
3025}
3026
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003027static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3028 IdentifierInfo *Member,
3029 const Selector &Sel,
3030 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003031 // Check protocols on qualified interfaces.
3032 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003033 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003034 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003035 if (Member)
3036 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3037 GDecl = PD;
3038 break;
3039 }
3040 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003041 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003042 GDecl = OMD;
3043 break;
3044 }
3045 }
3046 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003047 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003048 E = QIdTy->qual_end(); I != E; ++I) {
3049 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003050 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3051 Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003052 if (GDecl)
3053 return GDecl;
3054 }
3055 }
3056 return GDecl;
3057}
Chris Lattner76a642f2009-02-15 22:43:40 +00003058
John McCall60d7b3a2010-08-24 06:29:42 +00003059ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003060Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCallaa81e162009-12-01 22:10:20 +00003061 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00003062 const CXXScopeSpec &SS,
3063 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003064 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003065 const TemplateArgumentListInfo *TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00003066 // Even in dependent contexts, try to diagnose base expressions with
3067 // obviously wrong types, e.g.:
3068 //
3069 // T* t;
3070 // t.f;
3071 //
3072 // In Obj-C++, however, the above expression is valid, since it could be
3073 // accessing the 'f' property if T is an Obj-C interface. The extra check
3074 // allows this, while still reporting an error if T is a struct pointer.
3075 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00003076 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00003077 if (PT && (!getLangOptions().ObjC1 ||
3078 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00003079 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnara25777432010-08-11 22:01:17 +00003080 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00003081 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00003082 return ExprError();
3083 }
3084 }
3085
Abramo Bagnara25777432010-08-11 22:01:17 +00003086 assert(BaseType->isDependentType() ||
3087 NameInfo.getName().isDependentName() ||
Douglas Gregor01e56ae2010-04-12 20:54:26 +00003088 isDependentScopeSpecifier(SS));
John McCall129e2df2009-11-30 22:42:35 +00003089
3090 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3091 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00003092 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003093 IsArrow, OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003094 SS.getScopeRep(),
John McCall129e2df2009-11-30 22:42:35 +00003095 SS.getRange(),
3096 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003097 NameInfo, TemplateArgs));
John McCall129e2df2009-11-30 22:42:35 +00003098}
3099
3100/// We know that the given qualified member reference points only to
3101/// declarations which do not belong to the static type of the base
3102/// expression. Diagnose the problem.
3103static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3104 Expr *BaseExpr,
3105 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003106 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003107 const LookupResult &R) {
John McCall2f841ba2009-12-02 03:53:29 +00003108 // If this is an implicit member access, use a different set of
3109 // diagnostics.
3110 if (!BaseExpr)
3111 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall129e2df2009-11-30 22:42:35 +00003112
John McCall110acc12010-04-27 01:43:38 +00003113 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_of_unrelated)
3114 << SS.getRange() << R.getRepresentativeDecl() << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00003115}
3116
3117// Check whether the declarations we found through a nested-name
3118// specifier in a member expression are actually members of the base
3119// type. The restriction here is:
3120//
3121// C++ [expr.ref]p2:
3122// ... In these cases, the id-expression shall name a
3123// member of the class or of one of its base classes.
3124//
3125// So it's perfectly legitimate for the nested-name specifier to name
3126// an unrelated class, and for us to find an overload set including
3127// decls from classes which are not superclasses, as long as the decl
3128// we actually pick through overload resolution is from a superclass.
3129bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3130 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003131 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003132 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00003133 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3134 if (!BaseRT) {
3135 // We can't check this yet because the base type is still
3136 // dependent.
3137 assert(BaseType->isDependentType());
3138 return false;
3139 }
3140 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00003141
3142 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00003143 // If this is an implicit member reference and we find a
3144 // non-instance member, it's not an error.
John McCall161755a2010-04-06 21:38:20 +00003145 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCallaa81e162009-12-01 22:10:20 +00003146 return false;
John McCall129e2df2009-11-30 22:42:35 +00003147
John McCallaa81e162009-12-01 22:10:20 +00003148 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman02463762010-07-27 20:51:02 +00003149 DeclContext *DC = (*I)->getDeclContext();
3150 while (DC->isTransparentContext())
3151 DC = DC->getParent();
John McCallaa81e162009-12-01 22:10:20 +00003152
Douglas Gregor9d4bb942010-07-28 22:27:52 +00003153 if (!DC->isRecord())
3154 continue;
3155
John McCallaa81e162009-12-01 22:10:20 +00003156 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman02463762010-07-27 20:51:02 +00003157 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCallaa81e162009-12-01 22:10:20 +00003158
3159 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3160 return false;
3161 }
3162
John McCall2f841ba2009-12-02 03:53:29 +00003163 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCallaa81e162009-12-01 22:10:20 +00003164 return true;
3165}
3166
3167static bool
3168LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3169 SourceRange BaseRange, const RecordType *RTy,
John McCallad00b772010-06-16 08:42:20 +00003170 SourceLocation OpLoc, CXXScopeSpec &SS,
3171 bool HasTemplateArgs) {
John McCallaa81e162009-12-01 22:10:20 +00003172 RecordDecl *RDecl = RTy->getDecl();
3173 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003174 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCallaa81e162009-12-01 22:10:20 +00003175 << BaseRange))
3176 return true;
3177
John McCallad00b772010-06-16 08:42:20 +00003178 if (HasTemplateArgs) {
3179 // LookupTemplateName doesn't expect these both to exist simultaneously.
3180 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3181
3182 bool MOUS;
3183 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3184 return false;
3185 }
3186
John McCallaa81e162009-12-01 22:10:20 +00003187 DeclContext *DC = RDecl;
3188 if (SS.isSet()) {
3189 // If the member name was a qualified-id, look into the
3190 // nested-name-specifier.
3191 DC = SemaRef.computeDeclContext(SS, false);
3192
John McCall77bb1aa2010-05-01 00:40:08 +00003193 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCall2f841ba2009-12-02 03:53:29 +00003194 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3195 << SS.getRange() << DC;
3196 return true;
3197 }
3198
John McCallaa81e162009-12-01 22:10:20 +00003199 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003200
John McCallaa81e162009-12-01 22:10:20 +00003201 if (!isa<TypeDecl>(DC)) {
3202 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3203 << DC << SS.getRange();
3204 return true;
John McCall129e2df2009-11-30 22:42:35 +00003205 }
3206 }
3207
John McCallaa81e162009-12-01 22:10:20 +00003208 // The record definition is complete, now look up the member.
3209 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00003210
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003211 if (!R.empty())
3212 return false;
3213
3214 // We didn't find anything with the given name, so try to correct
3215 // for typos.
3216 DeclarationName Name = R.getLookupName();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003217 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00003218 !R.empty() &&
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003219 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3220 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3221 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00003222 << FixItHint::CreateReplacement(R.getNameLoc(),
3223 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00003224 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3225 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3226 << ND->getDeclName();
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003227 return false;
3228 } else {
3229 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003230 R.setLookupName(Name);
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003231 }
3232
John McCall129e2df2009-11-30 22:42:35 +00003233 return false;
3234}
3235
John McCall60d7b3a2010-08-24 06:29:42 +00003236ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003237Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003238 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003239 CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003240 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003241 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003242 const TemplateArgumentListInfo *TemplateArgs) {
John McCall2f841ba2009-12-02 03:53:29 +00003243 if (BaseType->isDependentType() ||
3244 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCall9ae2f072010-08-23 23:25:46 +00003245 return ActOnDependentMemberExpr(Base, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003246 IsArrow, OpLoc,
3247 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003248 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003249
Abramo Bagnara25777432010-08-11 22:01:17 +00003250 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00003251
John McCallaa81e162009-12-01 22:10:20 +00003252 // Implicit member accesses.
3253 if (!Base) {
3254 QualType RecordTy = BaseType;
3255 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3256 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3257 RecordTy->getAs<RecordType>(),
John McCallad00b772010-06-16 08:42:20 +00003258 OpLoc, SS, TemplateArgs != 0))
John McCallaa81e162009-12-01 22:10:20 +00003259 return ExprError();
3260
3261 // Explicit member accesses.
3262 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00003263 ExprResult Result =
John McCallaa81e162009-12-01 22:10:20 +00003264 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCalld226f652010-08-21 09:40:31 +00003265 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCallaa81e162009-12-01 22:10:20 +00003266
3267 if (Result.isInvalid()) {
3268 Owned(Base);
3269 return ExprError();
3270 }
3271
3272 if (Result.get())
3273 return move(Result);
Sebastian Redlf3e63372010-05-07 09:25:11 +00003274
3275 // LookupMemberExpr can modify Base, and thus change BaseType
3276 BaseType = Base->getType();
John McCall129e2df2009-11-30 22:42:35 +00003277 }
3278
John McCall9ae2f072010-08-23 23:25:46 +00003279 return BuildMemberReferenceExpr(Base, BaseType,
John McCallc2233c52010-01-15 08:34:02 +00003280 OpLoc, IsArrow, SS, FirstQualifierInScope,
3281 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003282}
3283
John McCall60d7b3a2010-08-24 06:29:42 +00003284ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003285Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCallaa81e162009-12-01 22:10:20 +00003286 SourceLocation OpLoc, bool IsArrow,
3287 const CXXScopeSpec &SS,
John McCallc2233c52010-01-15 08:34:02 +00003288 NamedDecl *FirstQualifierInScope,
John McCall129e2df2009-11-30 22:42:35 +00003289 LookupResult &R,
Douglas Gregor06a9f362010-05-01 20:49:11 +00003290 const TemplateArgumentListInfo *TemplateArgs,
3291 bool SuppressQualifierCheck) {
John McCallaa81e162009-12-01 22:10:20 +00003292 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00003293 if (IsArrow) {
3294 assert(BaseType->isPointerType());
3295 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3296 }
John McCall161755a2010-04-06 21:38:20 +00003297 R.setBaseObjectType(BaseType);
John McCall129e2df2009-11-30 22:42:35 +00003298
John McCall9ae2f072010-08-23 23:25:46 +00003299 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara25777432010-08-11 22:01:17 +00003300 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3301 DeclarationName MemberName = MemberNameInfo.getName();
3302 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall129e2df2009-11-30 22:42:35 +00003303
3304 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00003305 return ExprError();
3306
John McCall129e2df2009-11-30 22:42:35 +00003307 if (R.empty()) {
3308 // Rederive where we looked up.
3309 DeclContext *DC = (SS.isSet()
3310 ? computeDeclContext(SS, false)
3311 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00003312
John McCall129e2df2009-11-30 22:42:35 +00003313 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00003314 << MemberName << DC
3315 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00003316 return ExprError();
3317 }
3318
John McCallc2233c52010-01-15 08:34:02 +00003319 // Diagnose lookups that find only declarations from a non-base
3320 // type. This is possible for either qualified lookups (which may
3321 // have been qualified with an unrelated type) or implicit member
3322 // expressions (which were found with unqualified lookup and thus
3323 // may have come from an enclosing scope). Note that it's okay for
3324 // lookup to find declarations from a non-base type as long as those
3325 // aren't the ones picked by overload resolution.
3326 if ((SS.isSet() || !BaseExpr ||
3327 (isa<CXXThisExpr>(BaseExpr) &&
3328 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00003329 !SuppressQualifierCheck &&
John McCallc2233c52010-01-15 08:34:02 +00003330 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00003331 return ExprError();
3332
3333 // Construct an unresolved result if we in fact got an unresolved
3334 // result.
3335 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallc373d482010-01-27 01:50:18 +00003336 // Suppress any lookup-related diagnostics; we'll do these when we
3337 // pick a member.
3338 R.suppressDiagnostics();
3339
John McCall129e2df2009-11-30 22:42:35 +00003340 UnresolvedMemberExpr *MemExpr
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003341 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00003342 BaseExpr, BaseExprType,
3343 IsArrow, OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00003344 Qualifier, SS.getRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +00003345 MemberNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00003346 TemplateArgs, R.begin(), R.end());
John McCall129e2df2009-11-30 22:42:35 +00003347
3348 return Owned(MemExpr);
3349 }
3350
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003351 assert(R.isSingleResult());
John McCall161755a2010-04-06 21:38:20 +00003352 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall129e2df2009-11-30 22:42:35 +00003353 NamedDecl *MemberDecl = R.getFoundDecl();
3354
3355 // FIXME: diagnose the presence of template arguments now.
3356
3357 // If the decl being referenced had an error, return an error for this
3358 // sub-expr without emitting another error, in order to avoid cascading
3359 // error cases.
3360 if (MemberDecl->isInvalidDecl())
3361 return ExprError();
3362
John McCallaa81e162009-12-01 22:10:20 +00003363 // Handle the implicit-member-access case.
3364 if (!BaseExpr) {
3365 // If this is not an instance member, convert to a non-member access.
John McCall161755a2010-04-06 21:38:20 +00003366 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnara25777432010-08-11 22:01:17 +00003367 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCallaa81e162009-12-01 22:10:20 +00003368
Douglas Gregor828a1972010-01-07 23:12:05 +00003369 SourceLocation Loc = R.getNameLoc();
3370 if (SS.getRange().isValid())
3371 Loc = SS.getRange().getBegin();
3372 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003373 }
3374
John McCall129e2df2009-11-30 22:42:35 +00003375 bool ShouldCheckUse = true;
3376 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3377 // Don't diagnose the use of a virtual member function unless it's
3378 // explicitly qualified.
3379 if (MD->isVirtual() && !SS.isSet())
3380 ShouldCheckUse = false;
3381 }
3382
3383 // Check the use of this member.
3384 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3385 Owned(BaseExpr);
3386 return ExprError();
3387 }
3388
John McCallf6a16482010-12-04 03:47:34 +00003389 // Perform a property load on the base regardless of whether we
3390 // actually need it for the declaration.
3391 if (BaseExpr->getObjectKind() == OK_ObjCProperty)
3392 ConvertPropertyForRValue(BaseExpr);
3393
John McCalldfa1edb2010-11-23 20:48:44 +00003394 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3395 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3396 SS, FD, FoundDecl, MemberNameInfo);
John McCall129e2df2009-11-30 22:42:35 +00003397
Francois Pichet87c2e122010-11-21 06:08:52 +00003398 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3399 // We may have found a field within an anonymous union or struct
3400 // (C++ [class.union]).
3401 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
John McCallf6a16482010-12-04 03:47:34 +00003402 BaseExpr, OpLoc);
Francois Pichet87c2e122010-11-21 06:08:52 +00003403
John McCall129e2df2009-11-30 22:42:35 +00003404 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3405 MarkDeclarationReferenced(MemberLoc, Var);
3406 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003407 Var, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003408 Var->getType().getNonReferenceType(),
John McCall09431682010-11-18 19:01:18 +00003409 VK_LValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003410 }
3411
John McCallf89e55a2010-11-18 06:31:45 +00003412 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall129e2df2009-11-30 22:42:35 +00003413 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3414 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003415 MemberFn, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003416 MemberFn->getType(),
3417 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3418 OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003419 }
John McCallf89e55a2010-11-18 06:31:45 +00003420 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall129e2df2009-11-30 22:42:35 +00003421
3422 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3423 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3424 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003425 Enum, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003426 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003427 }
3428
3429 Owned(BaseExpr);
3430
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003431 // We found something that we didn't expect. Complain.
John McCall129e2df2009-11-30 22:42:35 +00003432 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnara25777432010-08-11 22:01:17 +00003433 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003434 << MemberName << BaseType << int(IsArrow);
3435 else
3436 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3437 << MemberName << BaseType << int(IsArrow);
John McCall129e2df2009-11-30 22:42:35 +00003438
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003439 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3440 << MemberName;
Douglas Gregor2b147f02010-04-25 21:15:30 +00003441 R.suppressDiagnostics();
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003442 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00003443}
3444
John McCall028d3972010-12-15 16:46:44 +00003445/// Given that normal member access failed on the given expression,
3446/// and given that the expression's type involves builtin-id or
3447/// builtin-Class, decide whether substituting in the redefinition
3448/// types would be profitable. The redefinition type is whatever
3449/// this translation unit tried to typedef to id/Class; we store
3450/// it to the side and then re-use it in places like this.
3451static bool ShouldTryAgainWithRedefinitionType(Sema &S, Expr *&base) {
3452 const ObjCObjectPointerType *opty
3453 = base->getType()->getAs<ObjCObjectPointerType>();
3454 if (!opty) return false;
3455
3456 const ObjCObjectType *ty = opty->getObjectType();
3457
3458 QualType redef;
3459 if (ty->isObjCId()) {
3460 redef = S.Context.ObjCIdRedefinitionType;
3461 } else if (ty->isObjCClass()) {
3462 redef = S.Context.ObjCClassRedefinitionType;
3463 } else {
3464 return false;
3465 }
3466
3467 // Do the substitution as long as the redefinition type isn't just a
3468 // possibly-qualified pointer to builtin-id or builtin-Class again.
3469 opty = redef->getAs<ObjCObjectPointerType>();
3470 if (opty && !opty->getObjectType()->getInterface() != 0)
3471 return false;
3472
3473 S.ImpCastExprToType(base, redef, CK_BitCast);
3474 return true;
3475}
3476
John McCall129e2df2009-11-30 22:42:35 +00003477/// Look up the given member of the given non-type-dependent
3478/// expression. This can return in one of two ways:
3479/// * If it returns a sentinel null-but-valid result, the caller will
3480/// assume that lookup was performed and the results written into
3481/// the provided structure. It will take over from there.
3482/// * Otherwise, the returned expression will be produced in place of
3483/// an ordinary member expression.
3484///
3485/// The ObjCImpDecl bit is a gross hack that will need to be properly
3486/// fixed for ObjC++.
John McCall60d7b3a2010-08-24 06:29:42 +00003487ExprResult
John McCall129e2df2009-11-30 22:42:35 +00003488Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCall812c1542009-12-07 22:46:59 +00003489 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003490 CXXScopeSpec &SS,
John McCalld226f652010-08-21 09:40:31 +00003491 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003492 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00003493
Steve Naroff3cc4af82007-12-16 21:42:28 +00003494 // Perform default conversions.
3495 DefaultFunctionArrayConversion(BaseExpr);
John McCall5e3c67b2010-12-15 04:42:30 +00003496 if (IsArrow) DefaultLvalueConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003497
Steve Naroffdfa6aae2007-07-26 03:11:44 +00003498 QualType BaseType = BaseExpr->getType();
John McCall129e2df2009-11-30 22:42:35 +00003499 assert(!BaseType->isDependentType());
3500
3501 DeclarationName MemberName = R.getLookupName();
3502 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00003503
John McCall028d3972010-12-15 16:46:44 +00003504 // For later type-checking purposes, turn arrow accesses into dot
3505 // accesses. The only access type we support that doesn't follow
3506 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
3507 // and those never use arrows, so this is unaffected.
3508 if (IsArrow) {
3509 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3510 BaseType = Ptr->getPointeeType();
3511 else if (const ObjCObjectPointerType *Ptr
3512 = BaseType->getAs<ObjCObjectPointerType>())
3513 BaseType = Ptr->getPointeeType();
3514 else if (BaseType->isRecordType()) {
3515 // Recover from arrow accesses to records, e.g.:
3516 // struct MyRecord foo;
3517 // foo->bar
3518 // This is actually well-formed in C++ if MyRecord has an
3519 // overloaded operator->, but that should have been dealt with
3520 // by now.
3521 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3522 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3523 << FixItHint::CreateReplacement(OpLoc, ".");
3524 IsArrow = false;
3525 } else {
3526 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3527 << BaseType << BaseExpr->getSourceRange();
3528 return ExprError();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00003529 }
3530 }
3531
John McCall028d3972010-12-15 16:46:44 +00003532 // Handle field access to simple records.
3533 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
3534 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
3535 RTy, OpLoc, SS, HasTemplateArgs))
3536 return ExprError();
3537
3538 // Returning valid-but-null is how we indicate to the caller that
3539 // the lookup result was filled in.
3540 return Owned((Expr*) 0);
David Chisnall0f436562009-08-17 16:35:33 +00003541 }
John McCall129e2df2009-11-30 22:42:35 +00003542
John McCall028d3972010-12-15 16:46:44 +00003543 // Handle ivar access to Objective-C objects.
3544 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003545 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall028d3972010-12-15 16:46:44 +00003546
3547 // There are three cases for the base type:
3548 // - builtin id (qualified or unqualified)
3549 // - builtin Class (qualified or unqualified)
3550 // - an interface
3551 ObjCInterfaceDecl *IDecl = OTy->getInterface();
3552 if (!IDecl) {
3553 // There's an implicit 'isa' ivar on all objects.
3554 // But we only actually find it this way on objects of type 'id',
3555 // apparently.
3556 if (OTy->isObjCId() && Member->isStr("isa"))
3557 return Owned(new (Context) ObjCIsaExpr(BaseExpr, IsArrow, MemberLoc,
3558 Context.getObjCClassType()));
3559
3560 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3561 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3562 ObjCImpDecl, HasTemplateArgs);
3563 goto fail;
3564 }
3565
3566 ObjCInterfaceDecl *ClassDeclared;
3567 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
3568
3569 if (!IV) {
3570 // Attempt to correct for typos in ivar names.
3571 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3572 LookupMemberName);
3573 if (CorrectTypo(Res, 0, 0, IDecl, false,
3574 IsArrow ? CTC_ObjCIvarLookup
3575 : CTC_ObjCPropertyLookup) &&
3576 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
3577 Diag(R.getNameLoc(),
3578 diag::err_typecheck_member_reference_ivar_suggest)
3579 << IDecl->getDeclName() << MemberName << IV->getDeclName()
3580 << FixItHint::CreateReplacement(R.getNameLoc(),
3581 IV->getNameAsString());
3582 Diag(IV->getLocation(), diag::note_previous_decl)
3583 << IV->getDeclName();
3584 } else {
3585 Res.clear();
3586 Res.setLookupName(Member);
3587
3588 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
3589 << IDecl->getDeclName() << MemberName
3590 << BaseExpr->getSourceRange();
3591 return ExprError();
3592 }
3593 }
3594
3595 // If the decl being referenced had an error, return an error for this
3596 // sub-expr without emitting another error, in order to avoid cascading
3597 // error cases.
3598 if (IV->isInvalidDecl())
3599 return ExprError();
3600
3601 // Check whether we can reference this field.
3602 if (DiagnoseUseOfDecl(IV, MemberLoc))
3603 return ExprError();
3604 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3605 IV->getAccessControl() != ObjCIvarDecl::Package) {
3606 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3607 if (ObjCMethodDecl *MD = getCurMethodDecl())
3608 ClassOfMethodDecl = MD->getClassInterface();
3609 else if (ObjCImpDecl && getCurFunctionDecl()) {
3610 // Case of a c-function declared inside an objc implementation.
3611 // FIXME: For a c-style function nested inside an objc implementation
3612 // class, there is no implementation context available, so we pass
3613 // down the context as argument to this routine. Ideally, this context
3614 // need be passed down in the AST node and somehow calculated from the
3615 // AST for a function decl.
3616 if (ObjCImplementationDecl *IMPD =
3617 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
3618 ClassOfMethodDecl = IMPD->getClassInterface();
3619 else if (ObjCCategoryImplDecl* CatImplClass =
3620 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
3621 ClassOfMethodDecl = CatImplClass->getClassInterface();
3622 }
3623
3624 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3625 if (ClassDeclared != IDecl ||
3626 ClassOfMethodDecl != ClassDeclared)
3627 Diag(MemberLoc, diag::error_private_ivar_access)
3628 << IV->getDeclName();
3629 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3630 // @protected
3631 Diag(MemberLoc, diag::error_protected_ivar_access)
3632 << IV->getDeclName();
3633 }
3634
3635 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3636 MemberLoc, BaseExpr,
3637 IsArrow));
3638 }
3639
3640 // Objective-C property access.
3641 const ObjCObjectPointerType *OPT;
3642 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
3643 // This actually uses the base as an r-value.
3644 DefaultLvalueConversion(BaseExpr);
3645 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr->getType()));
3646
3647 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3648
3649 const ObjCObjectType *OT = OPT->getObjectType();
3650
3651 // id, with and without qualifiers.
3652 if (OT->isObjCId()) {
3653 // Check protocols on qualified interfaces.
3654 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3655 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
3656 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3657 // Check the use of this declaration
3658 if (DiagnoseUseOfDecl(PD, MemberLoc))
3659 return ExprError();
3660
3661 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3662 VK_LValue,
3663 OK_ObjCProperty,
3664 MemberLoc,
3665 BaseExpr));
3666 }
3667
3668 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3669 // Check the use of this method.
3670 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3671 return ExprError();
3672 Selector SetterSel =
3673 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3674 PP.getSelectorTable(), Member);
3675 ObjCMethodDecl *SMD = 0;
3676 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
3677 SetterSel, Context))
3678 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3679 QualType PType = OMD->getSendResultType();
3680
3681 ExprValueKind VK = VK_LValue;
3682 if (!getLangOptions().CPlusPlus &&
3683 IsCForbiddenLValueType(Context, PType))
3684 VK = VK_RValue;
3685 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3686
3687 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
3688 VK, OK,
3689 MemberLoc, BaseExpr));
3690 }
3691 }
3692
3693 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3694 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3695 ObjCImpDecl, HasTemplateArgs);
3696
3697 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3698 << MemberName << BaseType);
3699 }
3700
3701 // 'Class', unqualified only.
3702 if (OT->isObjCClass()) {
3703 // Only works in a method declaration (??!).
3704 ObjCMethodDecl *MD = getCurMethodDecl();
3705 if (!MD) {
3706 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3707 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3708 ObjCImpDecl, HasTemplateArgs);
3709
3710 goto fail;
3711 }
3712
3713 // Also must look for a getter name which uses property syntax.
3714 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003715 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3716 ObjCMethodDecl *Getter;
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003717 if ((Getter = IFace->lookupClassMethod(Sel))) {
3718 // Check the use of this method.
3719 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3720 return ExprError();
John McCall028d3972010-12-15 16:46:44 +00003721 } else
Fariborz Jahanian74b27562010-12-03 23:37:08 +00003722 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003723 // If we found a getter then this may be a valid dot-reference, we
3724 // will look for the matching setter, in case it is needed.
3725 Selector SetterSel =
John McCall028d3972010-12-15 16:46:44 +00003726 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3727 PP.getSelectorTable(), Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003728 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3729 if (!Setter) {
3730 // If this reference is in an @implementation, also check for 'private'
3731 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +00003732 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003733 }
3734 // Look through local category implementations associated with the class.
3735 if (!Setter)
3736 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003737
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003738 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3739 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003740
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003741 if (Getter || Setter) {
3742 QualType PType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003743
John McCall09431682010-11-18 19:01:18 +00003744 ExprValueKind VK = VK_LValue;
3745 if (Getter) {
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003746 PType = Getter->getSendResultType();
John McCall09431682010-11-18 19:01:18 +00003747 if (!getLangOptions().CPlusPlus &&
3748 IsCForbiddenLValueType(Context, PType))
3749 VK = VK_RValue;
3750 } else {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003751 // Get the expression type from Setter's incoming parameter.
3752 PType = (*(Setter->param_end() -1))->getType();
John McCall09431682010-11-18 19:01:18 +00003753 }
3754 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3755
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003756 // FIXME: we must check that the setter has property type.
John McCall12f78a62010-12-02 01:19:52 +00003757 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
3758 PType, VK, OK,
3759 MemberLoc, BaseExpr));
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003760 }
John McCall028d3972010-12-15 16:46:44 +00003761
3762 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3763 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3764 ObjCImpDecl, HasTemplateArgs);
3765
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00003766 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall028d3972010-12-15 16:46:44 +00003767 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00003768 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003769
John McCall028d3972010-12-15 16:46:44 +00003770 // Normal property access.
3771 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc,
3772 SourceLocation(), QualType(), false);
Steve Naroff14108da2009-07-10 23:34:53 +00003773 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003774
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003775 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00003776 if (BaseType->isExtVectorType()) {
John McCall5e3c67b2010-12-15 04:42:30 +00003777 // FIXME: this expr should store IsArrow.
Anders Carlsson8f28f992009-08-26 18:25:21 +00003778 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall5e3c67b2010-12-15 04:42:30 +00003779 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr->getValueKind());
John McCall09431682010-11-18 19:01:18 +00003780 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
3781 Member, MemberLoc);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003782 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003783 return ExprError();
John McCall09431682010-11-18 19:01:18 +00003784
3785 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr,
3786 *Member, MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003787 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003788
John McCall028d3972010-12-15 16:46:44 +00003789 // Adjust builtin-sel to the appropriate redefinition type if that's
3790 // not just a pointer to builtin-sel again.
3791 if (IsArrow &&
3792 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
3793 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
3794 ImpCastExprToType(BaseExpr, Context.ObjCSelRedefinitionType, CK_BitCast);
3795 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3796 ObjCImpDecl, HasTemplateArgs);
3797 }
3798
3799 // Failure cases.
3800 fail:
3801
3802 // There's a possible road to recovery for function types.
3803 const FunctionType *Fun = 0;
3804
3805 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
3806 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
3807 // fall out, handled below.
3808
3809 // Recover from dot accesses to pointers, e.g.:
3810 // type *foo;
3811 // foo.bar
3812 // This is actually well-formed in two cases:
3813 // - 'type' is an Objective C type
3814 // - 'bar' is a pseudo-destructor name which happens to refer to
3815 // the appropriate pointer type
3816 } else if (Ptr->getPointeeType()->isRecordType() &&
3817 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
3818 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3819 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3820 << FixItHint::CreateReplacement(OpLoc, "->");
3821
3822 // Recurse as an -> access.
3823 IsArrow = true;
3824 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3825 ObjCImpDecl, HasTemplateArgs);
3826 }
3827 } else {
3828 Fun = BaseType->getAs<FunctionType>();
3829 }
3830
3831 // If the user is trying to apply -> or . to a function pointer
3832 // type, it's probably because they forgot parentheses to call that
3833 // function. Suggest the addition of those parentheses, build the
3834 // call, and continue on.
3835 if (Fun || BaseType == Context.OverloadTy) {
3836 bool TryCall;
3837 if (BaseType == Context.OverloadTy) {
3838 TryCall = true;
3839 } else {
3840 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
3841 TryCall = (FPT->getNumArgs() == 0);
3842 } else {
3843 TryCall = true;
3844 }
3845
3846 if (TryCall) {
3847 QualType ResultTy = Fun->getResultType();
3848 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
3849 (IsArrow && ResultTy->isPointerType() &&
3850 ResultTy->getAs<PointerType>()->getPointeeType()->isRecordType());
3851 }
3852 }
3853
3854
3855 if (TryCall) {
3856 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
3857 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
3858 << QualType(Fun, 0)
3859 << FixItHint::CreateInsertion(Loc, "()");
3860
3861 ExprResult NewBase
3862 = ActOnCallExpr(0, BaseExpr, Loc, MultiExprArg(*this, 0, 0), Loc);
3863 if (NewBase.isInvalid())
3864 return ExprError();
3865 BaseExpr = NewBase.takeAs<Expr>();
3866
3867
3868 DefaultFunctionArrayConversion(BaseExpr);
3869 BaseType = BaseExpr->getType();
3870
3871 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3872 ObjCImpDecl, HasTemplateArgs);
3873 }
3874 }
3875
Douglas Gregor214f31a2009-03-27 06:00:30 +00003876 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3877 << BaseType << BaseExpr->getSourceRange();
3878
Douglas Gregor214f31a2009-03-27 06:00:30 +00003879 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003880}
3881
John McCall129e2df2009-11-30 22:42:35 +00003882/// The main callback when the parser finds something like
3883/// expression . [nested-name-specifier] identifier
3884/// expression -> [nested-name-specifier] identifier
3885/// where 'identifier' encompasses a fairly broad spectrum of
3886/// possibilities, including destructor and operator references.
3887///
3888/// \param OpKind either tok::arrow or tok::period
3889/// \param HasTrailingLParen whether the next token is '(', which
3890/// is used to diagnose mis-uses of special members that can
3891/// only be called
3892/// \param ObjCImpDecl the current ObjC @implementation decl;
3893/// this is an ugly hack around the fact that ObjC @implementations
3894/// aren't properly put in the context chain
John McCall60d7b3a2010-08-24 06:29:42 +00003895ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall5e3c67b2010-12-15 04:42:30 +00003896 SourceLocation OpLoc,
3897 tok::TokenKind OpKind,
3898 CXXScopeSpec &SS,
3899 UnqualifiedId &Id,
3900 Decl *ObjCImpDecl,
3901 bool HasTrailingLParen) {
John McCall129e2df2009-11-30 22:42:35 +00003902 if (SS.isSet() && SS.isInvalid())
3903 return ExprError();
3904
3905 TemplateArgumentListInfo TemplateArgsBuffer;
3906
3907 // Decompose the name into its component parts.
Abramo Bagnara25777432010-08-11 22:01:17 +00003908 DeclarationNameInfo NameInfo;
John McCall129e2df2009-11-30 22:42:35 +00003909 const TemplateArgumentListInfo *TemplateArgs;
3910 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnara25777432010-08-11 22:01:17 +00003911 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003912
Abramo Bagnara25777432010-08-11 22:01:17 +00003913 DeclarationName Name = NameInfo.getName();
John McCall129e2df2009-11-30 22:42:35 +00003914 bool IsArrow = (OpKind == tok::arrow);
3915
3916 NamedDecl *FirstQualifierInScope
3917 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3918 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3919
3920 // This is a postfix expression, so get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003921 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003922 if (Result.isInvalid()) return ExprError();
3923 Base = Result.take();
John McCall129e2df2009-11-30 22:42:35 +00003924
Douglas Gregor01e56ae2010-04-12 20:54:26 +00003925 if (Base->getType()->isDependentType() || Name.isDependentName() ||
3926 isDependentScopeSpecifier(SS)) {
John McCall9ae2f072010-08-23 23:25:46 +00003927 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00003928 IsArrow, OpLoc,
3929 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003930 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003931 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003932 LookupResult R(*this, NameInfo, LookupMemberName);
John McCallad00b772010-06-16 08:42:20 +00003933 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3934 SS, ObjCImpDecl, TemplateArgs != 0);
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003935
John McCallad00b772010-06-16 08:42:20 +00003936 if (Result.isInvalid()) {
3937 Owned(Base);
3938 return ExprError();
3939 }
John McCall129e2df2009-11-30 22:42:35 +00003940
John McCallad00b772010-06-16 08:42:20 +00003941 if (Result.get()) {
3942 // The only way a reference to a destructor can be used is to
3943 // immediately call it, which falls into this case. If the
3944 // next token is not a '(', produce a diagnostic and build the
3945 // call now.
3946 if (!HasTrailingLParen &&
3947 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCall9ae2f072010-08-23 23:25:46 +00003948 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall129e2df2009-11-30 22:42:35 +00003949
John McCallad00b772010-06-16 08:42:20 +00003950 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00003951 }
3952
John McCall9ae2f072010-08-23 23:25:46 +00003953 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCallc2233c52010-01-15 08:34:02 +00003954 OpLoc, IsArrow, SS, FirstQualifierInScope,
3955 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003956 }
3957
3958 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00003959}
3960
John McCall60d7b3a2010-08-24 06:29:42 +00003961ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003962 FunctionDecl *FD,
3963 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003964 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003965 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003966 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003967 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003968 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003969 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003970 return ExprError();
3971 }
3972
3973 if (Param->hasUninstantiatedDefaultArg()) {
3974 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003975
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003976 // Instantiate the expression.
3977 MultiLevelTemplateArgumentList ArgList
3978 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003979
Nico Weber08e41a62010-11-29 18:19:25 +00003980 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003981 = ArgList.getInnermost();
3982 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3983 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003984
Nico Weber08e41a62010-11-29 18:19:25 +00003985 ExprResult Result;
3986 {
3987 // C++ [dcl.fct.default]p5:
3988 // The names in the [default argument] expression are bound, and
3989 // the semantic constraints are checked, at the point where the
3990 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003991 ContextRAII SavedContext(*this, FD);
Nico Weber08e41a62010-11-29 18:19:25 +00003992 Result = SubstExpr(UninstExpr, ArgList);
3993 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003994 if (Result.isInvalid())
3995 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003996
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003997 // Check the expression as an initializer for the parameter.
3998 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003999 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004000 InitializationKind Kind
4001 = InitializationKind::CreateCopy(Param->getLocation(),
4002 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4003 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00004004
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004005 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4006 Result = InitSeq.Perform(*this, Entity, Kind,
4007 MultiExprArg(*this, &ResultE, 1));
4008 if (Result.isInvalid())
4009 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004010
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004011 // Build the default argument expression.
4012 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4013 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004014 }
4015
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004016 // If the default expression creates temporaries, we need to
4017 // push them to the current stack of expression temporaries so they'll
4018 // be properly destroyed.
4019 // FIXME: We should really be rebuilding the default argument with new
4020 // bound temporaries; see the comment in PR5810.
Douglas Gregor5833b0b2010-09-14 22:55:20 +00004021 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4022 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4023 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4024 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4025 ExprTemporaries.push_back(Temporary);
4026 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004027
4028 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00004029 // Just mark all of the declarations in this potentially-evaluated expression
4030 // as being "referenced".
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004031 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor036aed12009-12-23 23:03:06 +00004032 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004033}
4034
Douglas Gregor88a35142008-12-22 05:46:06 +00004035/// ConvertArgumentsForCall - Converts the arguments specified in
4036/// Args/NumArgs to the parameter types of the function FDecl with
4037/// function prototype Proto. Call is the call expression itself, and
4038/// Fn is the function expression. For a C++ member function, this
4039/// routine does not attempt to convert the object argument. Returns
4040/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004041bool
4042Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00004043 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00004044 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00004045 Expr **Args, unsigned NumArgs,
4046 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004047 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00004048 // assignment, to the types of the corresponding parameter, ...
4049 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004050 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004051
Douglas Gregor88a35142008-12-22 05:46:06 +00004052 // If too few arguments are available (and we don't have default
4053 // arguments for the remaining parameters), don't make the call.
4054 if (NumArgs < NumArgsInProto) {
4055 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4056 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004057 << Fn->getType()->isBlockPointerType()
Eric Christopherd77b9a22010-04-16 04:48:22 +00004058 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00004059 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00004060 }
4061
4062 // If too many are passed and not variadic, error on the extras and drop
4063 // them.
4064 if (NumArgs > NumArgsInProto) {
4065 if (!Proto->isVariadic()) {
4066 Diag(Args[NumArgsInProto]->getLocStart(),
4067 diag::err_typecheck_call_too_many_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004068 << Fn->getType()->isBlockPointerType()
Eric Christopherccfa9632010-04-16 04:56:46 +00004069 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00004070 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4071 Args[NumArgs-1]->getLocEnd());
4072 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004073 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004074 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004075 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004076 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004077 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004078 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004079 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4080 if (Fn->getType()->isBlockPointerType())
4081 CallType = VariadicBlock; // Block
4082 else if (isa<MemberExpr>(Fn))
4083 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004084 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004085 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004086 if (Invalid)
4087 return true;
4088 unsigned TotalNumArgs = AllArgs.size();
4089 for (unsigned i = 0; i < TotalNumArgs; ++i)
4090 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004091
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004092 return false;
4093}
Mike Stumpeed9cac2009-02-19 03:04:26 +00004094
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004095bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4096 FunctionDecl *FDecl,
4097 const FunctionProtoType *Proto,
4098 unsigned FirstProtoArg,
4099 Expr **Args, unsigned NumArgs,
4100 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004101 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004102 unsigned NumArgsInProto = Proto->getNumArgs();
4103 unsigned NumArgsToCheck = NumArgs;
4104 bool Invalid = false;
4105 if (NumArgs != NumArgsInProto)
4106 // Use default arguments for missing arguments
4107 NumArgsToCheck = NumArgsInProto;
4108 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00004109 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004110 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004111 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004112
Douglas Gregor88a35142008-12-22 05:46:06 +00004113 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004114 if (ArgIx < NumArgs) {
4115 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004116
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004117 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4118 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00004119 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004120 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004121 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004122
Douglas Gregora188ff22009-12-22 16:09:06 +00004123 // Pass the argument
4124 ParmVarDecl *Param = 0;
4125 if (FDecl && i < FDecl->getNumParams())
4126 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00004127
Douglas Gregora188ff22009-12-22 16:09:06 +00004128 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004129 Param? InitializedEntity::InitializeParameter(Context, Param)
4130 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCall60d7b3a2010-08-24 06:29:42 +00004131 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00004132 SourceLocation(),
4133 Owned(Arg));
Douglas Gregora188ff22009-12-22 16:09:06 +00004134 if (ArgE.isInvalid())
4135 return true;
4136
4137 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004138 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00004139 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004140
John McCall60d7b3a2010-08-24 06:29:42 +00004141 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004142 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004143 if (ArgExpr.isInvalid())
4144 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004145
Anders Carlsson56c5e332009-08-25 03:49:14 +00004146 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004147 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004148 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00004149 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004150
Douglas Gregor88a35142008-12-22 05:46:06 +00004151 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004152 if (CallType != VariadicDoesNotApply) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004153 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner40378332010-05-16 04:01:30 +00004154 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004155 Expr *Arg = Args[i];
Chris Lattner40378332010-05-16 04:01:30 +00004156 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004157 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00004158 }
4159 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004160 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00004161}
4162
Steve Narofff69936d2007-09-16 03:34:24 +00004163/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00004164/// This provides the location of the left/right parens and a list of comma
4165/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00004166ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004167Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +00004168 MultiExprArg args, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00004169 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00004170
4171 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004172 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00004173 if (Result.isInvalid()) return ExprError();
4174 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00004175
John McCall9ae2f072010-08-23 23:25:46 +00004176 Expr **Args = args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004177
Douglas Gregor88a35142008-12-22 05:46:06 +00004178 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00004179 // If this is a pseudo-destructor expression, build the call immediately.
4180 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4181 if (NumArgs > 0) {
4182 // Pseudo-destructor calls should not have any arguments.
4183 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00004184 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00004185 SourceRange(Args[0]->getLocStart(),
4186 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00004187
Douglas Gregora71d8192009-09-04 17:36:40 +00004188 NumArgs = 0;
4189 }
Mike Stump1eb44332009-09-09 15:08:12 +00004190
Douglas Gregora71d8192009-09-04 17:36:40 +00004191 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00004192 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00004193 }
Mike Stump1eb44332009-09-09 15:08:12 +00004194
Douglas Gregor17330012009-02-04 15:01:18 +00004195 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00004196 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00004197 // FIXME: Will need to cache the results of name lookup (including ADL) in
4198 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00004199 bool Dependent = false;
4200 if (Fn->isTypeDependent())
4201 Dependent = true;
4202 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4203 Dependent = true;
4204
4205 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00004206 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
John McCallf89e55a2010-11-18 06:31:45 +00004207 Context.DependentTy, VK_RValue,
4208 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00004209
4210 // Determine whether this is a call to an object (C++ [over.call.object]).
4211 if (Fn->getType()->isRecordType())
4212 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004213 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00004214
John McCall129e2df2009-11-30 22:42:35 +00004215 Expr *NakedFn = Fn->IgnoreParens();
4216
4217 // Determine whether this is a call to an unresolved member function.
4218 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4219 // If lookup was unresolved but not dependent (i.e. didn't find
4220 // an unresolved using declaration), it has to be an overloaded
4221 // function set, which means it must contain either multiple
4222 // declarations (all methods or method templates) or a single
4223 // method template.
4224 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor2b147f02010-04-25 21:15:30 +00004225 isa<FunctionTemplateDecl>(
4226 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor958aeb02009-12-01 03:34:29 +00004227 (void)MemE;
John McCall129e2df2009-11-30 22:42:35 +00004228
John McCallaa81e162009-12-01 22:10:20 +00004229 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004230 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00004231 }
4232
Douglas Gregorfa047642009-02-04 00:32:51 +00004233 // Determine whether this is a call to a member function.
John McCall129e2df2009-11-30 22:42:35 +00004234 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00004235 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall129e2df2009-11-30 22:42:35 +00004236 if (isa<CXXMethodDecl>(MemDecl))
John McCallaa81e162009-12-01 22:10:20 +00004237 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004238 RParenLoc);
Douglas Gregore53060f2009-06-25 22:08:12 +00004239 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004240
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004241 // Determine whether this is a call to a pointer-to-member function.
John McCall129e2df2009-11-30 22:42:35 +00004242 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
John McCall2de56d12010-08-25 11:45:40 +00004243 if (BO->getOpcode() == BO_PtrMemD ||
4244 BO->getOpcode() == BO_PtrMemI) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00004245 if (const FunctionProtoType *FPT
4246 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004247 QualType ResultTy = FPT->getCallResultType(Context);
John McCallf89e55a2010-11-18 06:31:45 +00004248 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004249
John McCall9ae2f072010-08-23 23:25:46 +00004250 CXXMemberCallExpr *TheCall
Abramo Bagnara6c572f12010-12-03 21:39:42 +00004251 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
John McCallf89e55a2010-11-18 06:31:45 +00004252 NumArgs, ResultTy, VK,
John McCall9ae2f072010-08-23 23:25:46 +00004253 RParenLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004254
4255 if (CheckCallReturnType(FPT->getResultType(),
4256 BO->getRHS()->getSourceRange().getBegin(),
John McCall9ae2f072010-08-23 23:25:46 +00004257 TheCall, 0))
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004258 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00004259
John McCall9ae2f072010-08-23 23:25:46 +00004260 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004261 RParenLoc))
4262 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004263
John McCall9ae2f072010-08-23 23:25:46 +00004264 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004265 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004266 return ExprError(Diag(Fn->getLocStart(),
Fariborz Jahanian5de24502009-10-28 16:49:46 +00004267 diag::err_typecheck_call_not_function)
4268 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004269 }
4270 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004271 }
4272
Douglas Gregorfa047642009-02-04 00:32:51 +00004273 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00004274 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004275 // lookup and whether there were any explicitly-specified template arguments.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004276
Eli Friedmanefa42f72009-12-26 03:35:45 +00004277 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00004278 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4279 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4280 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
4281 RParenLoc);
4282 }
4283
John McCall3b4294e2009-12-16 12:17:52 +00004284 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00004285 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4286 if (UnOp->getOpcode() == UO_AddrOf)
4287 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4288
John McCall3b4294e2009-12-16 12:17:52 +00004289 if (isa<DeclRefExpr>(NakedFn))
4290 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4291
John McCallaa81e162009-12-01 22:10:20 +00004292 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
4293}
4294
John McCall3b4294e2009-12-16 12:17:52 +00004295/// BuildResolvedCallExpr - Build a call to a resolved expression,
4296/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00004297/// unary-convert to an expression of function-pointer or
4298/// block-pointer type.
4299///
4300/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00004301ExprResult
John McCallaa81e162009-12-01 22:10:20 +00004302Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4303 SourceLocation LParenLoc,
4304 Expr **Args, unsigned NumArgs,
4305 SourceLocation RParenLoc) {
4306 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4307
Chris Lattner04421082008-04-08 04:40:51 +00004308 // Promote the function operand.
4309 UsualUnaryConversions(Fn);
4310
Chris Lattner925e60d2007-12-28 05:29:59 +00004311 // Make the call expr early, before semantic checks. This guarantees cleanup
4312 // of arguments and function on error.
John McCall9ae2f072010-08-23 23:25:46 +00004313 CallExpr *TheCall = new (Context) CallExpr(Context, Fn,
4314 Args, NumArgs,
4315 Context.BoolTy,
John McCallf89e55a2010-11-18 06:31:45 +00004316 VK_RValue,
John McCall9ae2f072010-08-23 23:25:46 +00004317 RParenLoc);
Sebastian Redl0eb23302009-01-19 00:08:26 +00004318
Steve Naroffdd972f22008-09-05 22:11:13 +00004319 const FunctionType *FuncT;
4320 if (!Fn->getType()->isBlockPointerType()) {
4321 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4322 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00004323 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00004324 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00004325 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4326 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00004327 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00004328 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00004329 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00004330 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00004331 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004332 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00004333 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4334 << Fn->getType() << Fn->getSourceRange());
4335
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004336 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004337 if (CheckCallReturnType(FuncT->getResultType(),
John McCall9ae2f072010-08-23 23:25:46 +00004338 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004339 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004340 return ExprError();
4341
Chris Lattner925e60d2007-12-28 05:29:59 +00004342 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004343 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00004344 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00004345
Douglas Gregor72564e72009-02-26 23:50:07 +00004346 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00004347 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00004348 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00004349 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00004350 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004351 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00004352
Douglas Gregor74734d52009-04-02 15:37:10 +00004353 if (FDecl) {
4354 // Check if we have too few/too many template arguments, based
4355 // on our knowledge of the function definition.
4356 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00004357 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004358 const FunctionProtoType *Proto
4359 = Def->getType()->getAs<FunctionProtoType>();
4360 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004361 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4362 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004363 }
Douglas Gregor46542412010-10-25 20:39:23 +00004364
4365 // If the function we're calling isn't a function prototype, but we have
4366 // a function prototype from a prior declaratiom, use that prototype.
4367 if (!FDecl->hasPrototype())
4368 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00004369 }
4370
Steve Naroffb291ab62007-08-28 23:30:39 +00004371 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00004372 for (unsigned i = 0; i != NumArgs; i++) {
4373 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00004374
4375 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004376 InitializedEntity Entity
4377 = InitializedEntity::InitializeParameter(Context,
4378 Proto->getArgType(i));
4379 ExprResult ArgE = PerformCopyInitialization(Entity,
4380 SourceLocation(),
4381 Owned(Arg));
4382 if (ArgE.isInvalid())
4383 return true;
4384
4385 Arg = ArgE.takeAs<Expr>();
4386
4387 } else {
4388 DefaultArgumentPromotion(Arg);
Douglas Gregor46542412010-10-25 20:39:23 +00004389 }
4390
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004391 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4392 Arg->getType(),
4393 PDiag(diag::err_call_incomplete_argument)
4394 << Arg->getSourceRange()))
4395 return ExprError();
4396
Chris Lattner925e60d2007-12-28 05:29:59 +00004397 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00004398 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004399 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004400
Douglas Gregor88a35142008-12-22 05:46:06 +00004401 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4402 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004403 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4404 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00004405
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00004406 // Check for sentinels
4407 if (NDecl)
4408 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00004409
Chris Lattner59907c42007-08-10 20:18:51 +00004410 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00004411 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00004412 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00004413 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004414
Fariborz Jahanian67aba812010-11-30 17:35:24 +00004415 if (unsigned BuiltinID = FDecl->getBuiltinID())
4416 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00004417 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00004418 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00004419 return ExprError();
4420 }
Chris Lattner59907c42007-08-10 20:18:51 +00004421
John McCall9ae2f072010-08-23 23:25:46 +00004422 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00004423}
4424
John McCall60d7b3a2010-08-24 06:29:42 +00004425ExprResult
John McCallb3d87482010-08-24 05:47:05 +00004426Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004427 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00004428 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00004429 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00004430 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00004431
4432 TypeSourceInfo *TInfo;
4433 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4434 if (!TInfo)
4435 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4436
John McCall9ae2f072010-08-23 23:25:46 +00004437 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00004438}
4439
John McCall60d7b3a2010-08-24 06:29:42 +00004440ExprResult
John McCall42f56b52010-01-18 19:35:47 +00004441Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCall9ae2f072010-08-23 23:25:46 +00004442 SourceLocation RParenLoc, Expr *literalExpr) {
John McCall42f56b52010-01-18 19:35:47 +00004443 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00004444
Eli Friedman6223c222008-05-20 05:22:08 +00004445 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004446 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4447 PDiag(diag::err_illegal_decl_array_incomplete_type)
4448 << SourceRange(LParenLoc,
4449 literalExpr->getSourceRange().getEnd())))
4450 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004451 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004452 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4453 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004454 } else if (!literalType->isDependentType() &&
4455 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00004456 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00004457 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00004458 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004459 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00004460
Douglas Gregor99a2e602009-12-16 01:38:02 +00004461 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00004462 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004463 InitializationKind Kind
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004464 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor99a2e602009-12-16 01:38:02 +00004465 /*IsCStyleCast=*/true);
Eli Friedman08544622009-12-22 02:35:53 +00004466 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00004467 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00004468 MultiExprArg(*this, &literalExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00004469 &literalType);
4470 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004471 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00004472 literalExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00004473
Chris Lattner371f2582008-12-04 23:50:19 +00004474 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00004475 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00004476 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004477 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00004478 }
Eli Friedman08544622009-12-22 02:35:53 +00004479
John McCallf89e55a2010-11-18 06:31:45 +00004480 // In C, compound literals are l-values for some reason.
4481 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
4482
John McCall1d7d8d62010-01-19 22:33:45 +00004483 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCallf89e55a2010-11-18 06:31:45 +00004484 VK, literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00004485}
4486
John McCall60d7b3a2010-08-24 06:29:42 +00004487ExprResult
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004488Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004489 SourceLocation RBraceLoc) {
4490 unsigned NumInit = initlist.size();
John McCall9ae2f072010-08-23 23:25:46 +00004491 Expr **InitList = initlist.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00004492
Steve Naroff08d92e42007-09-15 18:49:24 +00004493 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00004494 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004495
Ted Kremenek709210f2010-04-13 23:39:13 +00004496 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4497 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00004498 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004499 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00004500}
4501
John McCallf3ea8cf2010-11-14 08:17:51 +00004502/// Prepares for a scalar cast, performing all the necessary stages
4503/// except the final cast and returning the kind required.
4504static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
4505 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4506 // Also, callers should have filtered out the invalid cases with
4507 // pointers. Everything else should be possible.
4508
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004509 QualType SrcTy = Src->getType();
John McCallf3ea8cf2010-11-14 08:17:51 +00004510 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00004511 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00004512
John McCalldaa8e4e2010-11-15 09:13:47 +00004513 switch (SrcTy->getScalarTypeKind()) {
4514 case Type::STK_MemberPointer:
4515 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004516
John McCalldaa8e4e2010-11-15 09:13:47 +00004517 case Type::STK_Pointer:
4518 switch (DestTy->getScalarTypeKind()) {
4519 case Type::STK_Pointer:
4520 return DestTy->isObjCObjectPointerType() ?
John McCallf3ea8cf2010-11-14 08:17:51 +00004521 CK_AnyPointerToObjCPointerCast :
4522 CK_BitCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004523 case Type::STK_Bool:
4524 return CK_PointerToBoolean;
4525 case Type::STK_Integral:
4526 return CK_PointerToIntegral;
4527 case Type::STK_Floating:
4528 case Type::STK_FloatingComplex:
4529 case Type::STK_IntegralComplex:
4530 case Type::STK_MemberPointer:
4531 llvm_unreachable("illegal cast from pointer");
4532 }
4533 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004534
John McCalldaa8e4e2010-11-15 09:13:47 +00004535 case Type::STK_Bool: // casting from bool is like casting from an integer
4536 case Type::STK_Integral:
4537 switch (DestTy->getScalarTypeKind()) {
4538 case Type::STK_Pointer:
John McCallf3ea8cf2010-11-14 08:17:51 +00004539 if (Src->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00004540 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00004541 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00004542 case Type::STK_Bool:
4543 return CK_IntegralToBoolean;
4544 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00004545 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004546 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004547 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004548 case Type::STK_IntegralComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004549 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCall8786da72010-12-14 17:51:41 +00004550 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004551 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004552 case Type::STK_FloatingComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004553 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004554 CK_IntegralToFloating);
4555 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004556 case Type::STK_MemberPointer:
4557 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004558 }
4559 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004560
John McCalldaa8e4e2010-11-15 09:13:47 +00004561 case Type::STK_Floating:
4562 switch (DestTy->getScalarTypeKind()) {
4563 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004564 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004565 case Type::STK_Bool:
4566 return CK_FloatingToBoolean;
4567 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00004568 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004569 case Type::STK_FloatingComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004570 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCall8786da72010-12-14 17:51:41 +00004571 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004572 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004573 case Type::STK_IntegralComplex:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004574 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004575 CK_FloatingToIntegral);
4576 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004577 case Type::STK_Pointer:
4578 llvm_unreachable("valid float->pointer cast?");
4579 case Type::STK_MemberPointer:
4580 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004581 }
4582 break;
4583
John McCalldaa8e4e2010-11-15 09:13:47 +00004584 case Type::STK_FloatingComplex:
4585 switch (DestTy->getScalarTypeKind()) {
4586 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004587 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004588 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004589 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00004590 case Type::STK_Floating: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004591 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00004592 if (S.Context.hasSameType(ET, DestTy))
4593 return CK_FloatingComplexToReal;
4594 S.ImpCastExprToType(Src, ET, CK_FloatingComplexToReal);
4595 return CK_FloatingCast;
4596 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004597 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004598 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004599 case Type::STK_Integral:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004600 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004601 CK_FloatingComplexToReal);
4602 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004603 case Type::STK_Pointer:
4604 llvm_unreachable("valid complex float->pointer cast?");
4605 case Type::STK_MemberPointer:
4606 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004607 }
4608 break;
4609
John McCalldaa8e4e2010-11-15 09:13:47 +00004610 case Type::STK_IntegralComplex:
4611 switch (DestTy->getScalarTypeKind()) {
4612 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004613 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004614 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004615 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00004616 case Type::STK_Integral: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004617 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00004618 if (S.Context.hasSameType(ET, DestTy))
4619 return CK_IntegralComplexToReal;
4620 S.ImpCastExprToType(Src, ET, CK_IntegralComplexToReal);
4621 return CK_IntegralCast;
4622 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004623 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004624 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004625 case Type::STK_Floating:
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004626 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCallf3ea8cf2010-11-14 08:17:51 +00004627 CK_IntegralComplexToReal);
4628 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004629 case Type::STK_Pointer:
4630 llvm_unreachable("valid complex int->pointer cast?");
4631 case Type::STK_MemberPointer:
4632 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004633 }
4634 break;
Anders Carlsson82debc72009-10-18 18:12:03 +00004635 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004636
John McCallf3ea8cf2010-11-14 08:17:51 +00004637 llvm_unreachable("Unhandled scalar cast");
4638 return CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00004639}
4640
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004641/// CheckCastTypes - Check type constraints for casting between types.
John McCallf89e55a2010-11-18 06:31:45 +00004642bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
4643 Expr *&castExpr, CastKind& Kind, ExprValueKind &VK,
4644 CXXCastPath &BasePath, bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00004645 if (getLangOptions().CPlusPlus)
Douglas Gregor40749ee2010-11-03 00:35:38 +00004646 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
4647 castExpr->getLocEnd()),
John McCallf89e55a2010-11-18 06:31:45 +00004648 castType, VK, castExpr, Kind, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004649 FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00004650
John McCallf89e55a2010-11-18 06:31:45 +00004651 // We only support r-value casts in C.
4652 VK = VK_RValue;
4653
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004654 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4655 // type needs to be scalar.
4656 if (castType->isVoidType()) {
John McCallf6a16482010-12-04 03:47:34 +00004657 // We don't necessarily do lvalue-to-rvalue conversions on this.
4658 IgnoredValueConversions(castExpr);
4659
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004660 // Cast to void allows any expr type.
John McCall2de56d12010-08-25 11:45:40 +00004661 Kind = CK_ToVoid;
Anders Carlssonebeaf202009-10-16 02:35:04 +00004662 return false;
4663 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004664
John McCallf6a16482010-12-04 03:47:34 +00004665 DefaultFunctionArrayLvalueConversion(castExpr);
4666
Eli Friedman8d438082010-07-17 20:43:49 +00004667 if (RequireCompleteType(TyR.getBegin(), castType,
4668 diag::err_typecheck_cast_to_incomplete))
4669 return true;
4670
Anders Carlssonebeaf202009-10-16 02:35:04 +00004671 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00004672 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004673 (castType->isStructureType() || castType->isUnionType())) {
4674 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004675 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004676 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
4677 << castType << castExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004678 Kind = CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00004679 return false;
4680 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004681
Anders Carlssonc3516322009-10-16 02:48:28 +00004682 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004683 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00004684 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004685 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004686 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004687 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004688 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara8c4bfe52010-10-07 21:20:44 +00004689 castExpr->getType()) &&
4690 !Field->isUnnamedBitfield()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004691 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4692 << castExpr->getSourceRange();
4693 break;
4694 }
4695 }
4696 if (Field == FieldEnd)
4697 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
4698 << castExpr->getType() << castExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004699 Kind = CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00004700 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004701 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004702
Anders Carlssonc3516322009-10-16 02:48:28 +00004703 // Reject any other conversions to non-scalar types.
4704 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
4705 << castType << castExpr->getSourceRange();
4706 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004707
John McCallf3ea8cf2010-11-14 08:17:51 +00004708 // The type we're casting to is known to be a scalar or vector.
4709
4710 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004711 if (!castExpr->getType()->isScalarType() &&
Anders Carlssonc3516322009-10-16 02:48:28 +00004712 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004713 return Diag(castExpr->getLocStart(),
4714 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00004715 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00004716 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004717
4718 if (castType->isExtVectorType())
Anders Carlsson16a89042009-10-16 05:23:41 +00004719 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004720
Anders Carlssonc3516322009-10-16 02:48:28 +00004721 if (castType->isVectorType())
4722 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
4723 if (castExpr->getType()->isVectorType())
4724 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
4725
John McCallf3ea8cf2010-11-14 08:17:51 +00004726 // The source and target types are both scalars, i.e.
4727 // - arithmetic types (fundamental, enum, and complex)
4728 // - all kinds of pointers
4729 // Note that member pointers were filtered out with C++, above.
4730
Anders Carlsson16a89042009-10-16 05:23:41 +00004731 if (isa<ObjCSelectorExpr>(castExpr))
4732 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004733
John McCallf3ea8cf2010-11-14 08:17:51 +00004734 // If either type is a pointer, the other type has to be either an
4735 // integer or a pointer.
Anders Carlssonc3516322009-10-16 02:48:28 +00004736 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00004737 QualType castExprType = castExpr->getType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00004738 if (!castExprType->isIntegralType(Context) &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004739 castExprType->isArithmeticType())
Eli Friedman41826bb2009-05-01 02:23:58 +00004740 return Diag(castExpr->getLocStart(),
4741 diag::err_cast_pointer_from_non_pointer_int)
4742 << castExprType << castExpr->getSourceRange();
4743 } else if (!castExpr->getType()->isArithmeticType()) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00004744 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
Eli Friedman41826bb2009-05-01 02:23:58 +00004745 return Diag(castExpr->getLocStart(),
4746 diag::err_cast_pointer_to_non_pointer_int)
4747 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004748 }
Anders Carlsson82debc72009-10-18 18:12:03 +00004749
John McCallf3ea8cf2010-11-14 08:17:51 +00004750 Kind = PrepareScalarCast(*this, castExpr, castType);
John McCallb7f4ffe2010-08-12 21:44:57 +00004751
John McCallf3ea8cf2010-11-14 08:17:51 +00004752 if (Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +00004753 CheckCastAlign(castExpr, castType, TyR);
4754
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004755 return false;
4756}
4757
Anders Carlssonc3516322009-10-16 02:48:28 +00004758bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004759 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004760 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004761
Anders Carlssona64db8f2007-11-27 05:51:55 +00004762 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004763 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004764 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004765 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004766 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004767 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004768 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004769 } else
4770 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004771 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004772 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004773
John McCall2de56d12010-08-25 11:45:40 +00004774 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004775 return false;
4776}
4777
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004778bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
John McCall2de56d12010-08-25 11:45:40 +00004779 CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004780 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004781
Anders Carlsson16a89042009-10-16 05:23:41 +00004782 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004783
Nate Begeman9b10da62009-06-27 22:05:55 +00004784 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4785 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00004786 if (SrcTy->isVectorType()) {
4787 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
4788 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4789 << DestTy << SrcTy << R;
John McCall2de56d12010-08-25 11:45:40 +00004790 Kind = CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00004791 return false;
4792 }
4793
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004794 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004795 // conversion will take place first from scalar to elt type, and then
4796 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004797 if (SrcTy->isPointerType())
4798 return Diag(R.getBegin(),
4799 diag::err_invalid_conversion_between_vector_and_scalar)
4800 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004801
4802 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4803 ImpCastExprToType(CastExpr, DestElemTy,
John McCallf3ea8cf2010-11-14 08:17:51 +00004804 PrepareScalarCast(*this, CastExpr, DestElemTy));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004805
John McCall2de56d12010-08-25 11:45:40 +00004806 Kind = CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00004807 return false;
4808}
4809
John McCall60d7b3a2010-08-24 06:29:42 +00004810ExprResult
John McCallb3d87482010-08-24 05:47:05 +00004811Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004812 SourceLocation RParenLoc, Expr *castExpr) {
4813 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004814 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004815
John McCall9d125032010-01-15 18:39:57 +00004816 TypeSourceInfo *castTInfo;
4817 QualType castType = GetTypeFromParser(Ty, &castTInfo);
4818 if (!castTInfo)
John McCall42f56b52010-01-18 19:35:47 +00004819 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump1eb44332009-09-09 15:08:12 +00004820
Nate Begeman2ef13e52009-08-10 23:49:36 +00004821 // If the Expr being casted is a ParenListExpr, handle it specially.
4822 if (isa<ParenListExpr>(castExpr))
John McCall9ae2f072010-08-23 23:25:46 +00004823 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCall42f56b52010-01-18 19:35:47 +00004824 castTInfo);
John McCallb042fdf2010-01-15 18:56:44 +00004825
John McCall9ae2f072010-08-23 23:25:46 +00004826 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004827}
4828
John McCall60d7b3a2010-08-24 06:29:42 +00004829ExprResult
John McCallb042fdf2010-01-15 18:56:44 +00004830Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004831 SourceLocation RParenLoc, Expr *castExpr) {
John McCalldaa8e4e2010-11-15 09:13:47 +00004832 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +00004833 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +00004834 CXXCastPath BasePath;
John McCallb042fdf2010-01-15 18:56:44 +00004835 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
John McCallf89e55a2010-11-18 06:31:45 +00004836 Kind, VK, BasePath))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004837 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00004838
John McCallf871d0c2010-08-07 06:22:56 +00004839 return Owned(CStyleCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +00004840 Ty->getType().getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +00004841 VK, Kind, castExpr, &BasePath, Ty,
John McCallf871d0c2010-08-07 06:22:56 +00004842 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00004843}
4844
Nate Begeman2ef13e52009-08-10 23:49:36 +00004845/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4846/// of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004847ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004848Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004849 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4850 if (!E)
4851 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00004852
John McCall60d7b3a2010-08-24 06:29:42 +00004853 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004854
Nate Begeman2ef13e52009-08-10 23:49:36 +00004855 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004856 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4857 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004858
John McCall9ae2f072010-08-23 23:25:46 +00004859 if (Result.isInvalid()) return ExprError();
4860
4861 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004862}
4863
John McCall60d7b3a2010-08-24 06:29:42 +00004864ExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00004865Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00004866 SourceLocation RParenLoc, Expr *Op,
John McCall42f56b52010-01-18 19:35:47 +00004867 TypeSourceInfo *TInfo) {
John McCall9ae2f072010-08-23 23:25:46 +00004868 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCall42f56b52010-01-18 19:35:47 +00004869 QualType Ty = TInfo->getType();
John Thompson8bb59a82010-06-30 22:55:51 +00004870 bool isAltiVecLiteral = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004871
John Thompson8bb59a82010-06-30 22:55:51 +00004872 // Check for an altivec literal,
4873 // i.e. all the elements are integer constants.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004874 if (getLangOptions().AltiVec && Ty->isVectorType()) {
4875 if (PE->getNumExprs() == 0) {
4876 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
4877 return ExprError();
4878 }
John Thompson8bb59a82010-06-30 22:55:51 +00004879 if (PE->getNumExprs() == 1) {
4880 if (!PE->getExpr(0)->getType()->isVectorType())
4881 isAltiVecLiteral = true;
4882 }
4883 else
4884 isAltiVecLiteral = true;
4885 }
Nate Begeman2ef13e52009-08-10 23:49:36 +00004886
John Thompson8bb59a82010-06-30 22:55:51 +00004887 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
4888 // then handle it as such.
4889 if (isAltiVecLiteral) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004890 llvm::SmallVector<Expr *, 8> initExprs;
4891 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4892 initExprs.push_back(PE->getExpr(i));
4893
4894 // FIXME: This means that pretty-printing the final AST will produce curly
4895 // braces instead of the original commas.
Ted Kremenek709210f2010-04-13 23:39:13 +00004896 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
4897 &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00004898 initExprs.size(), RParenLoc);
4899 E->setType(Ty);
John McCall9ae2f072010-08-23 23:25:46 +00004900 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004901 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004902 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00004903 // sequence of BinOp comma operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004904 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCall9ae2f072010-08-23 23:25:46 +00004905 if (Result.isInvalid()) return ExprError();
4906 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004907 }
4908}
4909
John McCall60d7b3a2010-08-24 06:29:42 +00004910ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00004911 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004912 MultiExprArg Val,
John McCallb3d87482010-08-24 05:47:05 +00004913 ParsedType TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004914 unsigned nexprs = Val.size();
4915 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004916 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4917 Expr *expr;
4918 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4919 expr = new (Context) ParenExpr(L, R, exprs[0]);
4920 else
4921 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004922 return Owned(expr);
4923}
4924
Sebastian Redl28507842009-02-26 14:39:58 +00004925/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4926/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004927/// C99 6.5.15
4928QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCallf89e55a2010-11-18 06:31:45 +00004929 Expr *&SAVE, ExprValueKind &VK,
John McCall09431682010-11-18 19:01:18 +00004930 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00004931 SourceLocation QuestionLoc) {
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004932 // If both LHS and RHS are overloaded functions, try to resolve them.
4933 if (Context.hasSameType(LHS->getType(), RHS->getType()) &&
4934 LHS->getType()->isSpecificBuiltinType(BuiltinType::Overload)) {
4935 ExprResult LHSResult = CheckPlaceholderExpr(LHS, QuestionLoc);
4936 if (LHSResult.isInvalid())
4937 return QualType();
4938
4939 ExprResult RHSResult = CheckPlaceholderExpr(RHS, QuestionLoc);
4940 if (RHSResult.isInvalid())
4941 return QualType();
4942
4943 LHS = LHSResult.take();
4944 RHS = RHSResult.take();
4945 }
4946
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004947 // C++ is sufficiently different to merit its own checker.
4948 if (getLangOptions().CPlusPlus)
John McCall09431682010-11-18 19:01:18 +00004949 return CXXCheckConditionalOperands(Cond, LHS, RHS, SAVE,
4950 VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00004951
4952 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004953 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004954
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004955 UsualUnaryConversions(Cond);
Fariborz Jahanian1fb019b2010-09-18 19:38:38 +00004956 if (SAVE) {
4957 SAVE = LHS = Cond;
4958 }
4959 else
4960 UsualUnaryConversions(LHS);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004961 UsualUnaryConversions(RHS);
4962 QualType CondTy = Cond->getType();
4963 QualType LHSTy = LHS->getType();
4964 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004965
Reid Spencer5f016e22007-07-11 17:01:13 +00004966 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004967 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begeman6155d732010-09-20 22:41:17 +00004968 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4969 // Throw an error if its not either.
4970 if (getLangOptions().OpenCL) {
4971 if (!CondTy->isVectorType()) {
4972 Diag(Cond->getLocStart(),
4973 diag::err_typecheck_cond_expect_scalar_or_vector)
4974 << CondTy;
4975 return QualType();
4976 }
4977 }
4978 else {
4979 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4980 << CondTy;
4981 return QualType();
4982 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004983 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004984
Chris Lattner70d67a92008-01-06 22:42:25 +00004985 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004986 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4987 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00004988
Nate Begeman6155d732010-09-20 22:41:17 +00004989 // OpenCL: If the condition is a vector, and both operands are scalar,
4990 // attempt to implicity convert them to the vector type to act like the
4991 // built in select.
4992 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
4993 // Both operands should be of scalar type.
4994 if (!LHSTy->isScalarType()) {
4995 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4996 << CondTy;
4997 return QualType();
4998 }
4999 if (!RHSTy->isScalarType()) {
5000 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5001 << CondTy;
5002 return QualType();
5003 }
5004 // Implicity convert these scalars to the type of the condition.
5005 ImpCastExprToType(LHS, CondTy, CK_IntegralCast);
5006 ImpCastExprToType(RHS, CondTy, CK_IntegralCast);
5007 }
5008
Chris Lattner70d67a92008-01-06 22:42:25 +00005009 // If both operands have arithmetic type, do the usual arithmetic conversions
5010 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005011 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5012 UsualArithmeticConversions(LHS, RHS);
5013 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00005014 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005015
Chris Lattner70d67a92008-01-06 22:42:25 +00005016 // If both operands are the same structure or union type, the result is that
5017 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005018 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5019 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00005020 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005021 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00005022 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005023 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005024 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00005025 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005026
Chris Lattner70d67a92008-01-06 22:42:25 +00005027 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00005028 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005029 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5030 if (!LHSTy->isVoidType())
5031 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5032 << RHS->getSourceRange();
5033 if (!RHSTy->isVoidType())
5034 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5035 << LHS->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005036 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid);
5037 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00005038 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00005039 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00005040 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5041 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005042 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005043 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005044 // promote the null to a pointer.
John McCalldaa8e4e2010-11-15 09:13:47 +00005045 ImpCastExprToType(RHS, LHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005046 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00005047 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005048 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005049 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005050 ImpCastExprToType(LHS, RHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005051 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00005052 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005053
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005054 // All objective-c pointer type analysis is done here.
5055 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5056 QuestionLoc);
5057 if (!compositeType.isNull())
5058 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005059
5060
Steve Naroff7154a772009-07-01 14:36:47 +00005061 // Handle block pointer types.
5062 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5063 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5064 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5065 QualType destType = Context.getPointerType(Context.VoidTy);
John McCall2de56d12010-08-25 11:45:40 +00005066 ImpCastExprToType(LHS, destType, CK_BitCast);
5067 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005068 return destType;
5069 }
5070 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005071 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00005072 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00005073 }
Steve Naroff7154a772009-07-01 14:36:47 +00005074 // We have 2 block pointer types.
5075 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5076 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005077 return LHSTy;
5078 }
Steve Naroff7154a772009-07-01 14:36:47 +00005079 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00005080 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5081 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005082
Steve Naroff7154a772009-07-01 14:36:47 +00005083 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5084 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00005085 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005086 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00005087 // In this situation, we assume void* type. No especially good
5088 // reason, but this is what gcc does, and we do have to pick
5089 // to get a consistent AST.
5090 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCall2de56d12010-08-25 11:45:40 +00005091 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5092 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00005093 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005094 }
Steve Naroff7154a772009-07-01 14:36:47 +00005095 // The block pointer types are compatible.
John McCall2de56d12010-08-25 11:45:40 +00005096 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5097 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00005098 return LHSTy;
5099 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005100
Steve Naroff7154a772009-07-01 14:36:47 +00005101 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5102 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5103 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00005104 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5105 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00005106
5107 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5108 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5109 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00005110 QualType destPointee
5111 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00005112 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005113 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005114 ImpCastExprToType(LHS, destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005115 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005116 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005117 return destType;
5118 }
5119 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00005120 QualType destPointee
5121 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00005122 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005123 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005124 ImpCastExprToType(RHS, destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005125 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005126 ImpCastExprToType(LHS, destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005127 return destType;
5128 }
5129
5130 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5131 // Two identical pointer types are always compatible.
5132 return LHSTy;
5133 }
5134 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5135 rhptee.getUnqualifiedType())) {
5136 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5137 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5138 // In this situation, we assume void* type. No especially good
5139 // reason, but this is what gcc does, and we do have to pick
5140 // to get a consistent AST.
5141 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCall2de56d12010-08-25 11:45:40 +00005142 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5143 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005144 return incompatTy;
5145 }
5146 // The pointer types are compatible.
5147 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5148 // differently qualified versions of compatible types, the result type is
5149 // a pointer to an appropriately qualified version of the *composite*
5150 // type.
5151 // FIXME: Need to calculate the composite type.
5152 // FIXME: Need to add qualifiers
John McCall2de56d12010-08-25 11:45:40 +00005153 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5154 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005155 return LHSTy;
5156 }
Mike Stump1eb44332009-09-09 15:08:12 +00005157
John McCall404cd162010-11-13 01:35:44 +00005158 // GCC compatibility: soften pointer/integer mismatch. Note that
5159 // null pointers have been filtered out by this point.
Steve Naroff7154a772009-07-01 14:36:47 +00005160 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5161 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5162 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005163 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00005164 return RHSTy;
5165 }
5166 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5167 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5168 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005169 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00005170 return LHSTy;
5171 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00005172
Chris Lattner70d67a92008-01-06 22:42:25 +00005173 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005174 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5175 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005176 return QualType();
5177}
5178
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005179/// FindCompositeObjCPointerType - Helper method to find composite type of
5180/// two objective-c pointer types of the two input expressions.
5181QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
5182 SourceLocation QuestionLoc) {
5183 QualType LHSTy = LHS->getType();
5184 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005185
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005186 // Handle things like Class and struct objc_class*. Here we case the result
5187 // to the pseudo-builtin, because that will be implicitly cast back to the
5188 // redefinition type if an attempt is made to access its fields.
5189 if (LHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005190 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005191 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005192 return LHSTy;
5193 }
5194 if (RHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005195 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005196 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005197 return RHSTy;
5198 }
5199 // And the same for struct objc_object* / id
5200 if (LHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005201 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005202 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005203 return LHSTy;
5204 }
5205 if (RHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005206 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005207 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005208 return RHSTy;
5209 }
5210 // And the same for struct objc_selector* / SEL
5211 if (Context.isObjCSelType(LHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00005212 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005213 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005214 return LHSTy;
5215 }
5216 if (Context.isObjCSelType(RHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00005217 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John McCall2de56d12010-08-25 11:45:40 +00005218 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005219 return RHSTy;
5220 }
5221 // Check constraints for Objective-C object pointers types.
5222 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005223
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005224 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5225 // Two identical object pointer types are always compatible.
5226 return LHSTy;
5227 }
5228 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5229 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5230 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005231
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005232 // If both operands are interfaces and either operand can be
5233 // assigned to the other, use that type as the composite
5234 // type. This allows
5235 // xxx ? (A*) a : (B*) b
5236 // where B is a subclass of A.
5237 //
5238 // Additionally, as for assignment, if either type is 'id'
5239 // allow silent coercion. Finally, if the types are
5240 // incompatible then make sure to use 'id' as the composite
5241 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005242
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005243 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5244 // It could return the composite type.
5245 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5246 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5247 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5248 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5249 } else if ((LHSTy->isObjCQualifiedIdType() ||
5250 RHSTy->isObjCQualifiedIdType()) &&
5251 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5252 // Need to handle "id<xx>" explicitly.
5253 // GCC allows qualified id and any Objective-C type to devolve to
5254 // id. Currently localizing to here until clear this should be
5255 // part of ObjCQualifiedIdTypesAreCompatible.
5256 compositeType = Context.getObjCIdType();
5257 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5258 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005259 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005260 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5261 ;
5262 else {
5263 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5264 << LHSTy << RHSTy
5265 << LHS->getSourceRange() << RHS->getSourceRange();
5266 QualType incompatTy = Context.getObjCIdType();
John McCall2de56d12010-08-25 11:45:40 +00005267 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5268 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005269 return incompatTy;
5270 }
5271 // The object pointer types are compatible.
John McCall2de56d12010-08-25 11:45:40 +00005272 ImpCastExprToType(LHS, compositeType, CK_BitCast);
5273 ImpCastExprToType(RHS, compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005274 return compositeType;
5275 }
5276 // Check Objective-C object pointer types and 'void *'
5277 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5278 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5279 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5280 QualType destPointee
5281 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5282 QualType destType = Context.getPointerType(destPointee);
5283 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005284 ImpCastExprToType(LHS, destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005285 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005286 ImpCastExprToType(RHS, destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005287 return destType;
5288 }
5289 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5290 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5291 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5292 QualType destPointee
5293 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5294 QualType destType = Context.getPointerType(destPointee);
5295 // Add qualifiers if necessary.
John McCall2de56d12010-08-25 11:45:40 +00005296 ImpCastExprToType(RHS, destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005297 // Promote to void*.
John McCall2de56d12010-08-25 11:45:40 +00005298 ImpCastExprToType(LHS, destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005299 return destType;
5300 }
5301 return QualType();
5302}
5303
Steve Narofff69936d2007-09-16 03:34:24 +00005304/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005305/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005306ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005307 SourceLocation ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +00005308 Expr *CondExpr, Expr *LHSExpr,
5309 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005310 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5311 // was the condition.
5312 bool isLHSNull = LHSExpr == 0;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005313 Expr *SAVEExpr = 0;
5314 if (isLHSNull) {
5315 LHSExpr = SAVEExpr = CondExpr;
5316 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005317
John McCallf89e55a2010-11-18 06:31:45 +00005318 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005319 ExprObjectKind OK = OK_Ordinary;
Fariborz Jahanian1fb019b2010-09-18 19:38:38 +00005320 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr,
John McCall09431682010-11-18 19:01:18 +00005321 SAVEExpr, VK, OK, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00005322 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005323 return ExprError();
5324
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00005325 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005326 LHSExpr, ColonLoc,
5327 RHSExpr, SAVEExpr,
John McCall09431682010-11-18 19:01:18 +00005328 result, VK, OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005329}
5330
Reid Spencer5f016e22007-07-11 17:01:13 +00005331// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005332// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005333// routine is it effectively iqnores the qualifiers on the top level pointee.
5334// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5335// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005336Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00005337Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
5338 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005339
David Chisnall0f436562009-08-17 16:35:33 +00005340 if ((lhsType->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005341 (Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType))) ||
David Chisnall0f436562009-08-17 16:35:33 +00005342 (rhsType->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005343 (Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)))) {
David Chisnall0f436562009-08-17 16:35:33 +00005344 return Compatible;
5345 }
5346
Reid Spencer5f016e22007-07-11 17:01:13 +00005347 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00005348 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
5349 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005350
Reid Spencer5f016e22007-07-11 17:01:13 +00005351 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00005352 lhptee = Context.getCanonicalType(lhptee);
5353 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00005354
Chris Lattner5cf216b2008-01-04 18:04:52 +00005355 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005356
5357 // C99 6.5.16.1p1: This following citation is common to constraints
5358 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5359 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00005360 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00005361 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00005362 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00005363
Mike Stumpeed9cac2009-02-19 03:04:26 +00005364 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5365 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005366 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005367 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005368 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005369 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005370
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005371 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005372 assert(rhptee->isFunctionType());
5373 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005374 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005375
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005376 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005377 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005378 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005379
5380 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005381 assert(lhptee->isFunctionType());
5382 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005383 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005384 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005385 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005386 lhptee = lhptee.getUnqualifiedType();
5387 rhptee = rhptee.getUnqualifiedType();
5388 if (!Context.typesAreCompatible(lhptee, rhptee)) {
5389 // Check if the pointee types are compatible ignoring the sign.
5390 // We explicitly check for char so that we catch "char" vs
5391 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005392 if (lhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005393 lhptee = Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005394 else if (lhptee->hasSignedIntegerRepresentation())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005395 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005396
Chris Lattner6a2b9262009-10-17 20:33:28 +00005397 if (rhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005398 rhptee = Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005399 else if (rhptee->hasSignedIntegerRepresentation())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005400 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005401
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005402 if (lhptee == rhptee) {
5403 // Types are compatible ignoring the sign. Qualifier incompatibility
5404 // takes priority over sign incompatibility because the sign
5405 // warning can be disabled.
5406 if (ConvTy != Compatible)
5407 return ConvTy;
5408 return IncompatiblePointerSign;
5409 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005410
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005411 // If we are a multi-level pointer, it's possible that our issue is simply
5412 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5413 // the eventual target type is the same and the pointers have the same
5414 // level of indirection, this must be the issue.
5415 if (lhptee->isPointerType() && rhptee->isPointerType()) {
5416 do {
5417 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
5418 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005419
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005420 lhptee = Context.getCanonicalType(lhptee);
5421 rhptee = Context.getCanonicalType(rhptee);
5422 } while (lhptee->isPointerType() && rhptee->isPointerType());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005423
Douglas Gregora4923eb2009-11-16 21:35:15 +00005424 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Sean Huntc9132b62009-11-08 07:46:34 +00005425 return IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005426 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005427
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005428 // General pointer incompatibility takes priority over qualifiers.
Mike Stump1eb44332009-09-09 15:08:12 +00005429 return IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005430 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005431 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005432}
5433
Steve Naroff1c7d0672008-09-04 15:10:53 +00005434/// CheckBlockPointerTypesForAssignment - This routine determines whether two
5435/// block pointer types are compatible or whether a block and normal pointer
5436/// are compatible. It is more restrict than comparing two function pointer
5437// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005438Sema::AssignConvertType
5439Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00005440 QualType rhsType) {
5441 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005442
Steve Naroff1c7d0672008-09-04 15:10:53 +00005443 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00005444 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
5445 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005446
Steve Naroff1c7d0672008-09-04 15:10:53 +00005447 // make sure we operate on the canonical type
5448 lhptee = Context.getCanonicalType(lhptee);
5449 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005450
Steve Naroff1c7d0672008-09-04 15:10:53 +00005451 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005452
Steve Naroff1c7d0672008-09-04 15:10:53 +00005453 // For blocks we enforce that qualifiers are identical.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005454 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff1c7d0672008-09-04 15:10:53 +00005455 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005456
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005457 if (!getLangOptions().CPlusPlus) {
5458 if (!Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5459 return IncompatibleBlockPointer;
5460 }
5461 else if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00005462 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00005463 return ConvTy;
5464}
5465
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005466/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
5467/// for assignment compatibility.
5468Sema::AssignConvertType
5469Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005470 if (lhsType->isObjCBuiltinType()) {
5471 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00005472 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5473 !rhsType->isObjCQualifiedClassType())
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005474 return IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005475 return Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005476 }
5477 if (rhsType->isObjCBuiltinType()) {
5478 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00005479 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5480 !lhsType->isObjCQualifiedClassType())
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005481 return IncompatiblePointer;
5482 return Compatible;
5483 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005484 QualType lhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005485 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005486 QualType rhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005487 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
5488 // make sure we operate on the canonical type
5489 lhptee = Context.getCanonicalType(lhptee);
5490 rhptee = Context.getCanonicalType(rhptee);
5491 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5492 return CompatiblePointerDiscardsQualifiers;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005493
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005494 if (Context.typesAreCompatible(lhsType, rhsType))
5495 return Compatible;
5496 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
5497 return IncompatibleObjCQualifiedId;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005498 return IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005499}
5500
John McCall1c23e912010-11-16 02:32:08 +00005501Sema::AssignConvertType
5502Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
5503 // Fake up an opaque expression. We don't actually care about what
5504 // cast operations are required, so if CheckAssignmentConstraints
5505 // adds casts to this they'll be wasted, but fortunately that doesn't
5506 // usually happen on valid code.
5507 OpaqueValueExpr rhs(rhsType, VK_RValue);
5508 Expr *rhsPtr = &rhs;
5509 CastKind K = CK_Invalid;
5510
5511 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5512}
5513
Mike Stumpeed9cac2009-02-19 03:04:26 +00005514/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5515/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005516/// pointers. Here are some objectionable examples that GCC considers warnings:
5517///
5518/// int a, *pint;
5519/// short *pshort;
5520/// struct foo *pfoo;
5521///
5522/// pint = pshort; // warning: assignment from incompatible pointer type
5523/// a = pint; // warning: assignment makes integer from pointer without a cast
5524/// pint = a; // warning: assignment makes pointer from integer without a cast
5525/// pint = pfoo; // warning: assignment from incompatible pointer type
5526///
5527/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005528/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005529///
John McCalldaa8e4e2010-11-15 09:13:47 +00005530/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005531Sema::AssignConvertType
John McCall1c23e912010-11-16 02:32:08 +00005532Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs,
John McCalldaa8e4e2010-11-15 09:13:47 +00005533 CastKind &Kind) {
John McCall1c23e912010-11-16 02:32:08 +00005534 QualType rhsType = rhs->getType();
5535
Chris Lattnerfc144e22008-01-04 23:18:45 +00005536 // Get canonical types. We're not formatting these types, just comparing
5537 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00005538 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5539 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005540
John McCalldaa8e4e2010-11-15 09:13:47 +00005541 if (lhsType == rhsType) {
5542 Kind = CK_NoOp;
Chris Lattnerd2656dd2008-01-07 17:51:46 +00005543 return Compatible; // Common case: fast path an exact match.
John McCalldaa8e4e2010-11-15 09:13:47 +00005544 }
Steve Naroff700204c2007-07-24 21:46:40 +00005545
David Chisnall0f436562009-08-17 16:35:33 +00005546 if ((lhsType->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005547 (Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType))) ||
David Chisnall0f436562009-08-17 16:35:33 +00005548 (rhsType->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00005549 (Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)))) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005550 Kind = CK_BitCast;
5551 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005552 }
5553
Douglas Gregor9d293df2008-10-28 00:22:11 +00005554 // If the left-hand side is a reference type, then we are in a
5555 // (rare!) case where we've allowed the use of references in C,
5556 // e.g., as a parameter type in a built-in function. In this case,
5557 // just make sure that the type referenced is compatible with the
5558 // right-hand side type. The caller is responsible for adjusting
5559 // lhsType so that the resulting expression does not have reference
5560 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005561 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005562 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5563 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005564 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005565 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005566 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005567 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005568 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5569 // to the same ExtVector type.
5570 if (lhsType->isExtVectorType()) {
5571 if (rhsType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005572 return Incompatible;
5573 if (rhsType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005574 // CK_VectorSplat does T -> vector T, so first cast to the
5575 // element type.
5576 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5577 if (elType != rhsType) {
5578 Kind = PrepareScalarCast(*this, rhs, elType);
5579 ImpCastExprToType(rhs, elType, Kind);
5580 }
5581 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005582 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005583 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005584 }
Mike Stump1eb44332009-09-09 15:08:12 +00005585
Nate Begemanbe2341d2008-07-14 18:02:46 +00005586 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor255210e2010-08-06 10:14:59 +00005587 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005588 // Allow assignments of an AltiVec vector type to an equivalent GCC
5589 // vector type and vice versa
5590 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5591 Kind = CK_BitCast;
5592 return Compatible;
5593 }
5594
Douglas Gregor255210e2010-08-06 10:14:59 +00005595 // If we are allowing lax vector conversions, and LHS and RHS are both
5596 // vectors, the total size only needs to be the same. This is a bitcast;
5597 // no bits are changed but the result type is different.
5598 if (getLangOptions().LaxVectorConversions &&
John McCalldaa8e4e2010-11-15 09:13:47 +00005599 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005600 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005601 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005602 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005603 }
5604 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005605 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005606
Douglas Gregor88623ad2010-05-23 21:53:47 +00005607 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00005608 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall1c23e912010-11-16 02:32:08 +00005609 Kind = PrepareScalarCast(*this, rhs, lhsType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005610 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005611 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005612
Chris Lattner78eca282008-04-07 06:49:41 +00005613 if (isa<PointerType>(lhsType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005614 if (rhsType->isIntegerType()) {
5615 Kind = CK_IntegralToPointer; // FIXME: null?
Chris Lattnerb7b61152008-01-04 18:22:42 +00005616 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005617 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005618
John McCalldaa8e4e2010-11-15 09:13:47 +00005619 if (isa<PointerType>(rhsType)) {
5620 Kind = CK_BitCast;
Reid Spencer5f016e22007-07-11 17:01:13 +00005621 return CheckPointerTypesForAssignment(lhsType, rhsType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005622 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005623
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005624 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00005625 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005626 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005627 if (lhsType->isVoidPointerType()) // an exception to the rule.
5628 return Compatible;
5629 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005630 }
Ted Kremenek6217b802009-07-29 21:53:49 +00005631 if (rhsType->getAs<BlockPointerType>()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005632 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
5633 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005634 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005635 }
Steve Naroffb4406862008-09-29 18:10:17 +00005636
5637 // Treat block pointers as objects.
John McCalldaa8e4e2010-11-15 09:13:47 +00005638 if (getLangOptions().ObjC1 && lhsType->isObjCIdType()) {
5639 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005640 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005641 }
Steve Naroffb4406862008-09-29 18:10:17 +00005642 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00005643 return Incompatible;
5644 }
5645
5646 if (isa<BlockPointerType>(lhsType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005647 if (rhsType->isIntegerType()) {
5648 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005649 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005650 }
5651
5652 Kind = CK_AnyPointerToObjCPointerCast;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005653
Steve Naroffb4406862008-09-29 18:10:17 +00005654 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00005655 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00005656 return Compatible;
5657
Steve Naroff1c7d0672008-09-04 15:10:53 +00005658 if (rhsType->isBlockPointerType())
5659 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005660
John McCalldaa8e4e2010-11-15 09:13:47 +00005661 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
Steve Naroff1c7d0672008-09-04 15:10:53 +00005662 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00005663 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005664
Chris Lattnerfc144e22008-01-04 23:18:45 +00005665 return Incompatible;
5666 }
5667
Steve Naroff14108da2009-07-10 23:34:53 +00005668 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005669 if (rhsType->isIntegerType()) {
5670 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005671 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005672 }
5673
5674 Kind = CK_BitCast;
Mike Stump1eb44332009-09-09 15:08:12 +00005675
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005676 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00005677 if (isa<PointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005678 if (rhsType->isVoidPointerType()) // an exception to the rule.
5679 return Compatible;
5680 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005681 }
5682 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005683 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff14108da2009-07-10 23:34:53 +00005684 }
Ted Kremenek6217b802009-07-29 21:53:49 +00005685 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00005686 if (RHSPT->getPointeeType()->isVoidType())
5687 return Compatible;
5688 }
5689 // Treat block pointers as objects.
5690 if (rhsType->isBlockPointerType())
5691 return Compatible;
5692 return Incompatible;
5693 }
Chris Lattner78eca282008-04-07 06:49:41 +00005694 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005695 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
John McCalldaa8e4e2010-11-15 09:13:47 +00005696 if (lhsType == Context.BoolTy) {
5697 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005698 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005699 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005700
John McCalldaa8e4e2010-11-15 09:13:47 +00005701 if (lhsType->isIntegerType()) {
5702 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005703 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005704 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005705
5706 if (isa<BlockPointerType>(lhsType) &&
John McCalldaa8e4e2010-11-15 09:13:47 +00005707 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
5708 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005709 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005710 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005711 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005712 }
Steve Naroff14108da2009-07-10 23:34:53 +00005713 if (isa<ObjCObjectPointerType>(rhsType)) {
5714 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
John McCalldaa8e4e2010-11-15 09:13:47 +00005715 if (lhsType == Context.BoolTy) {
5716 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005717 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005718 }
Steve Naroff14108da2009-07-10 23:34:53 +00005719
John McCalldaa8e4e2010-11-15 09:13:47 +00005720 if (lhsType->isIntegerType()) {
5721 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005722 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005723 }
5724
5725 Kind = CK_BitCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005726
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005727 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00005728 if (isa<PointerType>(lhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005729 if (lhsType->isVoidPointerType()) // an exception to the rule.
5730 return Compatible;
5731 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005732 }
5733 if (isa<BlockPointerType>(lhsType) &&
John McCalldaa8e4e2010-11-15 09:13:47 +00005734 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
5735 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005736 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005737 }
Steve Naroff14108da2009-07-10 23:34:53 +00005738 return Incompatible;
5739 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005740
Chris Lattnerfc144e22008-01-04 23:18:45 +00005741 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005742 if (Context.typesAreCompatible(lhsType, rhsType)) {
5743 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005744 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005745 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005746 }
5747 return Incompatible;
5748}
5749
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005750/// \brief Constructs a transparent union from an expression that is
5751/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00005752static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005753 QualType UnionType, FieldDecl *Field) {
5754 // Build an initializer list that designates the appropriate member
5755 // of the transparent union.
Ted Kremenek709210f2010-04-13 23:39:13 +00005756 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00005757 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005758 SourceLocation());
5759 Initializer->setType(UnionType);
5760 Initializer->setInitializedFieldInUnion(Field);
5761
5762 // Build a compound literal constructing a value of the transparent
5763 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00005764 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall1d7d8d62010-01-19 22:33:45 +00005765 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCallf89e55a2010-11-18 06:31:45 +00005766 VK_RValue, Initializer, false);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005767}
5768
5769Sema::AssignConvertType
5770Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
5771 QualType FromType = rExpr->getType();
5772
Mike Stump1eb44332009-09-09 15:08:12 +00005773 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005774 // transparent_union GCC extension.
5775 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005776 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005777 return Incompatible;
5778
5779 // The field to initialize within the transparent union.
5780 RecordDecl *UD = UT->getDecl();
5781 FieldDecl *InitField = 0;
5782 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005783 for (RecordDecl::field_iterator it = UD->field_begin(),
5784 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005785 it != itend; ++it) {
5786 if (it->getType()->isPointerType()) {
5787 // If the transparent union contains a pointer type, we allow:
5788 // 1) void pointer
5789 // 2) null pointer constant
5790 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00005791 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John McCall2de56d12010-08-25 11:45:40 +00005792 ImpCastExprToType(rExpr, it->getType(), CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005793 InitField = *it;
5794 break;
5795 }
Mike Stump1eb44332009-09-09 15:08:12 +00005796
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005797 if (rExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005798 Expr::NPC_ValueDependentIsNull)) {
John McCall404cd162010-11-13 01:35:44 +00005799 ImpCastExprToType(rExpr, it->getType(), CK_NullToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005800 InitField = *it;
5801 break;
5802 }
5803 }
5804
John McCall1c23e912010-11-16 02:32:08 +00005805 Expr *rhs = rExpr;
John McCalldaa8e4e2010-11-15 09:13:47 +00005806 CastKind Kind = CK_Invalid;
John McCall1c23e912010-11-16 02:32:08 +00005807 if (CheckAssignmentConstraints(it->getType(), rhs, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005808 == Compatible) {
John McCall1c23e912010-11-16 02:32:08 +00005809 ImpCastExprToType(rhs, it->getType(), Kind);
5810 rExpr = rhs;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005811 InitField = *it;
5812 break;
5813 }
5814 }
5815
5816 if (!InitField)
5817 return Incompatible;
5818
5819 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
5820 return Compatible;
5821}
5822
Chris Lattner5cf216b2008-01-04 18:04:52 +00005823Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00005824Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005825 if (getLangOptions().CPlusPlus) {
5826 if (!lhsType->isRecordType()) {
5827 // C++ 5.17p3: If the left operand is not of class type, the
5828 // expression is implicitly converted (C++ 4) to the
5829 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00005830 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor68647482009-12-16 03:45:30 +00005831 AA_Assigning))
Douglas Gregor98cd5992008-10-21 23:43:52 +00005832 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00005833 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00005834 }
5835
5836 // FIXME: Currently, we fall through and treat C++ classes like C
5837 // structures.
John McCallf6a16482010-12-04 03:47:34 +00005838 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00005839
Steve Naroff529a4ad2007-11-27 17:58:44 +00005840 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5841 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00005842 if ((lhsType->isPointerType() ||
5843 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00005844 lhsType->isBlockPointerType())
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005845 && rExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005846 Expr::NPC_ValueDependentIsNull)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005847 ImpCastExprToType(rExpr, lhsType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00005848 return Compatible;
5849 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005850
Chris Lattner943140e2007-10-16 02:55:40 +00005851 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00005852 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00005853 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00005854 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00005855 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00005856 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00005857 if (!lhsType->isReferenceType())
Douglas Gregora873dfc2010-02-03 00:27:59 +00005858 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00005859
John McCalldaa8e4e2010-11-15 09:13:47 +00005860 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005861 Sema::AssignConvertType result =
John McCall1c23e912010-11-16 02:32:08 +00005862 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005863
Steve Narofff1120de2007-08-24 22:33:52 +00005864 // C99 6.5.16.1p2: The value of the right operand is converted to the
5865 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00005866 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5867 // so that we can use references in built-in functions even in C.
5868 // The getNonReferenceType() call makes sure that the resulting expression
5869 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005870 if (result != Incompatible && rExpr->getType() != lhsType)
John McCalldaa8e4e2010-11-15 09:13:47 +00005871 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00005872 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00005873}
5874
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005875QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005876 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00005877 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005878 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00005879 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005880}
5881
Chris Lattner7ef655a2010-01-12 21:23:57 +00005882QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00005883 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005884 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00005885 QualType lhsType =
5886 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
5887 QualType rhsType =
5888 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005889
Nate Begemanbe2341d2008-07-14 18:02:46 +00005890 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005891 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00005892 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00005893
Nate Begemanbe2341d2008-07-14 18:02:46 +00005894 // Handle the case of a vector & extvector type of the same size and element
5895 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005896 if (getLangOptions().LaxVectorConversions) {
John McCall183700f2009-09-21 23:43:11 +00005897 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth629f9e42010-08-30 07:36:24 +00005898 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00005899 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005900 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregor26bcf672010-05-19 03:21:00 +00005901 if (lhsType->isExtVectorType()) {
John McCall2de56d12010-08-25 11:45:40 +00005902 ImpCastExprToType(rex, lhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00005903 return lhsType;
5904 }
5905
John McCall2de56d12010-08-25 11:45:40 +00005906 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00005907 return rhsType;
Eric Christophere84f9eb2010-08-26 00:42:16 +00005908 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
5909 // If we are allowing lax vector conversions, and LHS and RHS are both
5910 // vectors, the total size only needs to be the same. This is a
5911 // bitcast; no bits are changed but the result type is different.
5912 ImpCastExprToType(rex, lhsType, CK_BitCast);
5913 return lhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005914 }
Eric Christophere84f9eb2010-08-26 00:42:16 +00005915 }
Chandler Carruth629f9e42010-08-30 07:36:24 +00005916 }
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005917 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005918
Douglas Gregor255210e2010-08-06 10:14:59 +00005919 // Handle the case of equivalent AltiVec and GCC vector types
5920 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5921 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John McCall2de56d12010-08-25 11:45:40 +00005922 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor255210e2010-08-06 10:14:59 +00005923 return rhsType;
5924 }
5925
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005926 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5927 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5928 bool swapped = false;
5929 if (rhsType->isExtVectorType()) {
5930 swapped = true;
5931 std::swap(rex, lex);
5932 std::swap(rhsType, lhsType);
5933 }
Mike Stump1eb44332009-09-09 15:08:12 +00005934
Nate Begemandde25982009-06-28 19:12:57 +00005935 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00005936 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005937 QualType EltTy = LV->getElementType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00005938 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005939 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
5940 if (order > 0)
5941 ImpCastExprToType(rex, EltTy, CK_IntegralCast);
5942 if (order >= 0) {
5943 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005944 if (swapped) std::swap(rex, lex);
5945 return lhsType;
5946 }
5947 }
5948 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5949 rhsType->isRealFloatingType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005950 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
5951 if (order > 0)
5952 ImpCastExprToType(rex, EltTy, CK_FloatingCast);
5953 if (order >= 0) {
5954 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005955 if (swapped) std::swap(rex, lex);
5956 return lhsType;
5957 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00005958 }
5959 }
Mike Stump1eb44332009-09-09 15:08:12 +00005960
Nate Begemandde25982009-06-28 19:12:57 +00005961 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005962 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00005963 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005964 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005965 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00005966}
5967
Chris Lattner7ef655a2010-01-12 21:23:57 +00005968QualType Sema::CheckMultiplyDivideOperands(
5969 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00005970 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005971 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005972
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005973 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005974
Chris Lattner7ef655a2010-01-12 21:23:57 +00005975 if (!lex->getType()->isArithmeticType() ||
5976 !rex->getType()->isArithmeticType())
5977 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005978
Chris Lattner7ef655a2010-01-12 21:23:57 +00005979 // Check for division by zero.
5980 if (isDiv &&
5981 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005982 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
Chris Lattnercb329c52010-01-12 21:30:55 +00005983 << rex->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005984
Chris Lattner7ef655a2010-01-12 21:23:57 +00005985 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005986}
5987
Chris Lattner7ef655a2010-01-12 21:23:57 +00005988QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00005989 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00005990 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
Douglas Gregorf6094622010-07-23 15:58:24 +00005991 if (lex->getType()->hasIntegerRepresentation() &&
5992 rex->getType()->hasIntegerRepresentation())
Daniel Dunbar523aa602009-01-05 22:55:36 +00005993 return CheckVectorOperands(Loc, lex, rex);
5994 return InvalidOperands(Loc, lex, rex);
5995 }
Steve Naroff90045e82007-07-13 23:32:42 +00005996
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005997 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005998
Chris Lattner7ef655a2010-01-12 21:23:57 +00005999 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
6000 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006001
Chris Lattner7ef655a2010-01-12 21:23:57 +00006002 // Check for remainder by zero.
6003 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattnercb329c52010-01-12 21:30:55 +00006004 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
6005 << rex->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006006
Chris Lattner7ef655a2010-01-12 21:23:57 +00006007 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006008}
6009
Chris Lattner7ef655a2010-01-12 21:23:57 +00006010QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00006011 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006012 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6013 QualType compType = CheckVectorOperands(Loc, lex, rex);
6014 if (CompLHSTy) *CompLHSTy = compType;
6015 return compType;
6016 }
Steve Naroff49b45262007-07-13 16:58:59 +00006017
Eli Friedmanab3a8522009-03-28 01:22:36 +00006018 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00006019
Reid Spencer5f016e22007-07-11 17:01:13 +00006020 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00006021 if (lex->getType()->isArithmeticType() &&
6022 rex->getType()->isArithmeticType()) {
6023 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006024 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006025 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006026
Eli Friedmand72d16e2008-05-18 18:08:51 +00006027 // Put any potential pointer into PExp
6028 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006029 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00006030 std::swap(PExp, IExp);
6031
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006032 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006033
Eli Friedmand72d16e2008-05-18 18:08:51 +00006034 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00006035 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00006036
Chris Lattnerb5f15622009-04-24 23:50:08 +00006037 // Check for arithmetic on pointers to incomplete types.
6038 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006039 if (getLangOptions().CPlusPlus) {
6040 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006041 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006042 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006043 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006044
6045 // GNU extension: arithmetic on pointer to void
6046 Diag(Loc, diag::ext_gnu_void_ptr)
6047 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00006048 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006049 if (getLangOptions().CPlusPlus) {
6050 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6051 << lex->getType() << lex->getSourceRange();
6052 return QualType();
6053 }
6054
6055 // GNU extension: arithmetic on pointer to function
6056 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6057 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00006058 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00006059 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00006060 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00006061 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00006062 PExp->getType()->isObjCObjectPointerType()) &&
6063 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00006064 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6065 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00006066 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00006067 return QualType();
6068 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00006069 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00006070 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00006071 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6072 << PointeeTy << PExp->getSourceRange();
6073 return QualType();
6074 }
Mike Stump1eb44332009-09-09 15:08:12 +00006075
Eli Friedmanab3a8522009-03-28 01:22:36 +00006076 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00006077 QualType LHSTy = Context.isPromotableBitField(lex);
6078 if (LHSTy.isNull()) {
6079 LHSTy = lex->getType();
6080 if (LHSTy->isPromotableIntegerType())
6081 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00006082 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00006083 *CompLHSTy = LHSTy;
6084 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00006085 return PExp->getType();
6086 }
6087 }
6088
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006089 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006090}
6091
Chris Lattnereca7be62008-04-07 05:30:13 +00006092// C99 6.5.6
6093QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00006094 SourceLocation Loc, QualType* CompLHSTy) {
6095 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6096 QualType compType = CheckVectorOperands(Loc, lex, rex);
6097 if (CompLHSTy) *CompLHSTy = compType;
6098 return compType;
6099 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006100
Eli Friedmanab3a8522009-03-28 01:22:36 +00006101 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006102
Chris Lattner6e4ab612007-12-09 21:53:25 +00006103 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006104
Chris Lattner6e4ab612007-12-09 21:53:25 +00006105 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00006106 if (lex->getType()->isArithmeticType()
6107 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006108 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006109 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006110 }
Mike Stump1eb44332009-09-09 15:08:12 +00006111
Chris Lattner6e4ab612007-12-09 21:53:25 +00006112 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006113 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00006114 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006115
Douglas Gregore7450f52009-03-24 19:52:54 +00006116 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00006117
Douglas Gregore7450f52009-03-24 19:52:54 +00006118 bool ComplainAboutVoid = false;
6119 Expr *ComplainAboutFunc = 0;
6120 if (lpointee->isVoidType()) {
6121 if (getLangOptions().CPlusPlus) {
6122 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6123 << lex->getSourceRange() << rex->getSourceRange();
6124 return QualType();
6125 }
6126
6127 // GNU C extension: arithmetic on pointer to void
6128 ComplainAboutVoid = true;
6129 } else if (lpointee->isFunctionType()) {
6130 if (getLangOptions().CPlusPlus) {
6131 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00006132 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006133 return QualType();
6134 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006135
6136 // GNU C extension: arithmetic on pointer to function
6137 ComplainAboutFunc = lex;
6138 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00006139 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00006140 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00006141 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00006142 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00006143 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006144
Chris Lattnerb5f15622009-04-24 23:50:08 +00006145 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00006146 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00006147 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6148 << lpointee << lex->getSourceRange();
6149 return QualType();
6150 }
Mike Stump1eb44332009-09-09 15:08:12 +00006151
Chris Lattner6e4ab612007-12-09 21:53:25 +00006152 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00006153 if (rex->getType()->isIntegerType()) {
6154 if (ComplainAboutVoid)
6155 Diag(Loc, diag::ext_gnu_void_ptr)
6156 << lex->getSourceRange() << rex->getSourceRange();
6157 if (ComplainAboutFunc)
6158 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00006159 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00006160 << ComplainAboutFunc->getSourceRange();
6161
Eli Friedmanab3a8522009-03-28 01:22:36 +00006162 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006163 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006164 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006165
Chris Lattner6e4ab612007-12-09 21:53:25 +00006166 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006167 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006168 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006169
Douglas Gregore7450f52009-03-24 19:52:54 +00006170 // RHS must be a completely-type object type.
6171 // Handle the GNU void* extension.
6172 if (rpointee->isVoidType()) {
6173 if (getLangOptions().CPlusPlus) {
6174 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6175 << lex->getSourceRange() << rex->getSourceRange();
6176 return QualType();
6177 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006178
Douglas Gregore7450f52009-03-24 19:52:54 +00006179 ComplainAboutVoid = true;
6180 } else if (rpointee->isFunctionType()) {
6181 if (getLangOptions().CPlusPlus) {
6182 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00006183 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006184 return QualType();
6185 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006186
6187 // GNU extension: arithmetic on pointer to function
6188 if (!ComplainAboutFunc)
6189 ComplainAboutFunc = rex;
6190 } else if (!rpointee->isDependentType() &&
6191 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00006192 PDiag(diag::err_typecheck_sub_ptr_object)
6193 << rex->getSourceRange()
6194 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00006195 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006196
Eli Friedman88d936b2009-05-16 13:54:38 +00006197 if (getLangOptions().CPlusPlus) {
6198 // Pointee types must be the same: C++ [expr.add]
6199 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6200 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6201 << lex->getType() << rex->getType()
6202 << lex->getSourceRange() << rex->getSourceRange();
6203 return QualType();
6204 }
6205 } else {
6206 // Pointee types must be compatible C99 6.5.6p3
6207 if (!Context.typesAreCompatible(
6208 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6209 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6210 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6211 << lex->getType() << rex->getType()
6212 << lex->getSourceRange() << rex->getSourceRange();
6213 return QualType();
6214 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006215 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006216
Douglas Gregore7450f52009-03-24 19:52:54 +00006217 if (ComplainAboutVoid)
6218 Diag(Loc, diag::ext_gnu_void_ptr)
6219 << lex->getSourceRange() << rex->getSourceRange();
6220 if (ComplainAboutFunc)
6221 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00006222 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00006223 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006224
6225 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006226 return Context.getPointerDiffType();
6227 }
6228 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006229
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006230 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006231}
6232
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006233static bool isScopedEnumerationType(QualType T) {
6234 if (const EnumType *ET = dyn_cast<EnumType>(T))
6235 return ET->getDecl()->isScoped();
6236 return false;
6237}
6238
Chris Lattnereca7be62008-04-07 05:30:13 +00006239// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006240QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00006241 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00006242 // C99 6.5.7p2: Each of the operands shall have integer type.
Douglas Gregorf6094622010-07-23 15:58:24 +00006243 if (!lex->getType()->hasIntegerRepresentation() ||
6244 !rex->getType()->hasIntegerRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006245 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006246
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006247 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6248 // hasIntegerRepresentation() above instead of this.
6249 if (isScopedEnumerationType(lex->getType()) ||
6250 isScopedEnumerationType(rex->getType())) {
6251 return InvalidOperands(Loc, lex, rex);
6252 }
6253
Nate Begeman2207d792009-10-25 02:26:48 +00006254 // Vector shifts promote their scalar inputs to vector type.
6255 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6256 return CheckVectorOperands(Loc, lex, rex);
6257
Chris Lattnerca5eede2007-12-12 05:47:28 +00006258 // Shifts don't perform usual arithmetic conversions, they just do integer
6259 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006260
John McCall1bc80af2010-12-16 19:28:59 +00006261 // For the LHS, do usual unary conversions, but then reset them away
6262 // if this is a compound assignment.
6263 Expr *old_lex = lex;
6264 UsualUnaryConversions(lex);
6265 QualType LHSTy = lex->getType();
6266 if (isCompAssign) lex = old_lex;
6267
6268 // The RHS is simpler.
Chris Lattnerca5eede2007-12-12 05:47:28 +00006269 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006270
Ryan Flynnd0439682009-08-07 16:20:20 +00006271 // Sanity-check shift operands
6272 llvm::APSInt Right;
6273 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00006274 if (!rex->isValueDependent() &&
6275 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00006276 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00006277 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
6278 else {
6279 llvm::APInt LeftBits(Right.getBitWidth(),
6280 Context.getTypeSize(lex->getType()));
6281 if (Right.uge(LeftBits))
6282 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
6283 }
6284 }
6285
Chris Lattnerca5eede2007-12-12 05:47:28 +00006286 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00006287 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006288}
6289
Chandler Carruth99919472010-07-10 12:30:03 +00006290static bool IsWithinTemplateSpecialization(Decl *D) {
6291 if (DeclContext *DC = D->getDeclContext()) {
6292 if (isa<ClassTemplateSpecializationDecl>(DC))
6293 return true;
6294 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6295 return FD->isFunctionTemplateSpecialization();
6296 }
6297 return false;
6298}
6299
Douglas Gregor0c6db942009-05-04 06:07:12 +00006300// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006301QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00006302 unsigned OpaqueOpc, bool isRelational) {
John McCall2de56d12010-08-25 11:45:40 +00006303 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006304
Chris Lattner02dd4b12009-12-05 05:40:13 +00006305 // Handle vector comparisons separately.
Nate Begemanbe2341d2008-07-14 18:02:46 +00006306 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006307 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006308
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006309 QualType lType = lex->getType();
6310 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006311
Douglas Gregor8eee1192010-06-22 22:12:46 +00006312 if (!lType->hasFloatingRepresentation() &&
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006313 !(lType->isBlockPointerType() && isRelational) &&
6314 !lex->getLocStart().isMacroID() &&
6315 !rex->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006316 // For non-floating point types, check for self-comparisons of the form
6317 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6318 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006319 //
6320 // NOTE: Don't warn about comparison expressions resulting from macro
6321 // expansion. Also don't warn about comparisons which are only self
6322 // comparisons within a template specialization. The warnings should catch
6323 // obvious cases in the definition of the template anyways. The idea is to
6324 // warn when the typed comparison operator will always evaluate to the same
6325 // result.
John McCallf6a16482010-12-04 03:47:34 +00006326 Expr *LHSStripped = lex->IgnoreParenImpCasts();
6327 Expr *RHSStripped = rex->IgnoreParenImpCasts();
Chandler Carruth99919472010-07-10 12:30:03 +00006328 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006329 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006330 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006331 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006332 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6333 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006334 << (Opc == BO_EQ
6335 || Opc == BO_LE
6336 || Opc == BO_GE));
Douglas Gregord64fdd02010-06-08 19:50:34 +00006337 } else if (lType->isArrayType() && rType->isArrayType() &&
6338 !DRL->getDecl()->getType()->isReferenceType() &&
6339 !DRR->getDecl()->getType()->isReferenceType()) {
6340 // what is it always going to eval to?
6341 char always_evals_to;
6342 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006343 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006344 always_evals_to = 0; // false
6345 break;
John McCall2de56d12010-08-25 11:45:40 +00006346 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006347 always_evals_to = 1; // true
6348 break;
6349 default:
6350 // best we can say is 'a constant'
6351 always_evals_to = 2; // e.g. array1 <= array2
6352 break;
6353 }
6354 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6355 << 1 // array
6356 << always_evals_to);
6357 }
6358 }
Chandler Carruth99919472010-07-10 12:30:03 +00006359 }
Mike Stump1eb44332009-09-09 15:08:12 +00006360
Chris Lattner55660a72009-03-08 19:39:53 +00006361 if (isa<CastExpr>(LHSStripped))
6362 LHSStripped = LHSStripped->IgnoreParenCasts();
6363 if (isa<CastExpr>(RHSStripped))
6364 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006365
Chris Lattner55660a72009-03-08 19:39:53 +00006366 // Warn about comparisons against a string constant (unless the other
6367 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00006368 Expr *literalString = 0;
6369 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00006370 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006371 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006372 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00006373 literalString = lex;
6374 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006375 } else if ((isa<StringLiteral>(RHSStripped) ||
6376 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006377 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006378 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00006379 literalString = rex;
6380 literalStringStripped = RHSStripped;
6381 }
6382
6383 if (literalString) {
6384 std::string resultComparison;
6385 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006386 case BO_LT: resultComparison = ") < 0"; break;
6387 case BO_GT: resultComparison = ") > 0"; break;
6388 case BO_LE: resultComparison = ") <= 0"; break;
6389 case BO_GE: resultComparison = ") >= 0"; break;
6390 case BO_EQ: resultComparison = ") == 0"; break;
6391 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregora86b8322009-04-06 18:45:53 +00006392 default: assert(false && "Invalid comparison operator");
6393 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006394
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00006395 DiagRuntimeBehavior(Loc,
6396 PDiag(diag::warn_stringcompare)
6397 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00006398 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00006399 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00006400 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006401
Douglas Gregord64fdd02010-06-08 19:50:34 +00006402 // C99 6.5.8p3 / C99 6.5.9p4
6403 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
6404 UsualArithmeticConversions(lex, rex);
6405 else {
6406 UsualUnaryConversions(lex);
6407 UsualUnaryConversions(rex);
6408 }
6409
6410 lType = lex->getType();
6411 rType = rex->getType();
6412
Douglas Gregor447b69e2008-11-19 03:25:36 +00006413 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner02dd4b12009-12-05 05:40:13 +00006414 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00006415
Chris Lattnera5937dd2007-08-26 01:18:55 +00006416 if (isRelational) {
6417 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006418 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006419 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00006420 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006421 if (lType->hasFloatingRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006422 CheckFloatComparison(Loc,lex,rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006423
Chris Lattnera5937dd2007-08-26 01:18:55 +00006424 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006425 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006426 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006427
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006428 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006429 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006430 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006431 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006432
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006433 // All of the following pointer-related warnings are GCC extensions, except
6434 // when handling null pointer constants.
Steve Naroff77878cc2007-08-27 04:08:11 +00006435 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00006436 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00006437 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00006438 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00006439 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006440
Douglas Gregor0c6db942009-05-04 06:07:12 +00006441 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00006442 if (LCanPointeeTy == RCanPointeeTy)
6443 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006444 if (!isRelational &&
6445 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6446 // Valid unless comparison between non-null pointer and function pointer
6447 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006448 // In a SFINAE context, we treat this as a hard error to maintain
6449 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006450 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6451 && !LHSIsNull && !RHSIsNull) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006452 Diag(Loc,
6453 isSFINAEContext()?
6454 diag::err_typecheck_comparison_of_fptr_to_void
6455 : diag::ext_typecheck_comparison_of_fptr_to_void)
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006456 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006457
6458 if (isSFINAEContext())
6459 return QualType();
6460
John McCall2de56d12010-08-25 11:45:40 +00006461 ImpCastExprToType(rex, lType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006462 return ResultTy;
6463 }
6464 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006465
Douglas Gregor0c6db942009-05-04 06:07:12 +00006466 // C++ [expr.rel]p2:
6467 // [...] Pointer conversions (4.10) and qualification
6468 // conversions (4.4) are performed on pointer operands (or on
6469 // a pointer operand and a null pointer constant) to bring
6470 // them to their composite pointer type. [...]
6471 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00006472 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00006473 // comparisons of pointers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006474 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00006475 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006476 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor0c6db942009-05-04 06:07:12 +00006477 if (T.isNull()) {
6478 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6479 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6480 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006481 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006482 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006483 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006484 << lType << rType << T
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006485 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00006486 }
6487
John McCall2de56d12010-08-25 11:45:40 +00006488 ImpCastExprToType(lex, T, CK_BitCast);
6489 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00006490 return ResultTy;
6491 }
Eli Friedman3075e762009-08-23 00:27:47 +00006492 // C99 6.5.9p2 and C99 6.5.8p2
6493 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6494 RCanPointeeTy.getUnqualifiedType())) {
6495 // Valid unless a relational comparison of function pointers
6496 if (isRelational && LCanPointeeTy->isFunctionType()) {
6497 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
6498 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6499 }
6500 } else if (!isRelational &&
6501 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6502 // Valid unless comparison between non-null pointer and function pointer
6503 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6504 && !LHSIsNull && !RHSIsNull) {
6505 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
6506 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6507 }
6508 } else {
6509 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006510 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00006511 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006512 }
Eli Friedman3075e762009-08-23 00:27:47 +00006513 if (LCanPointeeTy != RCanPointeeTy)
John McCall2de56d12010-08-25 11:45:40 +00006514 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006515 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00006516 }
Mike Stump1eb44332009-09-09 15:08:12 +00006517
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006518 if (getLangOptions().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006519 // Comparison of nullptr_t with itself.
6520 if (lType->isNullPtrType() && rType->isNullPtrType())
6521 return ResultTy;
6522
Mike Stump1eb44332009-09-09 15:08:12 +00006523 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00006524 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00006525 if (RHSIsNull &&
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006526 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregor20b3e992009-08-24 17:42:35 +00006527 (!isRelational && lType->isMemberPointerType()))) {
Douglas Gregor443c2122010-08-07 13:36:37 +00006528 ImpCastExprToType(rex, lType,
6529 lType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006530 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006531 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006532 return ResultTy;
6533 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006534 if (LHSIsNull &&
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006535 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregor20b3e992009-08-24 17:42:35 +00006536 (!isRelational && rType->isMemberPointerType()))) {
Douglas Gregor443c2122010-08-07 13:36:37 +00006537 ImpCastExprToType(lex, rType,
6538 rType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006539 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006540 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006541 return ResultTy;
6542 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006543
6544 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00006545 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00006546 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6547 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00006548 // In addition, pointers to members can be compared, or a pointer to
6549 // member and a null pointer constant. Pointer to member conversions
6550 // (4.11) and qualification conversions (4.4) are performed to bring
6551 // them to a common type. If one operand is a null pointer constant,
6552 // the common type is the type of the other operand. Otherwise, the
6553 // common type is a pointer to member type similar (4.4) to the type
6554 // of one of the operands, with a cv-qualification signature (4.4)
6555 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00006556 // types.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006557 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00006558 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006559 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor20b3e992009-08-24 17:42:35 +00006560 if (T.isNull()) {
6561 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006562 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00006563 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006564 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006565 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006566 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006567 << lType << rType << T
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006568 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00006569 }
Mike Stump1eb44332009-09-09 15:08:12 +00006570
John McCall2de56d12010-08-25 11:45:40 +00006571 ImpCastExprToType(lex, T, CK_BitCast);
6572 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00006573 return ResultTy;
6574 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006575 }
Mike Stump1eb44332009-09-09 15:08:12 +00006576
Steve Naroff1c7d0672008-09-04 15:10:53 +00006577 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00006578 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00006579 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6580 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006581
Steve Naroff1c7d0672008-09-04 15:10:53 +00006582 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00006583 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006584 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00006585 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00006586 }
John McCall2de56d12010-08-25 11:45:40 +00006587 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006588 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006589 }
Steve Naroff59f53942008-09-28 01:11:11 +00006590 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00006591 if (!isRelational
6592 && ((lType->isBlockPointerType() && rType->isPointerType())
6593 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00006594 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00006595 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006596 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00006597 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006598 ->getPointeeType()->isVoidType())))
6599 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
6600 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00006601 }
John McCall2de56d12010-08-25 11:45:40 +00006602 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006603 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00006604 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00006605
Steve Naroff14108da2009-07-10 23:34:53 +00006606 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00006607 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00006608 const PointerType *LPT = lType->getAs<PointerType>();
6609 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006610 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00006611 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006612 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00006613 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006614
Steve Naroffa8069f12008-11-17 19:49:16 +00006615 if (!LPtrToVoid && !RPtrToVoid &&
6616 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006617 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00006618 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00006619 }
John McCall2de56d12010-08-25 11:45:40 +00006620 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006621 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00006622 }
Steve Naroff14108da2009-07-10 23:34:53 +00006623 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00006624 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00006625 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
6626 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00006627 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006628 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00006629 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00006630 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006631 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6632 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006633 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006634 bool isError = false;
6635 if ((LHSIsNull && lType->isIntegerType()) ||
6636 (RHSIsNull && rType->isIntegerType())) {
6637 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006638 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006639 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006640 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006641 else if (getLangOptions().CPlusPlus) {
6642 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6643 isError = true;
6644 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006645 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00006646
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006647 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00006648 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00006649 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006650 if (isError)
6651 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00006652 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006653
6654 if (lType->isIntegerType())
John McCall404cd162010-11-13 01:35:44 +00006655 ImpCastExprToType(lex, rType,
6656 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006657 else
John McCall404cd162010-11-13 01:35:44 +00006658 ImpCastExprToType(rex, lType,
6659 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006660 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006661 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006662
Steve Naroff39218df2008-09-04 16:56:14 +00006663 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00006664 if (!isRelational && RHSIsNull
6665 && lType->isBlockPointerType() && rType->isIntegerType()) {
John McCall404cd162010-11-13 01:35:44 +00006666 ImpCastExprToType(rex, lType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006667 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006668 }
Mike Stumpaf199f32009-05-07 18:43:07 +00006669 if (!isRelational && LHSIsNull
6670 && lType->isIntegerType() && rType->isBlockPointerType()) {
John McCall404cd162010-11-13 01:35:44 +00006671 ImpCastExprToType(lex, rType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006672 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006673 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006674 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006675}
6676
Nate Begemanbe2341d2008-07-14 18:02:46 +00006677/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00006678/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00006679/// like a scalar comparison, a vector comparison produces a vector of integer
6680/// types.
6681QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006682 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00006683 bool isRelational) {
6684 // Check to make sure we're operating on vectors of the same type and width,
6685 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006686 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00006687 if (vType.isNull())
6688 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006689
Anton Yartsevaa4fe052010-11-18 03:19:30 +00006690 // If AltiVec, the comparison results in a numeric type, i.e.
6691 // bool for C++, int for C
6692 if (getLangOptions().AltiVec)
6693 return (getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy);
6694
Nate Begemanbe2341d2008-07-14 18:02:46 +00006695 QualType lType = lex->getType();
6696 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006697
Nate Begemanbe2341d2008-07-14 18:02:46 +00006698 // For non-floating point types, check for self-comparisons of the form
6699 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6700 // often indicate logic errors in the program.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006701 if (!lType->hasFloatingRepresentation()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00006702 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
6703 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
6704 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregord64fdd02010-06-08 19:50:34 +00006705 DiagRuntimeBehavior(Loc,
6706 PDiag(diag::warn_comparison_always)
6707 << 0 // self-
6708 << 2 // "a constant"
6709 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00006710 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006711
Nate Begemanbe2341d2008-07-14 18:02:46 +00006712 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006713 if (!isRelational && lType->hasFloatingRepresentation()) {
6714 assert (rType->hasFloatingRepresentation());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006715 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00006716 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006717
Nate Begemanbe2341d2008-07-14 18:02:46 +00006718 // Return the type for the comparison, which is the same as vector type for
6719 // integer vectors, or an integer type of identical size and number of
6720 // elements for floating point vectors.
Douglas Gregorf6094622010-07-23 15:58:24 +00006721 if (lType->hasIntegerRepresentation())
Nate Begemanbe2341d2008-07-14 18:02:46 +00006722 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006723
John McCall183700f2009-09-21 23:43:11 +00006724 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00006725 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00006726 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00006727 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00006728 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00006729 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6730
Mike Stumpeed9cac2009-02-19 03:04:26 +00006731 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00006732 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00006733 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6734}
6735
Reid Spencer5f016e22007-07-11 17:01:13 +00006736inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00006737 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Douglas Gregorf6094622010-07-23 15:58:24 +00006738 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6739 if (lex->getType()->hasIntegerRepresentation() &&
6740 rex->getType()->hasIntegerRepresentation())
6741 return CheckVectorOperands(Loc, lex, rex);
6742
6743 return InvalidOperands(Loc, lex, rex);
6744 }
Steve Naroff90045e82007-07-13 23:32:42 +00006745
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006746 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006747
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006748 if (lex->getType()->isIntegralOrUnscopedEnumerationType() &&
6749 rex->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006750 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006751 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006752}
6753
6754inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner90a8f272010-07-13 19:41:32 +00006755 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
6756
6757 // Diagnose cases where the user write a logical and/or but probably meant a
6758 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6759 // is a constant.
6760 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
Eli Friedman787b0942010-07-27 19:14:53 +00006761 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
Chris Lattner23ef3e42010-07-15 00:26:43 +00006762 // Don't warn in macros.
Chris Lattnerb7690b42010-07-24 01:10:11 +00006763 !Loc.isMacroID()) {
6764 // If the RHS can be constant folded, and if it constant folds to something
6765 // that isn't 0 or 1 (which indicate a potential logical operation that
6766 // happened to fold to true/false) then warn.
6767 Expr::EvalResult Result;
6768 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
6769 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
6770 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6771 << rex->getSourceRange()
John McCall2de56d12010-08-25 11:45:40 +00006772 << (Opc == BO_LAnd ? "&&" : "||")
6773 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattnerb7690b42010-07-24 01:10:11 +00006774 }
6775 }
Chris Lattner90a8f272010-07-13 19:41:32 +00006776
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006777 if (!Context.getLangOptions().CPlusPlus) {
6778 UsualUnaryConversions(lex);
6779 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006780
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006781 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
6782 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006783
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006784 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00006785 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006786
John McCall75f7c0f2010-06-04 00:29:51 +00006787 // The following is safe because we only use this method for
6788 // non-overloadable operands.
6789
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006790 // C++ [expr.log.and]p1
6791 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00006792 // The operands are both contextually converted to type bool.
6793 if (PerformContextuallyConvertToBool(lex) ||
6794 PerformContextuallyConvertToBool(rex))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006795 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006796
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006797 // C++ [expr.log.and]p2
6798 // C++ [expr.log.or]p2
6799 // The result is a bool.
6800 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006801}
6802
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006803/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6804/// is a read-only property; return true if so. A readonly property expression
6805/// depends on various declarations and thus must be treated specially.
6806///
Mike Stump1eb44332009-09-09 15:08:12 +00006807static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006808 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6809 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCall12f78a62010-12-02 01:19:52 +00006810 if (PropExpr->isImplicitProperty()) return false;
6811
6812 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6813 QualType BaseType = PropExpr->isSuperReceiver() ?
6814 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00006815 PropExpr->getBase()->getType();
6816
John McCall12f78a62010-12-02 01:19:52 +00006817 if (const ObjCObjectPointerType *OPT =
6818 BaseType->getAsObjCInterfacePointerType())
6819 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6820 if (S.isPropertyReadonly(PDecl, IFace))
6821 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006822 }
6823 return false;
6824}
6825
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006826/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6827/// emit an error and return true. If so, return false.
6828static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006829 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00006830 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006831 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006832 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6833 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006834 if (IsLV == Expr::MLV_Valid)
6835 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006836
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006837 unsigned Diag = 0;
6838 bool NeedType = false;
6839 switch (IsLV) { // C99 6.5.16p2
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006840 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006841 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006842 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6843 NeedType = true;
6844 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006845 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006846 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6847 NeedType = true;
6848 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00006849 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006850 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6851 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00006852 case Expr::MLV_Valid:
6853 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00006854 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00006855 case Expr::MLV_MemberFunction:
6856 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006857 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6858 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006859 case Expr::MLV_IncompleteType:
6860 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00006861 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006862 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00006863 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00006864 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006865 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6866 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00006867 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006868 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6869 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00006870 case Expr::MLV_ReadonlyProperty:
6871 Diag = diag::error_readonly_property_assignment;
6872 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00006873 case Expr::MLV_NoSetterProperty:
6874 Diag = diag::error_nosetter_property_assignment;
6875 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00006876 case Expr::MLV_SubObjCPropertySetting:
6877 Diag = diag::error_no_subobject_property_setting;
6878 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006879 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00006880
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006881 SourceRange Assign;
6882 if (Loc != OrigLoc)
6883 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006884 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006885 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006886 else
Mike Stump1eb44332009-09-09 15:08:12 +00006887 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006888 return true;
6889}
6890
6891
6892
6893// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006894QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
6895 SourceLocation Loc,
6896 QualType CompoundType) {
6897 // Verify that LHS is a modifiable lvalue, and emit error if not.
6898 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006899 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006900
6901 QualType LHSType = LHS->getType();
6902 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006903 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006904 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00006905 QualType LHSTy(LHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00006906 // Simple assignment "x = y".
John McCallf6a16482010-12-04 03:47:34 +00006907 if (LHS->getObjectKind() == OK_ObjCProperty)
6908 ConvertPropertyForLValue(LHS, RHS, LHSTy);
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00006909 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00006910 // Special case of NSObject attributes on c-style pointer types.
6911 if (ConvTy == IncompatiblePointer &&
6912 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00006913 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00006914 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00006915 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00006916 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006917
John McCallf89e55a2010-11-18 06:31:45 +00006918 if (ConvTy == Compatible &&
6919 getLangOptions().ObjCNonFragileABI &&
6920 LHSType->isObjCObjectType())
6921 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
6922 << LHSType;
6923
Chris Lattner2c156472008-08-21 18:04:13 +00006924 // If the RHS is a unary plus or minus, check to see if they = and + are
6925 // right next to each other. If so, the user may have typo'd "x =+ 4"
6926 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006927 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00006928 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
6929 RHSCheck = ICE->getSubExpr();
6930 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00006931 if ((UO->getOpcode() == UO_Plus ||
6932 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006933 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00006934 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00006935 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
6936 // And there is a space or other character before the subexpr of the
6937 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00006938 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
6939 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006940 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00006941 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006942 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00006943 }
Chris Lattner2c156472008-08-21 18:04:13 +00006944 }
6945 } else {
6946 // Compound assignment "x += y"
John McCall1c23e912010-11-16 02:32:08 +00006947 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00006948 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00006949
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006950 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor68647482009-12-16 03:45:30 +00006951 RHS, AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00006952 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006953
Chris Lattner8b5dec32010-07-07 06:14:23 +00006954
6955 // Check to see if the destination operand is a dereferenced null pointer. If
6956 // so, and if not volatile-qualified, this is undefined behavior that the
6957 // optimizer will delete, so warn about it. People sometimes try to use this
6958 // to get a deterministic trap and are surprised by clang's behavior. This
6959 // only handles the pattern "*null = whatever", which is a very syntactic
6960 // check.
6961 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
John McCall2de56d12010-08-25 11:45:40 +00006962 if (UO->getOpcode() == UO_Deref &&
Chris Lattner8b5dec32010-07-07 06:14:23 +00006963 UO->getSubExpr()->IgnoreParenCasts()->
6964 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
6965 !UO->getType().isVolatileQualified()) {
6966 Diag(UO->getOperatorLoc(), diag::warn_indirection_through_null)
6967 << UO->getSubExpr()->getSourceRange();
6968 Diag(UO->getOperatorLoc(), diag::note_indirection_through_null);
6969 }
6970
Reid Spencer5f016e22007-07-11 17:01:13 +00006971 // C99 6.5.16p3: The type of an assignment expression is the type of the
6972 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00006973 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00006974 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
6975 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006976 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00006977 // operand.
John McCall2bf6f492010-10-12 02:19:57 +00006978 return (getLangOptions().CPlusPlus
6979 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00006980}
6981
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006982// C99 6.5.17
John McCallf6a16482010-12-04 03:47:34 +00006983static QualType CheckCommaOperands(Sema &S, Expr *&LHS, Expr *&RHS,
John McCall09431682010-11-18 19:01:18 +00006984 SourceLocation Loc) {
6985 S.DiagnoseUnusedExprResult(LHS);
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00006986
John McCall09431682010-11-18 19:01:18 +00006987 ExprResult LHSResult = S.CheckPlaceholderExpr(LHS, Loc);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00006988 if (LHSResult.isInvalid())
6989 return QualType();
6990
John McCall09431682010-11-18 19:01:18 +00006991 ExprResult RHSResult = S.CheckPlaceholderExpr(RHS, Loc);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00006992 if (RHSResult.isInvalid())
6993 return QualType();
6994 RHS = RHSResult.take();
6995
John McCallcf2e5062010-10-12 07:14:40 +00006996 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
6997 // operands, but not unary promotions.
6998 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006999
John McCallf6a16482010-12-04 03:47:34 +00007000 // So we treat the LHS as a ignored value, and in C++ we allow the
7001 // containing site to determine what should be done with the RHS.
7002 S.IgnoredValueConversions(LHS);
7003
7004 if (!S.getLangOptions().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007005 S.DefaultFunctionArrayLvalueConversion(RHS);
John McCallcf2e5062010-10-12 07:14:40 +00007006 if (!RHS->getType()->isVoidType())
John McCall09431682010-11-18 19:01:18 +00007007 S.RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007008 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007009
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007010 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007011}
7012
Steve Naroff49b45262007-07-13 16:58:59 +00007013/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7014/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007015static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7016 ExprValueKind &VK,
7017 SourceLocation OpLoc,
7018 bool isInc, bool isPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007019 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007020 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007021
Chris Lattner3528d352008-11-21 07:05:48 +00007022 QualType ResType = Op->getType();
7023 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007024
John McCall09431682010-11-18 19:01:18 +00007025 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007026 // Decrement of bool is not allowed.
7027 if (!isInc) {
John McCall09431682010-11-18 19:01:18 +00007028 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007029 return QualType();
7030 }
7031 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007032 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007033 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007034 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00007035 } else if (ResType->isAnyPointerType()) {
7036 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00007037
Chris Lattner3528d352008-11-21 07:05:48 +00007038 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00007039 if (PointeeTy->isVoidType()) {
John McCall09431682010-11-18 19:01:18 +00007040 if (S.getLangOptions().CPlusPlus) {
7041 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00007042 << Op->getSourceRange();
7043 return QualType();
7044 }
7045
7046 // Pointer to void is a GNU extension in C.
John McCall09431682010-11-18 19:01:18 +00007047 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00007048 } else if (PointeeTy->isFunctionType()) {
John McCall09431682010-11-18 19:01:18 +00007049 if (S.getLangOptions().CPlusPlus) {
7050 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00007051 << Op->getType() << Op->getSourceRange();
7052 return QualType();
7053 }
7054
John McCall09431682010-11-18 19:01:18 +00007055 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00007056 << ResType << Op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007057 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
7058 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00007059 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00007060 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007061 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007062 // Diagnose bad cases where we step over interface counts.
John McCall09431682010-11-18 19:01:18 +00007063 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7064 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007065 << PointeeTy << Op->getSourceRange();
7066 return QualType();
7067 }
Eli Friedman5b088a12010-01-03 00:20:48 +00007068 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007069 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007070 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007071 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007072 } else if (ResType->isPlaceholderType()) {
John McCall09431682010-11-18 19:01:18 +00007073 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007074 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007075 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7076 isInc, isPrefix);
Chris Lattner3528d352008-11-21 07:05:48 +00007077 } else {
John McCall09431682010-11-18 19:01:18 +00007078 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00007079 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007080 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007081 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007082 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007083 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007084 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007085 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007086 // In C++, a prefix increment is the same type as the operand. Otherwise
7087 // (in C or with postfix), the increment is the unqualified type of the
7088 // operand.
John McCall09431682010-11-18 19:01:18 +00007089 if (isPrefix && S.getLangOptions().CPlusPlus) {
7090 VK = VK_LValue;
7091 return ResType;
7092 } else {
7093 VK = VK_RValue;
7094 return ResType.getUnqualifiedType();
7095 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007096}
7097
John McCallf6a16482010-12-04 03:47:34 +00007098void Sema::ConvertPropertyForRValue(Expr *&E) {
7099 assert(E->getValueKind() == VK_LValue &&
7100 E->getObjectKind() == OK_ObjCProperty);
7101 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7102
7103 ExprValueKind VK = VK_RValue;
7104 if (PRE->isImplicitProperty()) {
Fariborz Jahanian99130e52010-12-22 19:46:35 +00007105 if (const ObjCMethodDecl *GetterMethod =
7106 PRE->getImplicitPropertyGetter()) {
7107 QualType Result = GetterMethod->getResultType();
7108 VK = Expr::getValueKindForType(Result);
7109 }
7110 else {
7111 Diag(PRE->getLocation(), diag::err_getter_not_found)
7112 << PRE->getBase()->getType();
7113 }
John McCallf6a16482010-12-04 03:47:34 +00007114 }
7115
7116 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
7117 E, 0, VK);
John McCalldb67e2f2010-12-10 01:49:45 +00007118
7119 ExprResult Result = MaybeBindToTemporary(E);
7120 if (!Result.isInvalid())
7121 E = Result.take();
John McCallf6a16482010-12-04 03:47:34 +00007122}
7123
7124void Sema::ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType &LHSTy) {
7125 assert(LHS->getValueKind() == VK_LValue &&
7126 LHS->getObjectKind() == OK_ObjCProperty);
7127 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7128
7129 if (PRE->isImplicitProperty()) {
7130 // If using property-dot syntax notation for assignment, and there is a
7131 // setter, RHS expression is being passed to the setter argument. So,
7132 // type conversion (and comparison) is RHS to setter's argument type.
7133 if (const ObjCMethodDecl *SetterMD = PRE->getImplicitPropertySetter()) {
7134 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7135 LHSTy = (*P)->getType();
7136
7137 // Otherwise, if the getter returns an l-value, just call that.
7138 } else {
7139 QualType Result = PRE->getImplicitPropertyGetter()->getResultType();
7140 ExprValueKind VK = Expr::getValueKindForType(Result);
7141 if (VK == VK_LValue) {
7142 LHS = ImplicitCastExpr::Create(Context, LHS->getType(),
7143 CK_GetObjCProperty, LHS, 0, VK);
7144 return;
John McCall12f78a62010-12-02 01:19:52 +00007145 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007146 }
John McCallf6a16482010-12-04 03:47:34 +00007147 }
7148
7149 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007150 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007151 InitializedEntity::InitializeParameter(Context, LHSTy);
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007152 Expr *Arg = RHS;
7153 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(),
7154 Owned(Arg));
7155 if (!ArgE.isInvalid())
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007156 RHS = ArgE.takeAs<Expr>();
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007157 }
7158}
7159
7160
Anders Carlsson369dee42008-02-01 07:15:58 +00007161/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007162/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007163/// where the declaration is needed for type checking. We only need to
7164/// handle cases when the expression references a function designator
7165/// or is an lvalue. Here are some examples:
7166/// - &(x) => x
7167/// - &*****f => f for f a function designator.
7168/// - &s.xx => s
7169/// - &s.zz[1].yy -> s, if zz is an array
7170/// - *(x + 1) -> x, if x is an array
7171/// - &"123"[2] -> 0
7172/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007173static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007174 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007175 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007176 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007177 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007178 // If this is an arrow operator, the address is an offset from
7179 // the base's value, so the object the base refers to is
7180 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007181 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007182 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007183 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007184 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007185 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007186 // FIXME: This code shouldn't be necessary! We should catch the implicit
7187 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007188 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7189 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7190 if (ICE->getSubExpr()->getType()->isArrayType())
7191 return getPrimaryDecl(ICE->getSubExpr());
7192 }
7193 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007194 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007195 case Stmt::UnaryOperatorClass: {
7196 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007197
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007198 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007199 case UO_Real:
7200 case UO_Imag:
7201 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007202 return getPrimaryDecl(UO->getSubExpr());
7203 default:
7204 return 0;
7205 }
7206 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007207 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007208 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007209 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007210 // If the result of an implicit cast is an l-value, we care about
7211 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007212 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007213 default:
7214 return 0;
7215 }
7216}
7217
7218/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007219/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007220/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007221/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007222/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007223/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007224/// we allow the '&' but retain the overloaded-function type.
John McCall09431682010-11-18 19:01:18 +00007225static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7226 SourceLocation OpLoc) {
John McCall9c72c602010-08-27 09:08:28 +00007227 if (OrigOp->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007228 return S.Context.DependentTy;
7229 if (OrigOp->getType() == S.Context.OverloadTy)
7230 return S.Context.OverloadTy;
John McCall9c72c602010-08-27 09:08:28 +00007231
John McCall09431682010-11-18 19:01:18 +00007232 ExprResult PR = S.CheckPlaceholderExpr(OrigOp, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007233 if (PR.isInvalid()) return QualType();
7234 OrigOp = PR.take();
7235
John McCall9c72c602010-08-27 09:08:28 +00007236 // Make sure to ignore parentheses in subsequent checks
7237 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00007238
John McCall09431682010-11-18 19:01:18 +00007239 if (S.getLangOptions().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00007240 // Implement C99-only parts of addressof rules.
7241 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00007242 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00007243 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7244 // (assuming the deref expression is valid).
7245 return uOp->getSubExpr()->getType();
7246 }
7247 // Technically, there should be a check for array subscript
7248 // expressions here, but the result of one is always an lvalue anyway.
7249 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007250 NamedDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00007251 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00007252
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007253 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00007254 bool sfinae = S.isSFINAEContext();
7255 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7256 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00007257 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007258 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00007259 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00007260 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007261 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00007262 } else if (lval == Expr::LV_MemberFunction) {
7263 // If it's an instance method, make a member pointer.
7264 // The expression must have exactly the form &A::foo.
7265
7266 // If the underlying expression isn't a decl ref, give up.
7267 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007268 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007269 << OrigOp->getSourceRange();
7270 return QualType();
7271 }
7272 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7273 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7274
7275 // The id-expression was parenthesized.
7276 if (OrigOp != DRE) {
John McCall09431682010-11-18 19:01:18 +00007277 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007278 << OrigOp->getSourceRange();
7279
7280 // The method was named without a qualifier.
7281 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00007282 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007283 << op->getSourceRange();
7284 }
7285
John McCall09431682010-11-18 19:01:18 +00007286 return S.Context.getMemberPointerType(op->getType(),
7287 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00007288 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00007289 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007290 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00007291 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00007292 // FIXME: emit more specific diag...
John McCall09431682010-11-18 19:01:18 +00007293 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00007294 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007295 return QualType();
7296 }
John McCall7eb0a9e2010-11-24 05:12:34 +00007297 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007298 // The operand cannot be a bit-field
John McCall09431682010-11-18 19:01:18 +00007299 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman23d58ce2009-04-20 08:23:18 +00007300 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00007301 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00007302 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00007303 // The operand cannot be an element of a vector
John McCall09431682010-11-18 19:01:18 +00007304 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00007305 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00007306 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00007307 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007308 // cannot take address of a property expression.
John McCall09431682010-11-18 19:01:18 +00007309 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007310 << "property expression" << op->getSourceRange();
7311 return QualType();
Steve Naroffbcb2b612008-02-29 23:30:25 +00007312 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00007313 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00007314 // with the register storage-class specifier.
7315 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00007316 // in C++ it is not error to take address of a register
7317 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00007318 if (vd->getStorageClass() == SC_Register &&
John McCall09431682010-11-18 19:01:18 +00007319 !S.getLangOptions().CPlusPlus) {
7320 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007321 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007322 return QualType();
7323 }
John McCallba135432009-11-21 08:51:07 +00007324 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00007325 return S.Context.OverloadTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007326 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00007327 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00007328 // Could be a pointer to member, though, if there is an explicit
7329 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00007330 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00007331 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007332 if (Ctx && Ctx->isRecord()) {
7333 if (FD->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00007334 S.Diag(OpLoc,
7335 diag::err_cannot_form_pointer_to_member_of_reference_type)
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007336 << FD->getDeclName() << FD->getType();
7337 return QualType();
7338 }
Mike Stump1eb44332009-09-09 15:08:12 +00007339
John McCall09431682010-11-18 19:01:18 +00007340 return S.Context.getMemberPointerType(op->getType(),
7341 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007342 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00007343 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00007344 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00007345 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00007346 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00007347
Eli Friedman441cf102009-05-16 23:27:50 +00007348 if (lval == Expr::LV_IncompleteVoidType) {
7349 // Taking the address of a void variable is technically illegal, but we
7350 // allow it in cases which are otherwise valid.
7351 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00007352 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00007353 }
7354
Reid Spencer5f016e22007-07-11 17:01:13 +00007355 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00007356 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00007357 return S.Context.getObjCObjectPointerType(op->getType());
7358 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007359}
7360
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007361/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00007362static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7363 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00007364 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007365 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007366
John McCall09431682010-11-18 19:01:18 +00007367 S.UsualUnaryConversions(Op);
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007368 QualType OpTy = Op->getType();
7369 QualType Result;
7370
7371 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7372 // is an incomplete type or void. It would be possible to warn about
7373 // dereferencing a void pointer, but it's completely well-defined, and such a
7374 // warning is unlikely to catch any mistakes.
7375 if (const PointerType *PT = OpTy->getAs<PointerType>())
7376 Result = PT->getPointeeType();
7377 else if (const ObjCObjectPointerType *OPT =
7378 OpTy->getAs<ObjCObjectPointerType>())
7379 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00007380 else {
John McCall09431682010-11-18 19:01:18 +00007381 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007382 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007383 if (PR.take() != Op)
7384 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007385 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007386
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007387 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00007388 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007389 << OpTy << Op->getSourceRange();
7390 return QualType();
7391 }
John McCall09431682010-11-18 19:01:18 +00007392
7393 // Dereferences are usually l-values...
7394 VK = VK_LValue;
7395
7396 // ...except that certain expressions are never l-values in C.
7397 if (!S.getLangOptions().CPlusPlus &&
7398 IsCForbiddenLValueType(S.Context, Result))
7399 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007400
7401 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00007402}
7403
John McCall2de56d12010-08-25 11:45:40 +00007404static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007405 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007406 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007407 switch (Kind) {
7408 default: assert(0 && "Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00007409 case tok::periodstar: Opc = BO_PtrMemD; break;
7410 case tok::arrowstar: Opc = BO_PtrMemI; break;
7411 case tok::star: Opc = BO_Mul; break;
7412 case tok::slash: Opc = BO_Div; break;
7413 case tok::percent: Opc = BO_Rem; break;
7414 case tok::plus: Opc = BO_Add; break;
7415 case tok::minus: Opc = BO_Sub; break;
7416 case tok::lessless: Opc = BO_Shl; break;
7417 case tok::greatergreater: Opc = BO_Shr; break;
7418 case tok::lessequal: Opc = BO_LE; break;
7419 case tok::less: Opc = BO_LT; break;
7420 case tok::greaterequal: Opc = BO_GE; break;
7421 case tok::greater: Opc = BO_GT; break;
7422 case tok::exclaimequal: Opc = BO_NE; break;
7423 case tok::equalequal: Opc = BO_EQ; break;
7424 case tok::amp: Opc = BO_And; break;
7425 case tok::caret: Opc = BO_Xor; break;
7426 case tok::pipe: Opc = BO_Or; break;
7427 case tok::ampamp: Opc = BO_LAnd; break;
7428 case tok::pipepipe: Opc = BO_LOr; break;
7429 case tok::equal: Opc = BO_Assign; break;
7430 case tok::starequal: Opc = BO_MulAssign; break;
7431 case tok::slashequal: Opc = BO_DivAssign; break;
7432 case tok::percentequal: Opc = BO_RemAssign; break;
7433 case tok::plusequal: Opc = BO_AddAssign; break;
7434 case tok::minusequal: Opc = BO_SubAssign; break;
7435 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7436 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7437 case tok::ampequal: Opc = BO_AndAssign; break;
7438 case tok::caretequal: Opc = BO_XorAssign; break;
7439 case tok::pipeequal: Opc = BO_OrAssign; break;
7440 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007441 }
7442 return Opc;
7443}
7444
John McCall2de56d12010-08-25 11:45:40 +00007445static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007446 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007447 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007448 switch (Kind) {
7449 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00007450 case tok::plusplus: Opc = UO_PreInc; break;
7451 case tok::minusminus: Opc = UO_PreDec; break;
7452 case tok::amp: Opc = UO_AddrOf; break;
7453 case tok::star: Opc = UO_Deref; break;
7454 case tok::plus: Opc = UO_Plus; break;
7455 case tok::minus: Opc = UO_Minus; break;
7456 case tok::tilde: Opc = UO_Not; break;
7457 case tok::exclaim: Opc = UO_LNot; break;
7458 case tok::kw___real: Opc = UO_Real; break;
7459 case tok::kw___imag: Opc = UO_Imag; break;
7460 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007461 }
7462 return Opc;
7463}
7464
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007465/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7466/// This warning is only emitted for builtin assignment operations. It is also
7467/// suppressed in the event of macro expansions.
7468static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7469 SourceLocation OpLoc) {
7470 if (!S.ActiveTemplateInstantiations.empty())
7471 return;
7472 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7473 return;
7474 lhs = lhs->IgnoreParenImpCasts();
7475 rhs = rhs->IgnoreParenImpCasts();
7476 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7477 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7478 if (!LeftDeclRef || !RightDeclRef ||
7479 LeftDeclRef->getLocation().isMacroID() ||
7480 RightDeclRef->getLocation().isMacroID())
7481 return;
7482 const ValueDecl *LeftDecl =
7483 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7484 const ValueDecl *RightDecl =
7485 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7486 if (LeftDecl != RightDecl)
7487 return;
7488 if (LeftDecl->getType().isVolatileQualified())
7489 return;
7490 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7491 if (RefTy->getPointeeType().isVolatileQualified())
7492 return;
7493
7494 S.Diag(OpLoc, diag::warn_self_assignment)
7495 << LeftDeclRef->getType()
7496 << lhs->getSourceRange() << rhs->getSourceRange();
7497}
7498
Douglas Gregoreaebc752008-11-06 23:29:22 +00007499/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7500/// operator @p Opc at location @c TokLoc. This routine only supports
7501/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00007502ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00007503 BinaryOperatorKind Opc,
John McCall2de56d12010-08-25 11:45:40 +00007504 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00007505 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00007506 // The following two variables are used for compound assignment operators
7507 QualType CompLHSTy; // Type of LHS after promotions for computation
7508 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00007509 ExprValueKind VK = VK_RValue;
7510 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00007511
7512 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007513 case BO_Assign:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007514 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
John McCallf6a16482010-12-04 03:47:34 +00007515 if (getLangOptions().CPlusPlus &&
7516 lhs->getObjectKind() != OK_ObjCProperty) {
John McCall09431682010-11-18 19:01:18 +00007517 VK = lhs->getValueKind();
7518 OK = lhs->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007519 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007520 if (!ResultTy.isNull())
7521 DiagnoseSelfAssignment(*this, lhs, rhs, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007522 break;
John McCall2de56d12010-08-25 11:45:40 +00007523 case BO_PtrMemD:
7524 case BO_PtrMemI:
John McCallf89e55a2010-11-18 06:31:45 +00007525 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007526 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00007527 break;
John McCall2de56d12010-08-25 11:45:40 +00007528 case BO_Mul:
7529 case BO_Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00007530 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00007531 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007532 break;
John McCall2de56d12010-08-25 11:45:40 +00007533 case BO_Rem:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007534 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7535 break;
John McCall2de56d12010-08-25 11:45:40 +00007536 case BO_Add:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007537 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7538 break;
John McCall2de56d12010-08-25 11:45:40 +00007539 case BO_Sub:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007540 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7541 break;
John McCall2de56d12010-08-25 11:45:40 +00007542 case BO_Shl:
7543 case BO_Shr:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007544 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
7545 break;
John McCall2de56d12010-08-25 11:45:40 +00007546 case BO_LE:
7547 case BO_LT:
7548 case BO_GE:
7549 case BO_GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00007550 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007551 break;
John McCall2de56d12010-08-25 11:45:40 +00007552 case BO_EQ:
7553 case BO_NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00007554 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007555 break;
John McCall2de56d12010-08-25 11:45:40 +00007556 case BO_And:
7557 case BO_Xor:
7558 case BO_Or:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007559 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7560 break;
John McCall2de56d12010-08-25 11:45:40 +00007561 case BO_LAnd:
7562 case BO_LOr:
Chris Lattner90a8f272010-07-13 19:41:32 +00007563 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007564 break;
John McCall2de56d12010-08-25 11:45:40 +00007565 case BO_MulAssign:
7566 case BO_DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00007567 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00007568 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007569 CompLHSTy = CompResultTy;
7570 if (!CompResultTy.isNull())
7571 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007572 break;
John McCall2de56d12010-08-25 11:45:40 +00007573 case BO_RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007574 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7575 CompLHSTy = CompResultTy;
7576 if (!CompResultTy.isNull())
7577 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007578 break;
John McCall2de56d12010-08-25 11:45:40 +00007579 case BO_AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007580 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7581 if (!CompResultTy.isNull())
7582 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007583 break;
John McCall2de56d12010-08-25 11:45:40 +00007584 case BO_SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007585 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7586 if (!CompResultTy.isNull())
7587 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007588 break;
John McCall2de56d12010-08-25 11:45:40 +00007589 case BO_ShlAssign:
7590 case BO_ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007591 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
7592 CompLHSTy = CompResultTy;
7593 if (!CompResultTy.isNull())
7594 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007595 break;
John McCall2de56d12010-08-25 11:45:40 +00007596 case BO_AndAssign:
7597 case BO_XorAssign:
7598 case BO_OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007599 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7600 CompLHSTy = CompResultTy;
7601 if (!CompResultTy.isNull())
7602 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007603 break;
John McCall2de56d12010-08-25 11:45:40 +00007604 case BO_Comma:
John McCall09431682010-11-18 19:01:18 +00007605 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John McCallf89e55a2010-11-18 06:31:45 +00007606 if (getLangOptions().CPlusPlus) {
7607 VK = rhs->getValueKind();
7608 OK = rhs->getObjectKind();
7609 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00007610 break;
7611 }
7612 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00007613 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00007614 if (CompResultTy.isNull())
John McCallf89e55a2010-11-18 06:31:45 +00007615 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy,
7616 VK, OK, OpLoc));
7617
John McCallf6a16482010-12-04 03:47:34 +00007618 if (getLangOptions().CPlusPlus && lhs->getObjectKind() != OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00007619 VK = VK_LValue;
7620 OK = lhs->getObjectKind();
7621 }
7622 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
7623 VK, OK, CompLHSTy,
7624 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00007625}
7626
Sebastian Redlaee3c932009-10-27 12:10:02 +00007627/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
7628/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00007629static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7630 const PartialDiagnostic &PD,
Douglas Gregor55b38842010-04-14 16:09:52 +00007631 const PartialDiagnostic &FirstNote,
7632 SourceRange FirstParenRange,
7633 const PartialDiagnostic &SecondNote,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007634 SourceRange SecondParenRange) {
Douglas Gregor55b38842010-04-14 16:09:52 +00007635 Self.Diag(Loc, PD);
7636
7637 if (!FirstNote.getDiagID())
7638 return;
7639
7640 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
7641 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
7642 // We can't display the parentheses, so just return.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00007643 return;
7644 }
7645
Douglas Gregor55b38842010-04-14 16:09:52 +00007646 Self.Diag(Loc, FirstNote)
7647 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregor849b2432010-03-31 17:46:05 +00007648 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007649
Douglas Gregor55b38842010-04-14 16:09:52 +00007650 if (!SecondNote.getDiagID())
Douglas Gregor827feec2010-01-08 00:20:23 +00007651 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007652
Douglas Gregor827feec2010-01-08 00:20:23 +00007653 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
7654 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
7655 // We can't display the parentheses, so just dig the
7656 // warning/error and return.
Douglas Gregor55b38842010-04-14 16:09:52 +00007657 Self.Diag(Loc, SecondNote);
Douglas Gregor827feec2010-01-08 00:20:23 +00007658 return;
7659 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007660
Douglas Gregor55b38842010-04-14 16:09:52 +00007661 Self.Diag(Loc, SecondNote)
Douglas Gregor849b2432010-03-31 17:46:05 +00007662 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
7663 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl6b169ac2009-10-26 17:01:32 +00007664}
7665
Sebastian Redlaee3c932009-10-27 12:10:02 +00007666/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7667/// operators are mixed in a way that suggests that the programmer forgot that
7668/// comparison operators have higher precedence. The most typical example of
7669/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00007670static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007671 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00007672 typedef BinaryOperator BinOp;
7673 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7674 rhsopc = static_cast<BinOp::Opcode>(-1);
7675 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007676 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00007677 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007678 rhsopc = BO->getOpcode();
7679
7680 // Subs are not binary operators.
7681 if (lhsopc == -1 && rhsopc == -1)
7682 return;
7683
7684 // Bitwise operations are sometimes used as eager logical ops.
7685 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00007686 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7687 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007688 return;
7689
Sebastian Redlaee3c932009-10-27 12:10:02 +00007690 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00007691 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007692 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00007693 << SourceRange(lhs->getLocStart(), OpLoc)
7694 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007695 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00007696 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00007697 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
7698 Self.PDiag(diag::note_precedence_bitwise_silence)
7699 << BinOp::getOpcodeStr(lhsopc),
7700 lhs->getSourceRange());
Sebastian Redlaee3c932009-10-27 12:10:02 +00007701 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00007702 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007703 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00007704 << SourceRange(OpLoc, rhs->getLocEnd())
7705 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007706 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00007707 << BinOp::getOpcodeStr(Opc),
Douglas Gregor55b38842010-04-14 16:09:52 +00007708 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
7709 Self.PDiag(diag::note_precedence_bitwise_silence)
7710 << BinOp::getOpcodeStr(rhsopc),
7711 rhs->getSourceRange());
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007712}
7713
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007714/// \brief It accepts a '&&' expr that is inside a '||' one.
7715/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7716/// in parentheses.
7717static void
7718EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
7719 Expr *E) {
7720 assert(isa<BinaryOperator>(E) &&
7721 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
7722 SuggestParentheses(Self, OpLoc,
7723 Self.PDiag(diag::warn_logical_and_in_logical_or)
7724 << E->getSourceRange(),
7725 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
7726 E->getSourceRange(),
7727 Self.PDiag(0), SourceRange());
7728}
7729
7730/// \brief Returns true if the given expression can be evaluated as a constant
7731/// 'true'.
7732static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7733 bool Res;
7734 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7735}
7736
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007737/// \brief Returns true if the given expression can be evaluated as a constant
7738/// 'false'.
7739static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7740 bool Res;
7741 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7742}
7743
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007744/// \brief Look for '&&' in the left hand of a '||' expr.
7745static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007746 Expr *OrLHS, Expr *OrRHS) {
7747 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007748 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007749 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7750 if (EvaluatesAsFalse(S, OrRHS))
7751 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007752 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7753 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7754 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7755 } else if (Bop->getOpcode() == BO_LOr) {
7756 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7757 // If it's "a || b && 1 || c" we didn't warn earlier for
7758 // "a || b && 1", but warn now.
7759 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7760 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7761 }
7762 }
7763 }
7764}
7765
7766/// \brief Look for '&&' in the right hand of a '||' expr.
7767static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007768 Expr *OrLHS, Expr *OrRHS) {
7769 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007770 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007771 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7772 if (EvaluatesAsFalse(S, OrLHS))
7773 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007774 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7775 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7776 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007777 }
7778 }
7779}
7780
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007781/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007782/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00007783static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007784 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007785 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00007786 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007787 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7788
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007789 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7790 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00007791 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007792 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7793 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007794 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007795}
7796
Reid Spencer5f016e22007-07-11 17:01:13 +00007797// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00007798ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00007799 tok::TokenKind Kind,
7800 Expr *lhs, Expr *rhs) {
7801 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Narofff69936d2007-09-16 03:34:24 +00007802 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
7803 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007804
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007805 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7806 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
7807
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007808 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
7809}
7810
John McCall60d7b3a2010-08-24 06:29:42 +00007811ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007812 BinaryOperatorKind Opc,
7813 Expr *lhs, Expr *rhs) {
John McCall01b2e4e2010-12-06 05:26:58 +00007814 if (getLangOptions().CPlusPlus) {
7815 bool UseBuiltinOperator;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007816
John McCall01b2e4e2010-12-06 05:26:58 +00007817 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
7818 UseBuiltinOperator = false;
7819 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
7820 UseBuiltinOperator = true;
7821 } else {
7822 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
7823 !rhs->getType()->isOverloadableType();
7824 }
7825
7826 if (!UseBuiltinOperator) {
7827 // Find all of the overloaded operators visible from this
7828 // point. We perform both an operator-name lookup from the local
7829 // scope and an argument-dependent lookup based on the types of
7830 // the arguments.
7831 UnresolvedSet<16> Functions;
7832 OverloadedOperatorKind OverOp
7833 = BinaryOperator::getOverloadedOperator(Opc);
7834 if (S && OverOp != OO_None)
7835 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
7836 Functions);
7837
7838 // Build the (potentially-overloaded, potentially-dependent)
7839 // binary operation.
7840 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
7841 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00007842 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007843
Douglas Gregoreaebc752008-11-06 23:29:22 +00007844 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007845 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00007846}
7847
John McCall60d7b3a2010-08-24 06:29:42 +00007848ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00007849 UnaryOperatorKind Opc,
John McCall2cd11fe2010-10-12 02:09:17 +00007850 Expr *Input) {
John McCallf89e55a2010-11-18 06:31:45 +00007851 ExprValueKind VK = VK_RValue;
7852 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00007853 QualType resultType;
7854 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007855 case UO_PreInc:
7856 case UO_PreDec:
7857 case UO_PostInc:
7858 case UO_PostDec:
John McCall09431682010-11-18 19:01:18 +00007859 resultType = CheckIncrementDecrementOperand(*this, Input, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007860 Opc == UO_PreInc ||
7861 Opc == UO_PostInc,
7862 Opc == UO_PreInc ||
7863 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00007864 break;
John McCall2de56d12010-08-25 11:45:40 +00007865 case UO_AddrOf:
John McCall09431682010-11-18 19:01:18 +00007866 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00007867 break;
John McCall2de56d12010-08-25 11:45:40 +00007868 case UO_Deref:
Douglas Gregora873dfc2010-02-03 00:27:59 +00007869 DefaultFunctionArrayLvalueConversion(Input);
John McCall09431682010-11-18 19:01:18 +00007870 resultType = CheckIndirectionOperand(*this, Input, VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00007871 break;
John McCall2de56d12010-08-25 11:45:40 +00007872 case UO_Plus:
7873 case UO_Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00007874 UsualUnaryConversions(Input);
7875 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00007876 if (resultType->isDependentType())
7877 break;
Douglas Gregor00619622010-06-22 23:41:02 +00007878 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
7879 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00007880 break;
7881 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
7882 resultType->isEnumeralType())
7883 break;
7884 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00007885 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00007886 resultType->isPointerType())
7887 break;
John McCall2cd11fe2010-10-12 02:09:17 +00007888 else if (resultType->isPlaceholderType()) {
7889 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
7890 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00007891 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall2cd11fe2010-10-12 02:09:17 +00007892 }
Douglas Gregor74253732008-11-19 15:42:04 +00007893
Sebastian Redl0eb23302009-01-19 00:08:26 +00007894 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7895 << resultType << Input->getSourceRange());
John McCall2de56d12010-08-25 11:45:40 +00007896 case UO_Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00007897 UsualUnaryConversions(Input);
7898 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00007899 if (resultType->isDependentType())
7900 break;
Chris Lattner02a65142008-07-25 23:52:49 +00007901 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
7902 if (resultType->isComplexType() || resultType->isComplexIntegerType())
7903 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007904 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007905 << resultType << Input->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007906 else if (resultType->hasIntegerRepresentation())
7907 break;
7908 else if (resultType->isPlaceholderType()) {
7909 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
7910 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00007911 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall2cd11fe2010-10-12 02:09:17 +00007912 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00007913 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7914 << resultType << Input->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00007915 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007916 break;
John McCall2de56d12010-08-25 11:45:40 +00007917 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00007918 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregora873dfc2010-02-03 00:27:59 +00007919 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroffc80b4ee2007-07-16 21:54:35 +00007920 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00007921 if (resultType->isDependentType())
7922 break;
John McCall2cd11fe2010-10-12 02:09:17 +00007923 if (resultType->isScalarType()) { // C99 6.5.3.3p1
7924 // ok, fallthrough
7925 } else if (resultType->isPlaceholderType()) {
7926 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
7927 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00007928 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall2cd11fe2010-10-12 02:09:17 +00007929 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00007930 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7931 << resultType << Input->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00007932 }
Douglas Gregorea844f32010-09-20 17:13:33 +00007933
Reid Spencer5f016e22007-07-11 17:01:13 +00007934 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00007935 // In C++, it's bool. C++ 5.3.1p8
7936 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007937 break;
John McCall2de56d12010-08-25 11:45:40 +00007938 case UO_Real:
7939 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00007940 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCallf89e55a2010-11-18 06:31:45 +00007941 // _Real and _Imag map ordinary l-values into ordinary l-values.
7942 if (Input->getValueKind() != VK_RValue &&
7943 Input->getObjectKind() == OK_Ordinary)
7944 VK = Input->getValueKind();
Chris Lattnerdbb36972007-08-24 21:16:53 +00007945 break;
John McCall2de56d12010-08-25 11:45:40 +00007946 case UO_Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00007947 resultType = Input->getType();
John McCallf89e55a2010-11-18 06:31:45 +00007948 VK = Input->getValueKind();
7949 OK = Input->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00007950 break;
7951 }
7952 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00007953 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007954
John McCallf89e55a2010-11-18 06:31:45 +00007955 return Owned(new (Context) UnaryOperator(Input, Opc, resultType,
7956 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00007957}
7958
John McCall60d7b3a2010-08-24 06:29:42 +00007959ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007960 UnaryOperatorKind Opc,
7961 Expr *Input) {
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00007962 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman957c0942010-09-05 23:15:52 +00007963 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007964 // Find all of the overloaded operators visible from this
7965 // point. We perform both an operator-name lookup from the local
7966 // scope and an argument-dependent lookup based on the types of
7967 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00007968 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007969 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00007970 if (S && OverOp != OO_None)
7971 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
7972 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007973
John McCall9ae2f072010-08-23 23:25:46 +00007974 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007975 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007976
John McCall9ae2f072010-08-23 23:25:46 +00007977 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007978}
7979
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007980// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00007981ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00007982 tok::TokenKind Op, Expr *Input) {
7983 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007984}
7985
Steve Naroff1b273c42007-09-16 14:56:35 +00007986/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
John McCall60d7b3a2010-08-24 06:29:42 +00007987ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00007988 SourceLocation LabLoc,
7989 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007990 // Look up the record for this label identifier.
John McCall781472f2010-08-25 08:40:02 +00007991 LabelStmt *&LabelDecl = getCurFunction()->LabelMap[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00007992
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00007993 // If we haven't seen this label yet, create a forward reference. It
7994 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00007995 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00007996 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007997
Argyrios Kyrtzidis355a9fe2010-09-19 21:21:25 +00007998 LabelDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00007999 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00008000 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
8001 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008002}
8003
John McCall60d7b3a2010-08-24 06:29:42 +00008004ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008005Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008006 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008007 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8008 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8009
Douglas Gregordd8f5692010-03-10 04:54:39 +00008010 bool isFileScope
8011 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00008012 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00008013 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00008014
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008015 // FIXME: there are a variety of strange constraints to enforce here, for
8016 // example, it is not possible to goto into a stmt expression apparently.
8017 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008018
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008019 // If there are sub stmts in the compound stmt, take the type of the last one
8020 // as the type of the stmtexpr.
8021 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008022 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008023 if (!Compound->body_empty()) {
8024 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008025 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008026 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008027 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8028 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008029 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008030 }
8031 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00008032 // Do function/array conversion on the last expression, but not
8033 // lvalue-to-rvalue. However, initialize an unqualified type.
8034 DefaultFunctionArrayConversion(LastExpr);
8035 Ty = LastExpr->getType().getUnqualifiedType();
8036
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008037 if (!Ty->isDependentType() && !LastExpr->isTypeDependent()) {
8038 ExprResult Res = PerformCopyInitialization(
8039 InitializedEntity::InitializeResult(LPLoc,
8040 Ty,
8041 false),
8042 SourceLocation(),
8043 Owned(LastExpr));
8044 if (Res.isInvalid())
8045 return ExprError();
8046 if ((LastExpr = Res.takeAs<Expr>())) {
8047 if (!LastLabelStmt)
8048 Compound->setLastStmt(LastExpr);
8049 else
8050 LastLabelStmt->setSubStmt(LastExpr);
8051 StmtExprMayBindToTemp = true;
8052 }
8053 }
8054 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00008055 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008056
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008057 // FIXME: Check that expression type is complete/non-abstract; statement
8058 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008059 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8060 if (StmtExprMayBindToTemp)
8061 return MaybeBindToTemporary(ResStmtExpr);
8062 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008063}
Steve Naroffd34e9152007-08-01 22:05:33 +00008064
John McCall60d7b3a2010-08-24 06:29:42 +00008065ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008066 TypeSourceInfo *TInfo,
8067 OffsetOfComponent *CompPtr,
8068 unsigned NumComponents,
8069 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008070 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008071 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008072 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008073
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008074 // We must have at least one component that refers to the type, and the first
8075 // one is known to be a field designator. Verify that the ArgTy represents
8076 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00008077 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008078 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8079 << ArgTy << TypeRange);
8080
8081 // Type must be complete per C99 7.17p3 because a declaring a variable
8082 // with an incomplete type would be ill-formed.
8083 if (!Dependent
8084 && RequireCompleteType(BuiltinLoc, ArgTy,
8085 PDiag(diag::err_offsetof_incomplete_type)
8086 << TypeRange))
8087 return ExprError();
8088
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008089 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8090 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00008091 // FIXME: This diagnostic isn't actually visible because the location is in
8092 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008093 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008094 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8095 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008096
8097 bool DidWarnAboutNonPOD = false;
8098 QualType CurrentType = ArgTy;
8099 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8100 llvm::SmallVector<OffsetOfNode, 4> Comps;
8101 llvm::SmallVector<Expr*, 4> Exprs;
8102 for (unsigned i = 0; i != NumComponents; ++i) {
8103 const OffsetOfComponent &OC = CompPtr[i];
8104 if (OC.isBrackets) {
8105 // Offset of an array sub-field. TODO: Should we allow vector elements?
8106 if (!CurrentType->isDependentType()) {
8107 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8108 if(!AT)
8109 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8110 << CurrentType);
8111 CurrentType = AT->getElementType();
8112 } else
8113 CurrentType = Context.DependentTy;
8114
8115 // The expression must be an integral expression.
8116 // FIXME: An integral constant expression?
8117 Expr *Idx = static_cast<Expr*>(OC.U.E);
8118 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8119 !Idx->getType()->isIntegerType())
8120 return ExprError(Diag(Idx->getLocStart(),
8121 diag::err_typecheck_subscript_not_integer)
8122 << Idx->getSourceRange());
8123
8124 // Record this array index.
8125 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8126 Exprs.push_back(Idx);
8127 continue;
8128 }
8129
8130 // Offset of a field.
8131 if (CurrentType->isDependentType()) {
8132 // We have the offset of a field, but we can't look into the dependent
8133 // type. Just record the identifier of the field.
8134 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8135 CurrentType = Context.DependentTy;
8136 continue;
8137 }
8138
8139 // We need to have a complete type to look into.
8140 if (RequireCompleteType(OC.LocStart, CurrentType,
8141 diag::err_offsetof_incomplete_type))
8142 return ExprError();
8143
8144 // Look for the designated field.
8145 const RecordType *RC = CurrentType->getAs<RecordType>();
8146 if (!RC)
8147 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8148 << CurrentType);
8149 RecordDecl *RD = RC->getDecl();
8150
8151 // C++ [lib.support.types]p5:
8152 // The macro offsetof accepts a restricted set of type arguments in this
8153 // International Standard. type shall be a POD structure or a POD union
8154 // (clause 9).
8155 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8156 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
8157 DiagRuntimeBehavior(BuiltinLoc,
8158 PDiag(diag::warn_offsetof_non_pod_type)
8159 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8160 << CurrentType))
8161 DidWarnAboutNonPOD = true;
8162 }
8163
8164 // Look for the field.
8165 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8166 LookupQualifiedName(R, RD);
8167 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00008168 IndirectFieldDecl *IndirectMemberDecl = 0;
8169 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00008170 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00008171 MemberDecl = IndirectMemberDecl->getAnonField();
8172 }
8173
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008174 if (!MemberDecl)
8175 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8176 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8177 OC.LocEnd));
8178
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00008179 // C99 7.17p3:
8180 // (If the specified member is a bit-field, the behavior is undefined.)
8181 //
8182 // We diagnose this as an error.
8183 if (MemberDecl->getBitWidth()) {
8184 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8185 << MemberDecl->getDeclName()
8186 << SourceRange(BuiltinLoc, RParenLoc);
8187 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8188 return ExprError();
8189 }
Eli Friedman19410a72010-08-05 10:11:36 +00008190
8191 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00008192 if (IndirectMemberDecl)
8193 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00008194
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008195 // If the member was found in a base class, introduce OffsetOfNodes for
8196 // the base class indirections.
8197 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8198 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00008199 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008200 CXXBasePath &Path = Paths.front();
8201 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8202 B != BEnd; ++B)
8203 Comps.push_back(OffsetOfNode(B->Base));
8204 }
Eli Friedman19410a72010-08-05 10:11:36 +00008205
Francois Pichet87c2e122010-11-21 06:08:52 +00008206 if (IndirectMemberDecl) {
8207 for (IndirectFieldDecl::chain_iterator FI =
8208 IndirectMemberDecl->chain_begin(),
8209 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8210 assert(isa<FieldDecl>(*FI));
8211 Comps.push_back(OffsetOfNode(OC.LocStart,
8212 cast<FieldDecl>(*FI), OC.LocEnd));
8213 }
8214 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008215 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00008216
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008217 CurrentType = MemberDecl->getType().getNonReferenceType();
8218 }
8219
8220 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8221 TInfo, Comps.data(), Comps.size(),
8222 Exprs.data(), Exprs.size(), RParenLoc));
8223}
Mike Stumpeed9cac2009-02-19 03:04:26 +00008224
John McCall60d7b3a2010-08-24 06:29:42 +00008225ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00008226 SourceLocation BuiltinLoc,
8227 SourceLocation TypeLoc,
8228 ParsedType argty,
8229 OffsetOfComponent *CompPtr,
8230 unsigned NumComponents,
8231 SourceLocation RPLoc) {
8232
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008233 TypeSourceInfo *ArgTInfo;
8234 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8235 if (ArgTy.isNull())
8236 return ExprError();
8237
Eli Friedman5a15dc12010-08-05 10:15:45 +00008238 if (!ArgTInfo)
8239 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8240
8241 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8242 RPLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008243}
8244
8245
John McCall60d7b3a2010-08-24 06:29:42 +00008246ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008247 Expr *CondExpr,
8248 Expr *LHSExpr, Expr *RHSExpr,
8249 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00008250 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8251
John McCallf89e55a2010-11-18 06:31:45 +00008252 ExprValueKind VK = VK_RValue;
8253 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00008254 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00008255 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00008256 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00008257 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00008258 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00008259 } else {
8260 // The conditional expression is required to be a constant expression.
8261 llvm::APSInt condEval(32);
8262 SourceLocation ExpLoc;
8263 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00008264 return ExprError(Diag(ExpLoc,
8265 diag::err_typecheck_choose_expr_requires_constant)
8266 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00008267
Sebastian Redl28507842009-02-26 14:39:58 +00008268 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00008269 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8270
8271 resType = ActiveExpr->getType();
8272 ValueDependent = ActiveExpr->isValueDependent();
8273 VK = ActiveExpr->getValueKind();
8274 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00008275 }
8276
Sebastian Redlf53597f2009-03-15 17:47:39 +00008277 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00008278 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00008279 resType->isDependentType(),
8280 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00008281}
8282
Steve Naroff4eb206b2008-09-03 18:15:37 +00008283//===----------------------------------------------------------------------===//
8284// Clang Extensions.
8285//===----------------------------------------------------------------------===//
8286
8287/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00008288void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008289 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8290 PushBlockScope(BlockScope, Block);
8291 CurContext->addDecl(Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008292 if (BlockScope)
8293 PushDeclContext(BlockScope, Block);
8294 else
8295 CurContext = Block;
Steve Naroff090276f2008-10-10 01:28:17 +00008296}
8297
Mike Stump98eb8a72009-02-04 22:31:32 +00008298void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00008299 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00008300 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008301 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008302
John McCallbf1a0282010-06-04 23:28:52 +00008303 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00008304 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00008305
John McCall711c52b2011-01-05 12:14:39 +00008306 // GetTypeForDeclarator always produces a function type for a block
8307 // literal signature. Furthermore, it is always a FunctionProtoType
8308 // unless the function was written with a typedef.
8309 assert(T->isFunctionType() &&
8310 "GetTypeForDeclarator made a non-function block signature");
8311
8312 // Look for an explicit signature in that function type.
8313 FunctionProtoTypeLoc ExplicitSignature;
8314
8315 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8316 if (isa<FunctionProtoTypeLoc>(tmp)) {
8317 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8318
8319 // Check whether that explicit signature was synthesized by
8320 // GetTypeForDeclarator. If so, don't save that as part of the
8321 // written signature.
8322 if (ExplicitSignature.getLParenLoc() ==
8323 ExplicitSignature.getRParenLoc()) {
8324 // This would be much cheaper if we stored TypeLocs instead of
8325 // TypeSourceInfos.
8326 TypeLoc Result = ExplicitSignature.getResultLoc();
8327 unsigned Size = Result.getFullDataSize();
8328 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8329 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8330
8331 ExplicitSignature = FunctionProtoTypeLoc();
8332 }
John McCall82dc0092010-06-04 11:21:44 +00008333 }
Mike Stump1eb44332009-09-09 15:08:12 +00008334
John McCall711c52b2011-01-05 12:14:39 +00008335 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8336 CurBlock->FunctionType = T;
8337
8338 const FunctionType *Fn = T->getAs<FunctionType>();
8339 QualType RetTy = Fn->getResultType();
8340 bool isVariadic =
8341 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8342
John McCallc71a4912010-06-04 19:02:56 +00008343 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00008344
John McCall82dc0092010-06-04 11:21:44 +00008345 // Don't allow returning a objc interface by value.
8346 if (RetTy->isObjCObjectType()) {
8347 Diag(ParamInfo.getSourceRange().getBegin(),
8348 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8349 return;
8350 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008351
John McCall82dc0092010-06-04 11:21:44 +00008352 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00008353 // return type. TODO: what should we do with declarators like:
8354 // ^ * { ... }
8355 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00008356 if (RetTy != Context.DependentTy)
8357 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008358
John McCall82dc0092010-06-04 11:21:44 +00008359 // Push block parameters from the declarator if we had them.
John McCallc71a4912010-06-04 19:02:56 +00008360 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00008361 if (ExplicitSignature) {
8362 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8363 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008364 if (Param->getIdentifier() == 0 &&
8365 !Param->isImplicit() &&
8366 !Param->isInvalidDecl() &&
8367 !getLangOptions().CPlusPlus)
8368 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00008369 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008370 }
John McCall82dc0092010-06-04 11:21:44 +00008371
8372 // Fake up parameter variables if we have a typedef, like
8373 // ^ fntype { ... }
8374 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8375 for (FunctionProtoType::arg_type_iterator
8376 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8377 ParmVarDecl *Param =
8378 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8379 ParamInfo.getSourceRange().getBegin(),
8380 *I);
John McCallc71a4912010-06-04 19:02:56 +00008381 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00008382 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008383 }
John McCall82dc0092010-06-04 11:21:44 +00008384
John McCallc71a4912010-06-04 19:02:56 +00008385 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00008386 if (!Params.empty()) {
John McCallc71a4912010-06-04 19:02:56 +00008387 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregor82aa7132010-11-01 18:37:59 +00008388 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8389 CurBlock->TheDecl->param_end(),
8390 /*CheckParameterNames=*/false);
8391 }
8392
John McCall82dc0092010-06-04 11:21:44 +00008393 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00008394 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00008395
John McCallc71a4912010-06-04 19:02:56 +00008396 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00008397 Diag(ParamInfo.getAttributes()->getLoc(),
8398 diag::warn_attribute_sentinel_not_variadic) << 1;
8399 // FIXME: remove the attribute.
8400 }
8401
8402 // Put the parameter variables in scope. We can bail out immediately
8403 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00008404 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00008405 return;
8406
Steve Naroff090276f2008-10-10 01:28:17 +00008407 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00008408 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8409 (*AI)->setOwningFunction(CurBlock->TheDecl);
8410
Steve Naroff090276f2008-10-10 01:28:17 +00008411 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00008412 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00008413 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00008414
Steve Naroff090276f2008-10-10 01:28:17 +00008415 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00008416 }
John McCall7a9813c2010-01-22 00:28:27 +00008417 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008418}
8419
8420/// ActOnBlockError - If there is an error parsing a block, this callback
8421/// is invoked to pop the information about the block from the action impl.
8422void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00008423 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00008424 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008425 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008426}
8427
8428/// ActOnBlockStmtExpr - This is called when the body of a block statement
8429/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00008430ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
John McCall9ae2f072010-08-23 23:25:46 +00008431 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00008432 // If blocks are disabled, emit an error.
8433 if (!LangOpts.Blocks)
8434 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00008435
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008436 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008437
Steve Naroff090276f2008-10-10 01:28:17 +00008438 PopDeclContext();
8439
Steve Naroff4eb206b2008-09-03 18:15:37 +00008440 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00008441 if (!BSI->ReturnType.isNull())
8442 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008443
Mike Stump56925862009-07-28 22:04:01 +00008444 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008445 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00008446
8447 // If the user wrote a function type in some form, try to use that.
8448 if (!BSI->FunctionType.isNull()) {
8449 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8450
8451 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8452 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8453
8454 // Turn protoless block types into nullary block types.
8455 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00008456 FunctionProtoType::ExtProtoInfo EPI;
8457 EPI.ExtInfo = Ext;
8458 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008459
8460 // Otherwise, if we don't need to change anything about the function type,
8461 // preserve its sugar structure.
8462 } else if (FTy->getResultType() == RetTy &&
8463 (!NoReturn || FTy->getNoReturnAttr())) {
8464 BlockTy = BSI->FunctionType;
8465
8466 // Otherwise, make the minimal modifications to the function type.
8467 } else {
8468 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00008469 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8470 EPI.TypeQuals = 0; // FIXME: silently?
8471 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00008472 BlockTy = Context.getFunctionType(RetTy,
8473 FPT->arg_type_begin(),
8474 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00008475 EPI);
John McCallc71a4912010-06-04 19:02:56 +00008476 }
8477
8478 // If we don't have a function type, just build one from nothing.
8479 } else {
John McCalle23cf432010-12-14 08:05:40 +00008480 FunctionProtoType::ExtProtoInfo EPI;
8481 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, 0, CC_Default);
8482 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008483 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008484
John McCallc71a4912010-06-04 19:02:56 +00008485 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8486 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00008487 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008488
Chris Lattner17a78302009-04-19 05:28:12 +00008489 // If needed, diagnose invalid gotos and switches in the block.
John McCall781472f2010-08-25 08:40:02 +00008490 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00008491 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00008492
John McCall9ae2f072010-08-23 23:25:46 +00008493 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Mike Stumpa3899eb2010-01-19 23:08:01 +00008494
8495 bool Good = true;
8496 // Check goto/label use.
8497 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
8498 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
8499 LabelStmt *L = I->second;
8500
8501 // Verify that we have no forward references left. If so, there was a goto
8502 // or address of a label taken, but no definition of it.
Argyrios Kyrtzidis355a9fe2010-09-19 21:21:25 +00008503 if (L->getSubStmt() != 0) {
8504 if (!L->isUsed())
8505 Diag(L->getIdentLoc(), diag::warn_unused_label) << L->getName();
Mike Stumpa3899eb2010-01-19 23:08:01 +00008506 continue;
Argyrios Kyrtzidis355a9fe2010-09-19 21:21:25 +00008507 }
Mike Stumpa3899eb2010-01-19 23:08:01 +00008508
8509 // Emit error.
8510 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
8511 Good = false;
8512 }
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008513 if (!Good) {
8514 PopFunctionOrBlockScope();
Mike Stumpa3899eb2010-01-19 23:08:01 +00008515 return ExprError();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008516 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008517
John McCalle0054f62010-08-25 05:56:39 +00008518 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy,
8519 BSI->hasBlockDeclRefExprs);
8520
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00008521 // Issue any analysis-based warnings.
Ted Kremenekd064fdc2010-03-23 00:13:23 +00008522 const sema::AnalysisBasedWarnings::Policy &WP =
8523 AnalysisWarnings.getDefaultPolicy();
John McCalle0054f62010-08-25 05:56:39 +00008524 AnalysisWarnings.IssueWarnings(WP, Result);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00008525
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008526 PopFunctionOrBlockScope();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008527 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00008528}
8529
John McCall60d7b3a2010-08-24 06:29:42 +00008530ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallb3d87482010-08-24 05:47:05 +00008531 Expr *expr, ParsedType type,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008532 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008533 TypeSourceInfo *TInfo;
8534 QualType T = GetTypeFromParser(type, &TInfo);
John McCall9ae2f072010-08-23 23:25:46 +00008535 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008536}
8537
John McCall60d7b3a2010-08-24 06:29:42 +00008538ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00008539 Expr *E, TypeSourceInfo *TInfo,
8540 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008541 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00008542
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008543 // Get the va_list type
8544 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008545 if (VaListType->isArrayType()) {
8546 // Deal with implicit array decay; for example, on x86-64,
8547 // va_list is an array, but it's supposed to decay to
8548 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008549 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00008550 // Make sure the input expression also decays appropriately.
8551 UsualUnaryConversions(E);
8552 } else {
8553 // Otherwise, the va_list argument must be an l-value because
8554 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00008555 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00008556 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00008557 return ExprError();
8558 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008559
Douglas Gregordd027302009-05-19 23:10:31 +00008560 if (!E->isTypeDependent() &&
8561 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00008562 return ExprError(Diag(E->getLocStart(),
8563 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008564 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00008565 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008566
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008567 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00008568 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008569
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008570 QualType T = TInfo->getType().getNonLValueExprType(Context);
8571 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00008572}
8573
John McCall60d7b3a2010-08-24 06:29:42 +00008574ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008575 // The type of __null will be int or long, depending on the size of
8576 // pointers on the target.
8577 QualType Ty;
8578 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
8579 Ty = Context.IntTy;
8580 else
8581 Ty = Context.LongTy;
8582
Sebastian Redlf53597f2009-03-15 17:47:39 +00008583 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008584}
8585
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008586static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00008587 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008588 if (!SemaRef.getLangOptions().ObjC1)
8589 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008590
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008591 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8592 if (!PT)
8593 return;
8594
8595 // Check if the destination is of type 'id'.
8596 if (!PT->isObjCIdType()) {
8597 // Check if the destination is the 'NSString' interface.
8598 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8599 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8600 return;
8601 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008602
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008603 // Strip off any parens and casts.
8604 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
8605 if (!SL || SL->isWide())
8606 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008607
Douglas Gregor849b2432010-03-31 17:46:05 +00008608 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008609}
8610
Chris Lattner5cf216b2008-01-04 18:04:52 +00008611bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8612 SourceLocation Loc,
8613 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00008614 Expr *SrcExpr, AssignmentAction Action,
8615 bool *Complained) {
8616 if (Complained)
8617 *Complained = false;
8618
Chris Lattner5cf216b2008-01-04 18:04:52 +00008619 // Decode the result (notice that AST's are still created for extensions).
8620 bool isInvalid = false;
8621 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00008622 FixItHint Hint;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008623
Chris Lattner5cf216b2008-01-04 18:04:52 +00008624 switch (ConvTy) {
8625 default: assert(0 && "Unknown conversion type");
8626 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008627 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00008628 DiagKind = diag::ext_typecheck_convert_pointer_int;
8629 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008630 case IntToPointer:
8631 DiagKind = diag::ext_typecheck_convert_int_pointer;
8632 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008633 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00008634 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00008635 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
8636 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00008637 case IncompatiblePointerSign:
8638 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8639 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008640 case FunctionVoidPointer:
8641 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8642 break;
8643 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00008644 // If the qualifiers lost were because we were applying the
8645 // (deprecated) C++ conversion from a string literal to a char*
8646 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8647 // Ideally, this check would be performed in
8648 // CheckPointerTypesForAssignment. However, that would require a
8649 // bit of refactoring (so that the second argument is an
8650 // expression, rather than a type), which should be done as part
8651 // of a larger effort to fix CheckPointerTypesForAssignment for
8652 // C++ semantics.
8653 if (getLangOptions().CPlusPlus &&
8654 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8655 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008656 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8657 break;
Sean Huntc9132b62009-11-08 07:46:34 +00008658 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00008659 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00008660 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00008661 case IntToBlockPointer:
8662 DiagKind = diag::err_int_to_block_pointer;
8663 break;
8664 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00008665 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00008666 break;
Steve Naroff39579072008-10-14 22:18:38 +00008667 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00008668 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00008669 // it can give a more specific diagnostic.
8670 DiagKind = diag::warn_incompatible_qualified_id;
8671 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00008672 case IncompatibleVectors:
8673 DiagKind = diag::warn_incompatible_vectors;
8674 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008675 case Incompatible:
8676 DiagKind = diag::err_typecheck_convert_incompatible;
8677 isInvalid = true;
8678 break;
8679 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008680
Douglas Gregord4eea832010-04-09 00:35:39 +00008681 QualType FirstType, SecondType;
8682 switch (Action) {
8683 case AA_Assigning:
8684 case AA_Initializing:
8685 // The destination type comes first.
8686 FirstType = DstType;
8687 SecondType = SrcType;
8688 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008689
Douglas Gregord4eea832010-04-09 00:35:39 +00008690 case AA_Returning:
8691 case AA_Passing:
8692 case AA_Converting:
8693 case AA_Sending:
8694 case AA_Casting:
8695 // The source type comes first.
8696 FirstType = SrcType;
8697 SecondType = DstType;
8698 break;
8699 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008700
Douglas Gregord4eea832010-04-09 00:35:39 +00008701 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008702 << SrcExpr->getSourceRange() << Hint;
Douglas Gregora41a8c52010-04-22 00:20:18 +00008703 if (Complained)
8704 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008705 return isInvalid;
8706}
Anders Carlssone21555e2008-11-30 19:50:32 +00008707
Chris Lattner3bf68932009-04-25 21:59:05 +00008708bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00008709 llvm::APSInt ICEResult;
8710 if (E->isIntegerConstantExpr(ICEResult, Context)) {
8711 if (Result)
8712 *Result = ICEResult;
8713 return false;
8714 }
8715
Anders Carlssone21555e2008-11-30 19:50:32 +00008716 Expr::EvalResult EvalResult;
8717
Mike Stumpeed9cac2009-02-19 03:04:26 +00008718 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00008719 EvalResult.HasSideEffects) {
8720 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
8721
8722 if (EvalResult.Diag) {
8723 // We only show the note if it's not the usual "invalid subexpression"
8724 // or if it's actually in a subexpression.
8725 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
8726 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
8727 Diag(EvalResult.DiagLoc, EvalResult.Diag);
8728 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008729
Anders Carlssone21555e2008-11-30 19:50:32 +00008730 return true;
8731 }
8732
Eli Friedman3b5ccca2009-04-25 22:26:58 +00008733 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
8734 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00008735
Eli Friedman3b5ccca2009-04-25 22:26:58 +00008736 if (EvalResult.Diag &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00008737 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
8738 != Diagnostic::Ignored)
Eli Friedman3b5ccca2009-04-25 22:26:58 +00008739 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008740
Anders Carlssone21555e2008-11-30 19:50:32 +00008741 if (Result)
8742 *Result = EvalResult.Val.getInt();
8743 return false;
8744}
Douglas Gregore0762c92009-06-19 23:52:42 +00008745
Douglas Gregor2afce722009-11-26 00:44:06 +00008746void
Mike Stump1eb44332009-09-09 15:08:12 +00008747Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00008748 ExprEvalContexts.push_back(
8749 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00008750}
8751
Mike Stump1eb44332009-09-09 15:08:12 +00008752void
Douglas Gregor2afce722009-11-26 00:44:06 +00008753Sema::PopExpressionEvaluationContext() {
8754 // Pop the current expression evaluation context off the stack.
8755 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
8756 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00008757
Douglas Gregor06d33692009-12-12 07:57:52 +00008758 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
8759 if (Rec.PotentiallyReferenced) {
8760 // Mark any remaining declarations in the current position of the stack
8761 // as "referenced". If they were not meant to be referenced, semantic
8762 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008763 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00008764 I = Rec.PotentiallyReferenced->begin(),
8765 IEnd = Rec.PotentiallyReferenced->end();
8766 I != IEnd; ++I)
8767 MarkDeclarationReferenced(I->first, I->second);
8768 }
8769
8770 if (Rec.PotentiallyDiagnosed) {
8771 // Emit any pending diagnostics.
8772 for (PotentiallyEmittedDiagnostics::iterator
8773 I = Rec.PotentiallyDiagnosed->begin(),
8774 IEnd = Rec.PotentiallyDiagnosed->end();
8775 I != IEnd; ++I)
8776 Diag(I->first, I->second);
8777 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008778 }
Douglas Gregor2afce722009-11-26 00:44:06 +00008779
8780 // When are coming out of an unevaluated context, clear out any
8781 // temporaries that we may have created as part of the evaluation of
8782 // the expression in that context: they aren't relevant because they
8783 // will never be constructed.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008784 if (Rec.Context == Unevaluated &&
Douglas Gregor2afce722009-11-26 00:44:06 +00008785 ExprTemporaries.size() > Rec.NumTemporaries)
8786 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
8787 ExprTemporaries.end());
8788
8789 // Destroy the popped expression evaluation record.
8790 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00008791}
Douglas Gregore0762c92009-06-19 23:52:42 +00008792
8793/// \brief Note that the given declaration was referenced in the source code.
8794///
8795/// This routine should be invoke whenever a given declaration is referenced
8796/// in the source code, and where that reference occurred. If this declaration
8797/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
8798/// C99 6.9p3), then the declaration will be marked as used.
8799///
8800/// \param Loc the location where the declaration was referenced.
8801///
8802/// \param D the declaration that has been referenced by the source code.
8803void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
8804 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00008805
Douglas Gregorc070cc62010-06-17 23:14:26 +00008806 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +00008807 return;
Mike Stump1eb44332009-09-09 15:08:12 +00008808
Douglas Gregorb5352cf2009-10-08 21:35:42 +00008809 // Mark a parameter or variable declaration "used", regardless of whether we're in a
8810 // template or not. The reason for this is that unevaluated expressions
8811 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
8812 // -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008813 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00008814 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson2127ecc2010-10-22 23:37:08 +00008815 D->setUsed();
Douglas Gregorfc2ca562010-04-07 20:29:57 +00008816 return;
8817 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008818
Douglas Gregorfc2ca562010-04-07 20:29:57 +00008819 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
8820 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008821
Douglas Gregore0762c92009-06-19 23:52:42 +00008822 // Do not mark anything as "used" within a dependent context; wait for
8823 // an instantiation.
8824 if (CurContext->isDependentContext())
8825 return;
Mike Stump1eb44332009-09-09 15:08:12 +00008826
Douglas Gregor2afce722009-11-26 00:44:06 +00008827 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00008828 case Unevaluated:
8829 // We are in an expression that is not potentially evaluated; do nothing.
8830 return;
Mike Stump1eb44332009-09-09 15:08:12 +00008831
Douglas Gregorac7610d2009-06-22 20:57:11 +00008832 case PotentiallyEvaluated:
8833 // We are in a potentially-evaluated expression, so this declaration is
8834 // "used"; handle this below.
8835 break;
Mike Stump1eb44332009-09-09 15:08:12 +00008836
Douglas Gregorac7610d2009-06-22 20:57:11 +00008837 case PotentiallyPotentiallyEvaluated:
8838 // We are in an expression that may be potentially evaluated; queue this
8839 // declaration reference until we know whether the expression is
8840 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00008841 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00008842 return;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00008843
8844 case PotentiallyEvaluatedIfUsed:
8845 // Referenced declarations will only be used if the construct in the
8846 // containing expression is used.
8847 return;
Douglas Gregorac7610d2009-06-22 20:57:11 +00008848 }
Mike Stump1eb44332009-09-09 15:08:12 +00008849
Douglas Gregore0762c92009-06-19 23:52:42 +00008850 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00008851 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008852 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00008853 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00008854 if (Constructor->getParent()->hasTrivialConstructor())
8855 return;
8856 if (!Constructor->isUsed(false))
8857 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00008858 } else if (Constructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00008859 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00008860 if (!Constructor->isUsed(false))
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008861 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
8862 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008863
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008864 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008865 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00008866 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008867 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008868 if (Destructor->isVirtual())
8869 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008870 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
8871 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
8872 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00008873 if (!MethodDecl->isUsed(false))
Douglas Gregor39957dc2010-05-01 15:04:51 +00008874 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008875 } else if (MethodDecl->isVirtual())
8876 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008877 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00008878 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00008879 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00008880 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00008881 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00008882 bool AlreadyInstantiated = false;
8883 if (FunctionTemplateSpecializationInfo *SpecInfo
8884 = Function->getTemplateSpecializationInfo()) {
8885 if (SpecInfo->getPointOfInstantiation().isInvalid())
8886 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008887 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00008888 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00008889 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008890 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00008891 = Function->getMemberSpecializationInfo()) {
8892 if (MSInfo->getPointOfInstantiation().isInvalid())
8893 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008894 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00008895 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00008896 AlreadyInstantiated = true;
8897 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008898
Douglas Gregor60406be2010-01-16 22:29:39 +00008899 if (!AlreadyInstantiated) {
8900 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
8901 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
8902 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
8903 Loc));
8904 else
Chandler Carruth62c78d52010-08-25 08:44:16 +00008905 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor60406be2010-01-16 22:29:39 +00008906 }
Gabor Greif40181c42010-08-28 00:16:06 +00008907 } else // Walk redefinitions, as some of them may be instantiable.
8908 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
8909 e(Function->redecls_end()); i != e; ++i) {
Gabor Greifbe9ebe32010-08-28 01:58:12 +00008910 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greif40181c42010-08-28 00:16:06 +00008911 MarkDeclarationReferenced(Loc, *i);
8912 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008913
Douglas Gregore0762c92009-06-19 23:52:42 +00008914 // FIXME: keep track of references to static functions
Argyrios Kyrtzidis58b52592010-08-25 10:34:54 +00008915
8916 // Recursive functions should be marked when used from another function.
8917 if (CurContext != Function)
8918 Function->setUsed(true);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008919
Douglas Gregore0762c92009-06-19 23:52:42 +00008920 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00008921 }
Mike Stump1eb44332009-09-09 15:08:12 +00008922
Douglas Gregore0762c92009-06-19 23:52:42 +00008923 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00008924 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00008925 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00008926 Var->getInstantiatedFromStaticDataMember()) {
8927 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
8928 assert(MSInfo && "Missing member specialization information?");
8929 if (MSInfo->getPointOfInstantiation().isInvalid() &&
8930 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
8931 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth62c78d52010-08-25 08:44:16 +00008932 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00008933 }
8934 }
Mike Stump1eb44332009-09-09 15:08:12 +00008935
Douglas Gregore0762c92009-06-19 23:52:42 +00008936 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00008937
Douglas Gregore0762c92009-06-19 23:52:42 +00008938 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00008939 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00008940 }
Douglas Gregore0762c92009-06-19 23:52:42 +00008941}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00008942
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00008943namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +00008944 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00008945 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +00008946 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00008947 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
8948 Sema &S;
8949 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00008950
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00008951 public:
8952 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00008953
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00008954 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00008955
8956 bool TraverseTemplateArgument(const TemplateArgument &Arg);
8957 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00008958 };
8959}
8960
Chandler Carruthdfc35e32010-06-09 08:17:30 +00008961bool MarkReferencedDecls::TraverseTemplateArgument(
8962 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00008963 if (Arg.getKind() == TemplateArgument::Declaration) {
8964 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
8965 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00008966
8967 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00008968}
8969
Chandler Carruthdfc35e32010-06-09 08:17:30 +00008970bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00008971 if (ClassTemplateSpecializationDecl *Spec
8972 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
8973 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +00008974 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00008975 }
8976
Chandler Carruthe3e210c2010-06-10 10:31:57 +00008977 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00008978}
8979
8980void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
8981 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +00008982 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00008983}
8984
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00008985namespace {
8986 /// \brief Helper class that marks all of the declarations referenced by
8987 /// potentially-evaluated subexpressions as "referenced".
8988 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
8989 Sema &S;
8990
8991 public:
8992 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
8993
8994 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
8995
8996 void VisitDeclRefExpr(DeclRefExpr *E) {
8997 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
8998 }
8999
9000 void VisitMemberExpr(MemberExpr *E) {
9001 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009002 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009003 }
9004
9005 void VisitCXXNewExpr(CXXNewExpr *E) {
9006 if (E->getConstructor())
9007 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9008 if (E->getOperatorNew())
9009 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9010 if (E->getOperatorDelete())
9011 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009012 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009013 }
9014
9015 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9016 if (E->getOperatorDelete())
9017 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +00009018 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9019 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9020 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9021 S.MarkDeclarationReferenced(E->getLocStart(),
9022 S.LookupDestructor(Record));
9023 }
9024
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009025 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009026 }
9027
9028 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9029 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009030 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009031 }
9032
9033 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9034 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9035 }
Douglas Gregor102ff972010-10-19 17:17:35 +00009036
9037 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9038 Visit(E->getExpr());
9039 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009040 };
9041}
9042
9043/// \brief Mark any declarations that appear within this expression or any
9044/// potentially-evaluated subexpressions as "referenced".
9045void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9046 EvaluatedExprMarker(*this).Visit(E);
9047}
9048
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009049/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9050/// of the program being compiled.
9051///
9052/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009053/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009054/// possibility that the code will actually be executable. Code in sizeof()
9055/// expressions, code used only during overload resolution, etc., are not
9056/// potentially evaluated. This routine will suppress such diagnostics or,
9057/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009058/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009059/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009060///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009061/// This routine should be used for all diagnostics that describe the run-time
9062/// behavior of a program, such as passing a non-POD value through an ellipsis.
9063/// Failure to do so will likely result in spurious diagnostics or failures
9064/// during overload resolution or within sizeof/alignof/typeof/typeid.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009065bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009066 const PartialDiagnostic &PD) {
9067 switch (ExprEvalContexts.back().Context ) {
9068 case Unevaluated:
9069 // The argument will never be evaluated, so don't complain.
9070 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009071
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009072 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009073 case PotentiallyEvaluatedIfUsed:
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009074 Diag(Loc, PD);
9075 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009076
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009077 case PotentiallyPotentiallyEvaluated:
9078 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9079 break;
9080 }
9081
9082 return false;
9083}
9084
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009085bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9086 CallExpr *CE, FunctionDecl *FD) {
9087 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9088 return false;
9089
9090 PartialDiagnostic Note =
9091 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9092 << FD->getDeclName() : PDiag();
9093 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009094
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009095 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009096 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009097 PDiag(diag::err_call_function_incomplete_return)
9098 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009099 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009100 << CE->getSourceRange(),
9101 std::make_pair(NoteLoc, Note)))
9102 return true;
9103
9104 return false;
9105}
9106
John McCall5a881bb2009-10-12 21:59:07 +00009107// Diagnose the common s/=/==/ typo. Note that adding parentheses
9108// will prevent this condition from triggering, which is what we want.
9109void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9110 SourceLocation Loc;
9111
John McCalla52ef082009-11-11 02:41:58 +00009112 unsigned diagnostic = diag::warn_condition_is_assignment;
9113
John McCall5a881bb2009-10-12 21:59:07 +00009114 if (isa<BinaryOperator>(E)) {
9115 BinaryOperator *Op = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00009116 if (Op->getOpcode() != BO_Assign)
John McCall5a881bb2009-10-12 21:59:07 +00009117 return;
9118
John McCallc8d8ac52009-11-12 00:06:05 +00009119 // Greylist some idioms by putting them into a warning subcategory.
9120 if (ObjCMessageExpr *ME
9121 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9122 Selector Sel = ME->getSelector();
9123
John McCallc8d8ac52009-11-12 00:06:05 +00009124 // self = [<foo> init...]
9125 if (isSelfExpr(Op->getLHS())
9126 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
9127 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9128
9129 // <foo> = [<bar> nextObject]
9130 else if (Sel.isUnarySelector() &&
9131 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
9132 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9133 }
John McCalla52ef082009-11-11 02:41:58 +00009134
John McCall5a881bb2009-10-12 21:59:07 +00009135 Loc = Op->getOperatorLoc();
9136 } else if (isa<CXXOperatorCallExpr>(E)) {
9137 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
9138 if (Op->getOperator() != OO_Equal)
9139 return;
9140
9141 Loc = Op->getOperatorLoc();
9142 } else {
9143 // Not an assignment.
9144 return;
9145 }
9146
John McCall5a881bb2009-10-12 21:59:07 +00009147 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00009148 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009149
Douglas Gregor55b38842010-04-14 16:09:52 +00009150 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor827feec2010-01-08 00:20:23 +00009151 Diag(Loc, diag::note_condition_assign_to_comparison)
Douglas Gregor849b2432010-03-31 17:46:05 +00009152 << FixItHint::CreateReplacement(Loc, "==");
Douglas Gregor55b38842010-04-14 16:09:52 +00009153 Diag(Loc, diag::note_condition_assign_silence)
9154 << FixItHint::CreateInsertion(Open, "(")
9155 << FixItHint::CreateInsertion(Close, ")");
John McCall5a881bb2009-10-12 21:59:07 +00009156}
9157
9158bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
9159 DiagnoseAssignmentAsCondition(E);
9160
9161 if (!E->isTypeDependent()) {
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00009162 if (E->isBoundMemberFunction(Context))
9163 return Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9164 << E->getSourceRange();
9165
John McCallf6a16482010-12-04 03:47:34 +00009166 if (getLangOptions().CPlusPlus)
9167 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9168
9169 DefaultFunctionArrayLvalueConversion(E);
John McCallabc56c72010-12-04 06:09:13 +00009170
9171 QualType T = E->getType();
John McCallf6a16482010-12-04 03:47:34 +00009172 if (!T->isScalarType()) // C99 6.8.4.1p1
9173 return Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9174 << T << E->getSourceRange();
John McCall5a881bb2009-10-12 21:59:07 +00009175 }
9176
9177 return false;
9178}
Douglas Gregor586596f2010-05-06 17:25:47 +00009179
John McCall60d7b3a2010-08-24 06:29:42 +00009180ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9181 Expr *Sub) {
Douglas Gregoreecf38f2010-05-06 21:39:56 +00009182 if (!Sub)
Douglas Gregor586596f2010-05-06 17:25:47 +00009183 return ExprError();
9184
Douglas Gregorff331c12010-07-25 18:17:45 +00009185 if (CheckBooleanCondition(Sub, Loc))
Douglas Gregor586596f2010-05-06 17:25:47 +00009186 return ExprError();
Douglas Gregor586596f2010-05-06 17:25:47 +00009187
9188 return Owned(Sub);
9189}
John McCall2a984ca2010-10-12 00:20:44 +00009190
9191/// Check for operands with placeholder types and complain if found.
9192/// Returns true if there was an error and no recovery was possible.
9193ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) {
9194 const BuiltinType *BT = E->getType()->getAs<BuiltinType>();
9195 if (!BT || !BT->isPlaceholderType()) return Owned(E);
9196
9197 // If this is overload, check for a single overload.
9198 if (BT->getKind() == BuiltinType::Overload) {
9199 if (FunctionDecl *Specialization
9200 = ResolveSingleFunctionTemplateSpecialization(E)) {
9201 // The access doesn't really matter in this case.
9202 DeclAccessPair Found = DeclAccessPair::make(Specialization,
9203 Specialization->getAccess());
9204 E = FixOverloadedFunctionReference(E, Found, Specialization);
9205 if (!E) return ExprError();
9206 return Owned(E);
9207 }
9208
John McCall2cd11fe2010-10-12 02:09:17 +00009209 Diag(Loc, diag::err_ovl_unresolvable) << E->getSourceRange();
John McCall2a984ca2010-10-12 00:20:44 +00009210 return ExprError();
9211 }
9212
9213 // Otherwise it's a use of undeduced auto.
9214 assert(BT->getKind() == BuiltinType::UndeducedAuto);
9215
9216 DeclRefExpr *DRE = cast<DeclRefExpr>(E->IgnoreParens());
9217 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
9218 << DRE->getDecl() << E->getSourceRange();
9219 return ExprError();
9220}