blob: 3112ccb55f398333f51b300bd8a37f4a9c955e26 [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/AnalysisBasedWarnings.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000018#include "clang/AST/ASTContext.h"
Douglas Gregord1702062010-04-29 00:18:15 +000019#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000023#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000024#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000025#include "clang/AST/ExprObjC.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000026#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000027#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000029#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000030#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000031#include "clang/Lex/LiteralSupport.h"
32#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000033#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Designator.h"
35#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000036#include "clang/Sema/ScopeInfo.h"
John McCall8b0666c2010-08-20 18:27:03 +000037#include "clang/Sema/ParsedTemplate.h"
John McCallde6836a2010-08-24 07:21:54 +000038#include "clang/Sema/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000039using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000040using namespace sema;
Chris Lattner5b183d82006-11-10 05:03:26 +000041
David Chisnall9f57c292009-08-17 16:35:33 +000042
Douglas Gregor171c45a2009-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 Jahanian7d6e11a2010-12-21 00:44:01 +000052/// If IgnoreDeprecated is set to true, this should not warn about deprecated
Chris Lattnerb7df3c62009-10-25 22:31:57 +000053/// decls.
54///
Douglas Gregor171c45a2009-02-18 21:56:37 +000055/// \returns true if there was an error (this declaration cannot be
56/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000057///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000058bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Peter Collingbourneed12ffb2011-01-02 19:53:12 +000059 bool UnknownObjCClass) {
Douglas Gregor5bb5e4a2010-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 Lattner4bf74fd2009-02-15 22:43:40 +000078 // See if the decl is deprecated.
Benjamin Kramerbfac7dc2010-10-09 15:49:00 +000079 if (const DeprecatedAttr *DA = D->getAttr<DeprecatedAttr>())
Peter Collingbourneed12ffb2011-01-02 19:53:12 +000080 EmitDeprecationWarning(D, DA->getMessage(), Loc, UnknownObjCClass);
Chris Lattner4bf74fd2009-02-15 22:43:40 +000081
Chris Lattnera27dd592009-10-25 17:21:40 +000082 // See if the decl is unavailable
Fariborz Jahanianc74073c2010-10-06 23:12:32 +000083 if (const UnavailableAttr *UA = D->getAttr<UnavailableAttr>()) {
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000084 if (UA->getMessage().empty()) {
Peter Collingbourneed12ffb2011-01-02 19:53:12 +000085 if (!UnknownObjCClass)
Fariborz Jahanian7d6e11a2010-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 Jahanianc74073c2010-10-06 23:12:32 +000092 Diag(Loc, diag::err_unavailable_message)
Benjamin Kramerbfac7dc2010-10-09 15:49:00 +000093 << D->getDeclName() << UA->getMessage();
Chris Lattnera27dd592009-10-25 17:21:40 +000094 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
95 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000096
Douglas Gregor171c45a2009-02-18 21:56:37 +000097 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000098 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-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 Gregorde681d42009-02-24 04:26:15 +0000104 }
Douglas Gregor171c45a2009-02-18 21:56:37 +0000105
Anders Carlsson73067a02010-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 Gregor171c45a2009-02-18 21:56:37 +0000110 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000111}
112
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000113/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +0000114/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-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 Stump11289f42009-09-09 15:08:12 +0000118 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000119 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000120 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000121 return;
Douglas Gregorc298ffc2010-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 Jahanian9e877212009-05-13 23:20:50 +0000125 int sentinelPos = attr->getSentinel();
126 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +0000127
Mike Stump87c57ac2009-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 Jahanian9e877212009-05-13 23:20:50 +0000130 unsigned int i = 0;
Fariborz Jahanian4a528032009-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 Stump12b8ce12009-08-04 21:02:39 +0000144 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-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 Stump12b8ce12009-08-04 21:02:39 +0000154 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000155 // block or function pointer call.
156 QualType Ty = V->getType();
157 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000158 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000159 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
160 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-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 Stump12b8ce12009-08-04 21:02:39 +0000174 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000175 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000176 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000177 return;
178
179 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000180 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000181 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-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 Jahanian4a528032009-05-14 18:00:00 +0000191 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000192 return;
193 }
194 while (i < NumArgs-1) {
195 ++i;
196 ++sentinel;
197 }
198 Expr *sentinelExpr = Args[sentinel];
John McCall7ddbcf42010-05-06 23:53:00 +0000199 if (!sentinelExpr) return;
200 if (sentinelExpr->isTypeDependent()) return;
201 if (sentinelExpr->isValueDependent()) return;
Anders Carlssone981a8c2010-11-05 15:21:33 +0000202
203 // nullptr_t is always treated as null.
204 if (sentinelExpr->getType()->isNullPtrType()) return;
205
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000206 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-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 Jahanian027b8862009-05-13 18:09:35 +0000216}
217
Douglas Gregor87f95b02009-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 Lattner513165e2008-07-25 21:10:04 +0000223//===----------------------------------------------------------------------===//
224// Standard Promotions and Conversions
225//===----------------------------------------------------------------------===//
226
Chris Lattner513165e2008-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 Lattner513165e2008-07-25 21:10:04 +0000232 if (Ty->isFunctionType())
Mike Stump11289f42009-09-09 15:08:12 +0000233 ImpCastExprToType(E, Context.getPointerType(Ty),
John McCalle3027922010-08-25 11:45:40 +0000234 CK_FunctionToPointerDecay);
Chris Lattner61f60a02008-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 Kyrtzidis9321c742008-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 McCall086a4642010-11-24 05:12:34 +0000247 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
Anders Carlsson8fc489d2009-08-07 23:48:20 +0000248 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
John McCalle3027922010-08-25 11:45:40 +0000249 CK_ArrayToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000250 }
Chris Lattner513165e2008-07-25 21:10:04 +0000251}
252
John McCall27584242010-12-06 20:48:59 +0000253void Sema::DefaultLvalueConversion(Expr *&E) {
John McCallf3735e02010-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 McCall27584242010-12-06 20:48:59 +0000257 if (!E->isGLValue()) return;
John McCall34376a62010-12-04 03:47:34 +0000258
John McCall27584242010-12-06 20:48:59 +0000259 QualType T = E->getType();
260 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000261
John McCall27584242010-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 McCall34376a62010-12-04 03:47:34 +0000266 return;
Douglas Gregorb92a1562010-02-03 00:27:59 +0000267 }
John McCall27584242010-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 Gregorb92a1562010-02-03 00:27:59 +0000304}
305
306
Chris Lattner513165e2008-07-25 21:10:04 +0000307/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000308/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-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 McCallf3735e02010-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 Lattner513165e2008-07-25 21:10:04 +0000317 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-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 Friedman629ffb92009-08-20 04:21:42 +0000346 }
347
John McCallf3735e02010-12-01 04:43:34 +0000348 return E;
Chris Lattner513165e2008-07-25 21:10:04 +0000349}
350
Chris Lattner2ce500f2008-07-25 22:25:12 +0000351/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000352/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-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 Stump11289f42009-09-09 15:08:12 +0000357
John McCall9bc26772010-12-06 18:36:11 +0000358 UsualUnaryConversions(Expr);
359
Chris Lattner2ce500f2008-07-25 22:25:12 +0000360 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000361 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John McCall9bc26772010-12-06 18:36:11 +0000362 return ImpCastExprToType(Expr, Context.DoubleTy, CK_FloatingCast);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000363}
364
Chris Lattnera8a7d0f2009-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 Lattnerbb53efb2010-05-16 04:01:30 +0000369bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
370 FunctionDecl *FDecl) {
Anders Carlssona7d069d2009-01-16 16:48:51 +0000371 DefaultArgumentPromotion(Expr);
Mike Stump11289f42009-09-09 15:08:12 +0000372
Chris Lattnerbb53efb2010-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 McCall8b07ec22010-05-15 11:32:37 +0000379 if (Expr->getType()->isObjCObjectType() &&
Douglas Gregorda8cdbc2009-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 Gregor7ca84af2009-12-12 07:25:49 +0000384
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000385 if (!Expr->getType()->isPODType() &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000386 DiagRuntimeBehavior(Expr->getLocStart(),
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000387 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
388 << Expr->getType() << CT))
389 return true;
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000390
391 return false;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000392}
393
Chris Lattner513165e2008-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 Stump11289f42009-09-09 15:08:12 +0000396/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-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 Friedman8b7b1b12009-03-28 01:22:36 +0000402 if (!isCompAssign)
Chris Lattner513165e2008-07-25 21:10:04 +0000403 UsualUnaryConversions(lhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000404
405 UsualUnaryConversions(rhsExpr);
Douglas Gregora11693b2008-11-12 17:17:38 +0000406
Mike Stump11289f42009-09-09 15:08:12 +0000407 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000408 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000409 QualType lhs =
410 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000411 QualType rhs =
Chris Lattner574dee62008-07-26 22:17:49 +0000412 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-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 McCalld005ac92010-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 Friedman629ffb92009-08-20 04:21:42 +0000427 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000428 if (!LHSBitfieldPromoteTy.isNull())
429 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000430 if (lhs != lhs_unpromoted && !isCompAssign)
431 ImpCastExprToType(lhsExpr, lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000432
John McCalld005ac92010-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 McCallc5e62b42010-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 McCalld7646252010-11-14 08:17:51 +0000452 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000453 }
John McCalld005ac92010-11-13 08:17:45 +0000454 return lhs;
455 }
456
John McCallc5e62b42010-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 McCalld7646252010-11-14 08:17:51 +0000466 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000467 }
468 }
John McCalld005ac92010-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 McCallc5e62b42010-11-13 09:02:35 +0000488 ImpCastExprToType(rhsExpr, lhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000489 return lhs;
490
491 } else if (order < 0) {
492 // _Complex float -> _Complex double
493 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000494 ImpCastExprToType(lhsExpr, rhs, CK_FloatingComplexCast);
John McCalld005ac92010-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 McCallc5e62b42010-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 McCalld005ac92010-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 McCallc5e62b42010-11-13 09:02:35 +0000515 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000516
517 // _Complex float -> _Complex double
518 if (!isCompAssign && order < 0)
John McCallc5e62b42010-11-13 09:02:35 +0000519 ImpCastExprToType(lhsExpr, result, CK_FloatingComplexCast);
John McCalld005ac92010-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 McCallc5e62b42010-11-13 09:02:35 +0000530 if (!isCompAssign) {
Argyrios Kyrtzidise84389b2011-01-18 18:49:33 +0000531 QualType fp = cast<ComplexType>(rhs)->getElementType();
532 ImpCastExprToType(lhsExpr, fp, CK_FloatingCast);
John McCallc5e62b42010-11-13 09:02:35 +0000533 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
534 }
John McCalld005ac92010-11-13 08:17:45 +0000535 return rhs;
536 }
537
538 // LHS is at least as wide. Find its corresponding complex type.
539 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
540
541 // double -> _Complex double
542 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000543 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000544
545 // _Complex float -> _Complex double
546 if (order > 0)
John McCallc5e62b42010-11-13 09:02:35 +0000547 ImpCastExprToType(rhsExpr, result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000548
549 return result;
550 }
551
552 // Now handle "real" floating types (i.e. float, double, long double).
553 bool LHSFloat = lhs->isRealFloatingType();
554 bool RHSFloat = rhs->isRealFloatingType();
555 if (LHSFloat || RHSFloat) {
556 // If we have two real floating types, convert the smaller operand
557 // to the bigger result.
558 if (LHSFloat && RHSFloat) {
559 int order = Context.getFloatingTypeOrder(lhs, rhs);
560 if (order > 0) {
561 ImpCastExprToType(rhsExpr, lhs, CK_FloatingCast);
562 return lhs;
563 }
564
565 assert(order < 0 && "illegal float comparison");
566 if (!isCompAssign)
567 ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast);
568 return rhs;
569 }
570
571 // If we have an integer operand, the result is the real floating type.
572 if (LHSFloat) {
573 if (rhs->isIntegerType()) {
574 // Convert rhs to the lhs floating point type.
575 ImpCastExprToType(rhsExpr, lhs, CK_IntegralToFloating);
576 return lhs;
577 }
578
579 // Convert both sides to the appropriate complex float.
580 assert(rhs->isComplexIntegerType());
581 QualType result = Context.getComplexType(lhs);
582
583 // _Complex int -> _Complex float
John McCalld7646252010-11-14 08:17:51 +0000584 ImpCastExprToType(rhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000585
586 // float -> _Complex float
587 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000588 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000589
590 return result;
591 }
592
593 assert(RHSFloat);
594 if (lhs->isIntegerType()) {
595 // Convert lhs to the rhs floating point type.
596 if (!isCompAssign)
597 ImpCastExprToType(lhsExpr, rhs, CK_IntegralToFloating);
598 return rhs;
599 }
600
601 // Convert both sides to the appropriate complex float.
602 assert(lhs->isComplexIntegerType());
603 QualType result = Context.getComplexType(rhs);
604
605 // _Complex int -> _Complex float
606 if (!isCompAssign)
John McCalld7646252010-11-14 08:17:51 +0000607 ImpCastExprToType(lhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000608
609 // float -> _Complex float
John McCallc5e62b42010-11-13 09:02:35 +0000610 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000611
612 return result;
613 }
614
615 // Handle GCC complex int extension.
616 // FIXME: if the operands are (int, _Complex long), we currently
617 // don't promote the complex. Also, signedness?
618 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
619 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
620 if (lhsComplexInt && rhsComplexInt) {
621 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
622 rhsComplexInt->getElementType());
623 assert(order && "inequal types with equal element ordering");
624 if (order > 0) {
625 // _Complex int -> _Complex long
John McCallc5e62b42010-11-13 09:02:35 +0000626 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000627 return lhs;
628 }
629
630 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000631 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000632 return rhs;
633 } else if (lhsComplexInt) {
634 // int -> _Complex int
John McCallc5e62b42010-11-13 09:02:35 +0000635 ImpCastExprToType(rhsExpr, lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000636 return lhs;
637 } else if (rhsComplexInt) {
638 // int -> _Complex int
639 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000640 ImpCastExprToType(lhsExpr, rhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000641 return rhs;
642 }
643
644 // Finally, we have two differing integer types.
645 // The rules for this case are in C99 6.3.1.8
646 int compare = Context.getIntegerTypeOrder(lhs, rhs);
647 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
648 rhsSigned = rhs->hasSignedIntegerRepresentation();
649 if (lhsSigned == rhsSigned) {
650 // Same signedness; use the higher-ranked type
651 if (compare >= 0) {
652 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
653 return lhs;
654 } else if (!isCompAssign)
655 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
656 return rhs;
657 } else if (compare != (lhsSigned ? 1 : -1)) {
658 // The unsigned type has greater than or equal rank to the
659 // signed type, so use the unsigned type
660 if (rhsSigned) {
661 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
662 return lhs;
663 } else if (!isCompAssign)
664 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
665 return rhs;
666 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
667 // The two types are different widths; if we are here, that
668 // means the signed type is larger than the unsigned type, so
669 // use the signed type.
670 if (lhsSigned) {
671 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
672 return lhs;
673 } else if (!isCompAssign)
674 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
675 return rhs;
676 } else {
677 // The signed type is higher-ranked than the unsigned type,
678 // but isn't actually any bigger (like unsigned int and long
679 // on most 32-bit systems). Use the unsigned type corresponding
680 // to the signed type.
681 QualType result =
682 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
683 ImpCastExprToType(rhsExpr, result, CK_IntegralCast);
684 if (!isCompAssign)
685 ImpCastExprToType(lhsExpr, result, CK_IntegralCast);
686 return result;
687 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000688}
689
Chris Lattner513165e2008-07-25 21:10:04 +0000690//===----------------------------------------------------------------------===//
691// Semantic Analysis for various Expression Types
692//===----------------------------------------------------------------------===//
693
694
Steve Naroff83895f72007-09-16 03:34:24 +0000695/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000696/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
697/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
698/// multiple tokens. However, the common case is that StringToks points to one
699/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000700///
John McCalldadc5752010-08-24 06:29:42 +0000701ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +0000702Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000703 assert(NumStringToks && "Must have at least one string!");
704
Chris Lattner8a24e582009-01-16 18:51:42 +0000705 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000706 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000707 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000708
Chris Lattner23b7eb62007-06-15 23:05:46 +0000709 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000710 for (unsigned i = 0; i != NumStringToks; ++i)
711 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000712
Chris Lattner36fc8792008-02-11 00:02:17 +0000713 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidiscbad7252008-08-09 17:20:01 +0000714 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattner36fc8792008-02-11 00:02:17 +0000715 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000716
717 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +0000718 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000719 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000720
Chris Lattner36fc8792008-02-11 00:02:17 +0000721 // Get an array type for the string, according to C99 6.4.5. This includes
722 // the nul terminator character as well as the string length for pascal
723 // strings.
724 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000725 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000726 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000727
Chris Lattner5b183d82006-11-10 05:03:26 +0000728 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +0000729 return Owned(StringLiteral::Create(Context, Literal.GetString(),
730 Literal.GetStringLength(),
731 Literal.AnyWide, StrTy,
732 &StringTokLocs[0],
733 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000734}
735
Chris Lattner2a9d9892008-10-20 05:16:36 +0000736/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
737/// CurBlock to VD should cause it to be snapshotted (as we do for auto
738/// variables defined outside the block) or false if this is not needed (e.g.
739/// for values inside the block or for globals).
740///
Douglas Gregor4f13beb2010-03-01 20:44:28 +0000741/// This also keeps the 'hasBlockDeclRefExprs' in the BlockScopeInfo records
Chris Lattner497d7b02009-04-21 22:26:47 +0000742/// up-to-date.
743///
Douglas Gregor9a28e842010-03-01 23:15:13 +0000744static bool ShouldSnapshotBlockValueReference(Sema &S, BlockScopeInfo *CurBlock,
Chris Lattner2a9d9892008-10-20 05:16:36 +0000745 ValueDecl *VD) {
746 // If the value is defined inside the block, we couldn't snapshot it even if
747 // we wanted to.
748 if (CurBlock->TheDecl == VD->getDeclContext())
749 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000750
Chris Lattner2a9d9892008-10-20 05:16:36 +0000751 // If this is an enum constant or function, it is constant, don't snapshot.
752 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
753 return false;
754
755 // If this is a reference to an extern, static, or global variable, no need to
756 // snapshot it.
757 // FIXME: What about 'const' variables in C++?
758 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner497d7b02009-04-21 22:26:47 +0000759 if (!Var->hasLocalStorage())
760 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000761
Chris Lattner497d7b02009-04-21 22:26:47 +0000762 // Blocks that have these can't be constant.
763 CurBlock->hasBlockDeclRefExprs = true;
764
765 // If we have nested blocks, the decl may be declared in an outer block (in
766 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
767 // be defined outside all of the current blocks (in which case the blocks do
768 // all get the bit). Walk the nesting chain.
Douglas Gregor9a28e842010-03-01 23:15:13 +0000769 for (unsigned I = S.FunctionScopes.size() - 1; I; --I) {
770 BlockScopeInfo *NextBlock = dyn_cast<BlockScopeInfo>(S.FunctionScopes[I]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000771
Douglas Gregor9a28e842010-03-01 23:15:13 +0000772 if (!NextBlock)
773 continue;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000774
Chris Lattner497d7b02009-04-21 22:26:47 +0000775 // If we found the defining block for the variable, don't mark the block as
776 // having a reference outside it.
777 if (NextBlock->TheDecl == VD->getDeclContext())
778 break;
Mike Stump11289f42009-09-09 15:08:12 +0000779
Chris Lattner497d7b02009-04-21 22:26:47 +0000780 // Otherwise, the DeclRef from the inner block causes the outer one to need
781 // a snapshot as well.
782 NextBlock->hasBlockDeclRefExprs = true;
783 }
Mike Stump11289f42009-09-09 15:08:12 +0000784
Chris Lattner2a9d9892008-10-20 05:16:36 +0000785 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000786}
787
Chris Lattner2a9d9892008-10-20 05:16:36 +0000788
John McCalldadc5752010-08-24 06:29:42 +0000789ExprResult
John McCall7decc9e2010-11-18 06:31:45 +0000790Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
791 SourceLocation Loc, const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000792 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +0000793 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000794}
795
796/// BuildDeclRefExpr - Build a DeclRefExpr.
John McCalldadc5752010-08-24 06:29:42 +0000797ExprResult
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000798Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +0000799 ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000800 const DeclarationNameInfo &NameInfo,
801 const CXXScopeSpec *SS) {
Anders Carlsson364035d12009-06-26 19:16:07 +0000802 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000803 Diag(NameInfo.getLoc(),
Mike Stump11289f42009-09-09 15:08:12 +0000804 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlsson364035d12009-06-26 19:16:07 +0000805 << D->getDeclName();
806 return ExprError();
807 }
Mike Stump11289f42009-09-09 15:08:12 +0000808
Anders Carlsson946b86d2009-06-24 00:10:43 +0000809 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Douglas Gregor15243332010-04-27 21:10:04 +0000810 if (isa<NonTypeTemplateParmDecl>(VD)) {
811 // Non-type template parameters can be referenced anywhere they are
812 // visible.
Douglas Gregora8a089b2010-07-13 18:40:04 +0000813 Ty = Ty.getNonLValueExprType(Context);
Douglas Gregor15243332010-04-27 21:10:04 +0000814 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
Anders Carlsson946b86d2009-06-24 00:10:43 +0000815 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
816 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000817 Diag(NameInfo.getLoc(),
818 diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000819 << D->getIdentifier() << FD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +0000820 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000821 << D->getIdentifier();
822 return ExprError();
823 }
824 }
John McCall4bc41ae2010-11-18 19:01:18 +0000825
826 // This ridiculousness brought to you by 'extern void x;' and the
827 // GNU compiler collection.
828 } else if (!getLangOptions().CPlusPlus && !Ty.hasQualifiers() &&
829 Ty->isVoidType()) {
830 VK = VK_RValue;
Anders Carlsson946b86d2009-06-24 00:10:43 +0000831 }
832 }
Mike Stump11289f42009-09-09 15:08:12 +0000833
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000834 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +0000835
John McCall086a4642010-11-24 05:12:34 +0000836 Expr *E = DeclRefExpr::Create(Context,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000837 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
John McCall086a4642010-11-24 05:12:34 +0000838 SS? SS->getRange() : SourceRange(),
839 D, NameInfo, Ty, VK);
840
841 // Just in case we're building an illegal pointer-to-member.
842 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
843 E->setObjectKind(OK_BitField);
844
845 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000846}
847
John McCallfeb624a2010-11-23 20:48:44 +0000848static ExprResult
849BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
850 const CXXScopeSpec &SS, FieldDecl *Field,
851 DeclAccessPair FoundDecl,
852 const DeclarationNameInfo &MemberNameInfo);
853
John McCalldadc5752010-08-24 06:29:42 +0000854ExprResult
Douglas Gregord5846a12009-04-15 06:41:24 +0000855Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
Francois Pichet783dd6e2010-11-21 06:08:52 +0000856 IndirectFieldDecl *IndirectField,
Douglas Gregord5846a12009-04-15 06:41:24 +0000857 Expr *BaseObjectExpr,
858 SourceLocation OpLoc) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000859 // Build the expression that refers to the base object, from
860 // which we will build a sequence of member references to each
861 // of the anonymous union objects and, eventually, the field we
862 // found via name lookup.
863 bool BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000864 Qualifiers BaseQuals;
Francois Pichet783dd6e2010-11-21 06:08:52 +0000865 VarDecl *BaseObject = IndirectField->getVarDecl();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000866 if (BaseObject) {
867 // BaseObject is an anonymous struct/union variable (and is,
868 // therefore, not part of another non-anonymous record).
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000869 MarkDeclarationReferenced(Loc, BaseObject);
John McCall7decc9e2010-11-18 06:31:45 +0000870 BaseObjectExpr =
871 new (Context) DeclRefExpr(BaseObject, BaseObject->getType(),
872 VK_LValue, Loc);
John McCall8ccfcb52009-09-24 19:53:00 +0000873 BaseQuals
874 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000875 } else if (BaseObjectExpr) {
876 // The caller provided the base object expression. Determine
877 // whether its a pointer and whether it adds any qualifiers to the
878 // anonymous struct/union fields we're looking into.
879 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000880 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000881 BaseObjectIsPointer = true;
882 ObjectType = ObjectPtr->getPointeeType();
883 }
John McCall8ccfcb52009-09-24 19:53:00 +0000884 BaseQuals
885 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000886 } else {
887 // We've found a member of an anonymous struct/union that is
888 // inside a non-anonymous struct/union, so in a well-formed
889 // program our base object expression is "this".
John McCall87fe5d52010-05-20 01:18:31 +0000890 DeclContext *DC = getFunctionLevelDeclContext();
891 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000892 if (!MD->isStatic()) {
Mike Stump11289f42009-09-09 15:08:12 +0000893 QualType AnonFieldType
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000894 = Context.getTagDeclType(
Francois Pichet783dd6e2010-11-21 06:08:52 +0000895 cast<RecordDecl>(
896 (*IndirectField->chain_begin())->getDeclContext()));
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000897 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump11289f42009-09-09 15:08:12 +0000898 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000899 == Context.getCanonicalType(ThisType)) ||
900 IsDerivedFrom(ThisType, AnonFieldType)) {
901 // Our base object expression is "this".
Douglas Gregor4b654412009-12-24 20:23:34 +0000902 BaseObjectExpr = new (Context) CXXThisExpr(Loc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000903 MD->getThisType(Context),
904 /*isImplicit=*/true);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000905 BaseObjectIsPointer = true;
906 }
907 } else {
Sebastian Redlffbcf962009-01-18 18:53:16 +0000908 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
Francois Pichet783dd6e2010-11-21 06:08:52 +0000909 << IndirectField->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000910 }
John McCall8ccfcb52009-09-24 19:53:00 +0000911 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000912 }
913
Mike Stump11289f42009-09-09 15:08:12 +0000914 if (!BaseObjectExpr)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000915 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
Francois Pichet783dd6e2010-11-21 06:08:52 +0000916 << IndirectField->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000917 }
918
919 // Build the implicit member references to the field of the
920 // anonymous struct/union.
921 Expr *Result = BaseObjectExpr;
John McCallfeb624a2010-11-23 20:48:44 +0000922
Francois Pichet783dd6e2010-11-21 06:08:52 +0000923 IndirectFieldDecl::chain_iterator FI = IndirectField->chain_begin(),
924 FEnd = IndirectField->chain_end();
John McCallfeb624a2010-11-23 20:48:44 +0000925
Francois Pichet783dd6e2010-11-21 06:08:52 +0000926 // Skip the first VarDecl if present.
927 if (BaseObject)
928 FI++;
929 for (; FI != FEnd; FI++) {
930 FieldDecl *Field = cast<FieldDecl>(*FI);
John McCall8ccfcb52009-09-24 19:53:00 +0000931
John McCallfeb624a2010-11-23 20:48:44 +0000932 // FIXME: the first access can be qualified
933 CXXScopeSpec SS;
John McCall8ccfcb52009-09-24 19:53:00 +0000934
John McCallfeb624a2010-11-23 20:48:44 +0000935 // FIXME: these are somewhat meaningless
936 DeclarationNameInfo MemberNameInfo(Field->getDeclName(), Loc);
937 DeclAccessPair FoundDecl = DeclAccessPair::make(Field, Field->getAccess());
John McCall8ccfcb52009-09-24 19:53:00 +0000938
John McCallfeb624a2010-11-23 20:48:44 +0000939 Result = BuildFieldReferenceExpr(*this, Result, BaseObjectIsPointer,
940 SS, Field, FoundDecl, MemberNameInfo)
941 .take();
John McCall8ccfcb52009-09-24 19:53:00 +0000942
John McCallfeb624a2010-11-23 20:48:44 +0000943 // All the implicit accesses are dot-accesses.
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000944 BaseObjectIsPointer = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000945 }
946
Sebastian Redlffbcf962009-01-18 18:53:16 +0000947 return Owned(Result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000948}
949
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000950/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +0000951/// possibly a list of template arguments.
952///
953/// If this produces template arguments, it is permitted to call
954/// DecomposeTemplateName.
955///
956/// This actually loses a lot of source location information for
957/// non-standard name kinds; we should consider preserving that in
958/// some way.
959static void DecomposeUnqualifiedId(Sema &SemaRef,
960 const UnqualifiedId &Id,
961 TemplateArgumentListInfo &Buffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000962 DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +0000963 const TemplateArgumentListInfo *&TemplateArgs) {
964 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
965 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
966 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
967
968 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
969 Id.TemplateId->getTemplateArgs(),
970 Id.TemplateId->NumArgs);
971 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
972 TemplateArgsPtr.release();
973
John McCall3e56fd42010-08-23 07:28:44 +0000974 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000975 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
976 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +0000977 TemplateArgs = &Buffer;
978 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000979 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +0000980 TemplateArgs = 0;
981 }
982}
983
John McCall69f9dbc2010-02-08 19:26:07 +0000984/// Determines whether the given record is "fully-formed" at the given
985/// location, i.e. whether a qualified lookup into it is assured of
986/// getting consistent results already.
John McCall10eae182009-11-30 22:42:35 +0000987static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
John McCall69f9dbc2010-02-08 19:26:07 +0000988 if (!Record->hasDefinition())
989 return false;
990
John McCall10eae182009-11-30 22:42:35 +0000991 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
992 E = Record->bases_end(); I != E; ++I) {
993 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
994 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
995 if (!BaseRT) return false;
996
997 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall69f9dbc2010-02-08 19:26:07 +0000998 if (!BaseRecord->hasDefinition() ||
John McCall10eae182009-11-30 22:42:35 +0000999 !IsFullyFormedScope(SemaRef, BaseRecord))
1000 return false;
1001 }
1002
1003 return true;
1004}
1005
John McCall2d74de92009-12-01 22:10:20 +00001006/// Determines if the given class is provably not derived from all of
1007/// the prospective base classes.
1008static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1009 CXXRecordDecl *Record,
1010 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +00001011 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +00001012 return false;
1013
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001014 RecordDecl *RD = Record->getDefinition();
John McCalla6d407c2009-12-01 22:28:41 +00001015 if (!RD) return false;
1016 Record = cast<CXXRecordDecl>(RD);
1017
John McCall2d74de92009-12-01 22:10:20 +00001018 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1019 E = Record->bases_end(); I != E; ++I) {
1020 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1021 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1022 if (!BaseRT) return false;
1023
1024 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +00001025 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1026 return false;
1027 }
1028
1029 return true;
1030}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001031
John McCall2d74de92009-12-01 22:10:20 +00001032enum IMAKind {
1033 /// The reference is definitely not an instance member access.
1034 IMA_Static,
1035
1036 /// The reference may be an implicit instance member access.
1037 IMA_Mixed,
1038
1039 /// The reference may be to an instance member, but it is invalid if
1040 /// so, because the context is not an instance method.
1041 IMA_Mixed_StaticContext,
1042
1043 /// The reference may be to an instance member, but it is invalid if
1044 /// so, because the context is from an unrelated class.
1045 IMA_Mixed_Unrelated,
1046
1047 /// The reference is definitely an implicit instance member access.
1048 IMA_Instance,
1049
1050 /// The reference may be to an unresolved using declaration.
1051 IMA_Unresolved,
1052
1053 /// The reference may be to an unresolved using declaration and the
1054 /// context is not an instance method.
1055 IMA_Unresolved_StaticContext,
1056
John McCall2d74de92009-12-01 22:10:20 +00001057 /// All possible referrents are instance members and the current
1058 /// context is not an instance method.
1059 IMA_Error_StaticContext,
1060
1061 /// All possible referrents are instance members of an unrelated
1062 /// class.
1063 IMA_Error_Unrelated
1064};
1065
1066/// The given lookup names class member(s) and is not being used for
1067/// an address-of-member expression. Classify the type of access
1068/// according to whether it's possible that this reference names an
1069/// instance member. This is best-effort; it is okay to
1070/// conservatively answer "yes", in which case some errors will simply
1071/// not be caught until template-instantiation.
1072static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1073 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +00001074 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +00001075
John McCall87fe5d52010-05-20 01:18:31 +00001076 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCall2d74de92009-12-01 22:10:20 +00001077 bool isStaticContext =
John McCall87fe5d52010-05-20 01:18:31 +00001078 (!isa<CXXMethodDecl>(DC) ||
1079 cast<CXXMethodDecl>(DC)->isStatic());
John McCall2d74de92009-12-01 22:10:20 +00001080
1081 if (R.isUnresolvableResult())
1082 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1083
1084 // Collect all the declaring classes of instance members we find.
1085 bool hasNonInstance = false;
Sebastian Redl34620312010-11-26 16:28:07 +00001086 bool hasField = false;
John McCall2d74de92009-12-01 22:10:20 +00001087 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1088 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCalla8ae2222010-04-06 21:38:20 +00001089 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00001090
John McCalla8ae2222010-04-06 21:38:20 +00001091 if (D->isCXXInstanceMember()) {
Sebastian Redl34620312010-11-26 16:28:07 +00001092 if (dyn_cast<FieldDecl>(D))
1093 hasField = true;
1094
John McCall2d74de92009-12-01 22:10:20 +00001095 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCall2d74de92009-12-01 22:10:20 +00001096 Classes.insert(R->getCanonicalDecl());
1097 }
1098 else
1099 hasNonInstance = true;
1100 }
1101
1102 // If we didn't find any instance members, it can't be an implicit
1103 // member reference.
1104 if (Classes.empty())
1105 return IMA_Static;
1106
1107 // If the current context is not an instance method, it can't be
1108 // an implicit member reference.
Sebastian Redl34620312010-11-26 16:28:07 +00001109 if (isStaticContext) {
1110 if (hasNonInstance)
1111 return IMA_Mixed_StaticContext;
1112
1113 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1114 // C++0x [expr.prim.general]p10:
1115 // An id-expression that denotes a non-static data member or non-static
1116 // member function of a class can only be used:
1117 // (...)
1118 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1119 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1120 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1121 if (isUnevaluatedExpression)
1122 return IMA_Mixed_StaticContext;
1123 }
1124
1125 return IMA_Error_StaticContext;
1126 }
John McCall2d74de92009-12-01 22:10:20 +00001127
1128 // If we can prove that the current context is unrelated to all the
1129 // declaring classes, it can't be an implicit member reference (in
1130 // which case it's an error if any of those members are selected).
1131 if (IsProvablyNotDerivedFrom(SemaRef,
John McCall87fe5d52010-05-20 01:18:31 +00001132 cast<CXXMethodDecl>(DC)->getParent(),
John McCall2d74de92009-12-01 22:10:20 +00001133 Classes))
1134 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1135
1136 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1137}
1138
1139/// Diagnose a reference to a field with no object available.
1140static void DiagnoseInstanceReference(Sema &SemaRef,
1141 const CXXScopeSpec &SS,
1142 const LookupResult &R) {
1143 SourceLocation Loc = R.getNameLoc();
1144 SourceRange Range(Loc);
1145 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1146
1147 if (R.getAsSingle<FieldDecl>()) {
1148 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1149 if (MD->isStatic()) {
1150 // "invalid use of member 'x' in static member function"
1151 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
1152 << Range << R.getLookupName();
1153 return;
1154 }
1155 }
1156
1157 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
1158 << R.getLookupName() << Range;
1159 return;
1160 }
1161
1162 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +00001163}
1164
John McCalld681c392009-12-16 08:11:27 +00001165/// Diagnose an empty lookup.
1166///
1167/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001168bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1169 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +00001170 DeclarationName Name = R.getLookupName();
1171
John McCalld681c392009-12-16 08:11:27 +00001172 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001173 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001174 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1175 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001176 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001177 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001178 diagnostic_suggest = diag::err_undeclared_use_suggest;
1179 }
John McCalld681c392009-12-16 08:11:27 +00001180
Douglas Gregor598b08f2009-12-31 05:20:13 +00001181 // If the original lookup was an unqualified lookup, fake an
1182 // unqualified lookup. This is useful when (for example) the
1183 // original lookup would not have found something because it was a
1184 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001185 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001186 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001187 if (isa<CXXRecordDecl>(DC)) {
1188 LookupQualifiedName(R, DC);
1189
1190 if (!R.empty()) {
1191 // Don't give errors about ambiguities in this lookup.
1192 R.suppressDiagnostics();
1193
1194 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1195 bool isInstance = CurMethod &&
1196 CurMethod->isInstance() &&
1197 DC == CurMethod->getParent();
1198
1199 // Give a code modification hint to insert 'this->'.
1200 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1201 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001202 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001203 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1204 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001205 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001206 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001207 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001208 Diag(R.getNameLoc(), diagnostic) << Name
1209 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1210 QualType DepThisType = DepMethod->getThisType(Context);
1211 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1212 R.getNameLoc(), DepThisType, false);
1213 TemplateArgumentListInfo TList;
1214 if (ULE->hasExplicitTemplateArgs())
1215 ULE->copyTemplateArgumentsInto(TList);
1216 CXXDependentScopeMemberExpr *DepExpr =
1217 CXXDependentScopeMemberExpr::Create(
1218 Context, DepThis, DepThisType, true, SourceLocation(),
1219 ULE->getQualifier(), ULE->getQualifierRange(), NULL,
1220 R.getLookupNameInfo(), &TList);
1221 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001222 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001223 // FIXME: we should be able to handle this case too. It is correct
1224 // to add this-> here. This is a workaround for PR7947.
1225 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001226 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001227 } else {
John McCalld681c392009-12-16 08:11:27 +00001228 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001229 }
John McCalld681c392009-12-16 08:11:27 +00001230
1231 // Do we really want to note all of these?
1232 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1233 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1234
1235 // Tell the callee to try to recover.
1236 return false;
1237 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001238
1239 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001240 }
1241 }
1242
Douglas Gregor598b08f2009-12-31 05:20:13 +00001243 // We didn't find anything, so try to correct for a typo.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001244 DeclarationName Corrected;
Daniel Dunbarf7ced252010-06-02 15:46:52 +00001245 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001246 if (!R.empty()) {
1247 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1248 if (SS.isEmpty())
1249 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1250 << FixItHint::CreateReplacement(R.getNameLoc(),
1251 R.getLookupName().getAsString());
1252 else
1253 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1254 << Name << computeDeclContext(SS, false) << R.getLookupName()
1255 << SS.getRange()
1256 << FixItHint::CreateReplacement(R.getNameLoc(),
1257 R.getLookupName().getAsString());
1258 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1259 Diag(ND->getLocation(), diag::note_previous_decl)
1260 << ND->getDeclName();
1261
1262 // Tell the callee to try to recover.
1263 return false;
1264 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001265
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001266 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1267 // FIXME: If we ended up with a typo for a type name or
1268 // Objective-C class name, we're in trouble because the parser
1269 // is in the wrong place to recover. Suggest the typo
1270 // correction, but don't make it a fix-it since we're not going
1271 // to recover well anyway.
1272 if (SS.isEmpty())
1273 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1274 else
1275 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1276 << Name << computeDeclContext(SS, false) << R.getLookupName()
1277 << SS.getRange();
1278
1279 // Don't try to recover; it won't work.
1280 return true;
1281 }
1282 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001283 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001284 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001285 if (SS.isEmpty())
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001286 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001287 else
Douglas Gregor25363982010-01-01 00:15:04 +00001288 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001289 << Name << computeDeclContext(SS, false) << Corrected
1290 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001291 return true;
1292 }
Douglas Gregor25363982010-01-01 00:15:04 +00001293 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001294 }
1295
1296 // Emit a special diagnostic for failed member lookups.
1297 // FIXME: computing the declaration context might fail here (?)
1298 if (!SS.isEmpty()) {
1299 Diag(R.getNameLoc(), diag::err_no_member)
1300 << Name << computeDeclContext(SS, false)
1301 << SS.getRange();
1302 return true;
1303 }
1304
John McCalld681c392009-12-16 08:11:27 +00001305 // Give up, we can't recover.
1306 Diag(R.getNameLoc(), diagnostic) << Name;
1307 return true;
1308}
1309
Douglas Gregor05fcf842010-11-02 20:36:02 +00001310ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1311 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001312 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1313 if (!IDecl)
1314 return 0;
1315 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1316 if (!ClassImpDecl)
1317 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001318 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001319 if (!property)
1320 return 0;
1321 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001322 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1323 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001324 return 0;
1325 return property;
1326}
1327
Douglas Gregor05fcf842010-11-02 20:36:02 +00001328bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1329 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1330 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1331 if (!IDecl)
1332 return false;
1333 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1334 if (!ClassImpDecl)
1335 return false;
1336 if (ObjCPropertyImplDecl *PIDecl
1337 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1338 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1339 PIDecl->getPropertyIvarDecl())
1340 return false;
1341
1342 return true;
1343}
1344
Fariborz Jahanian18722982010-07-17 00:59:30 +00001345static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001346 LookupResult &Lookup,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001347 IdentifierInfo *II,
1348 SourceLocation NameLoc) {
1349 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001350 bool LookForIvars;
1351 if (Lookup.empty())
1352 LookForIvars = true;
1353 else if (CurMeth->isClassMethod())
1354 LookForIvars = false;
1355 else
1356 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001357 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1358 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001359 if (!LookForIvars)
1360 return 0;
1361
Fariborz Jahanian18722982010-07-17 00:59:30 +00001362 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1363 if (!IDecl)
1364 return 0;
1365 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001366 if (!ClassImpDecl)
1367 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001368 bool DynamicImplSeen = false;
1369 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1370 if (!property)
1371 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001372 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001373 DynamicImplSeen =
1374 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001375 // property implementation has a designated ivar. No need to assume a new
1376 // one.
1377 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1378 return 0;
1379 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001380 if (!DynamicImplSeen) {
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001381 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1382 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001383 NameLoc,
1384 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001385 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001386 (Expr *)0, true);
1387 ClassImpDecl->addDecl(Ivar);
1388 IDecl->makeDeclVisibleInContext(Ivar, false);
1389 property->setPropertyIvarDecl(Ivar);
1390 return Ivar;
1391 }
1392 return 0;
1393}
1394
John McCalldadc5752010-08-24 06:29:42 +00001395ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001396 CXXScopeSpec &SS,
1397 UnqualifiedId &Id,
1398 bool HasTrailingLParen,
1399 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001400 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1401 "cannot be direct & operand and have a trailing lparen");
1402
1403 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001404 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001405
John McCall10eae182009-11-30 22:42:35 +00001406 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001407
1408 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001409 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001410 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001411 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001412
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001413 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001414 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001415 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001416
John McCalle66edc12009-11-24 19:00:30 +00001417 // C++ [temp.dep.expr]p3:
1418 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001419 // -- an identifier that was declared with a dependent type,
1420 // (note: handled after lookup)
1421 // -- a template-id that is dependent,
1422 // (note: handled in BuildTemplateIdExpr)
1423 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001424 // -- a nested-name-specifier that contains a class-name that
1425 // names a dependent type.
1426 // Determine whether this is a member of an unknown specialization;
1427 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001428 bool DependentID = false;
1429 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1430 Name.getCXXNameType()->isDependentType()) {
1431 DependentID = true;
1432 } else if (SS.isSet()) {
1433 DeclContext *DC = computeDeclContext(SS, false);
1434 if (DC) {
1435 if (RequireCompleteDeclContext(SS, DC))
1436 return ExprError();
1437 // FIXME: We should be checking whether DC is the current instantiation.
1438 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
1439 DependentID = !IsFullyFormedScope(*this, RD);
1440 } else {
1441 DependentID = true;
1442 }
1443 }
1444
1445 if (DependentID) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001446 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001447 TemplateArgs);
1448 }
Fariborz Jahanian86151342010-07-22 23:33:21 +00001449 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001450 // Perform the required lookup.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001451 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001452 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001453 // Lookup the template name again to correctly establish the context in
1454 // which it was found. This is really unfortunate as we already did the
1455 // lookup to determine that it was a template name in the first place. If
1456 // this becomes a performance hit, we can work harder to preserve those
1457 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001458 bool MemberOfUnknownSpecialization;
1459 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1460 MemberOfUnknownSpecialization);
John McCalle66edc12009-11-24 19:00:30 +00001461 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001462 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001463 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001464
John McCalle66edc12009-11-24 19:00:30 +00001465 // If this reference is in an Objective-C method, then we need to do
1466 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001467 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001468 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001469 if (E.isInvalid())
1470 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001471
John McCalle66edc12009-11-24 19:00:30 +00001472 Expr *Ex = E.takeAs<Expr>();
1473 if (Ex) return Owned(Ex);
Fariborz Jahanian18722982010-07-17 00:59:30 +00001474 // Synthesize ivars lazily
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001475 if (getLangOptions().ObjCDefaultSynthProperties &&
1476 getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001477 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1478 if (const ObjCPropertyDecl *Property =
1479 canSynthesizeProvisionalIvar(II)) {
1480 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1481 Diag(Property->getLocation(), diag::note_property_declare);
1482 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001483 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1484 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001485 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001486 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001487 // for further use, this must be set to false if in class method.
1488 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001489 }
Chris Lattner59a25942008-03-31 00:36:02 +00001490 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001491
John McCalle66edc12009-11-24 19:00:30 +00001492 if (R.isAmbiguous())
1493 return ExprError();
1494
Douglas Gregor171c45a2009-02-18 21:56:37 +00001495 // Determine whether this name might be a candidate for
1496 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001497 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001498
John McCalle66edc12009-11-24 19:00:30 +00001499 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001500 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001501 // in C90, extension in C99, forbidden in C++).
1502 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1503 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1504 if (D) R.addDecl(D);
1505 }
1506
1507 // If this name wasn't predeclared and if this is not a function
1508 // call, diagnose the problem.
1509 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001510 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001511 return ExprError();
1512
1513 assert(!R.empty() &&
1514 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001515
1516 // If we found an Objective-C instance variable, let
1517 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001518 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001519 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1520 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001521 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001522 assert(E.isInvalid() || E.get());
1523 return move(E);
1524 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001525 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001526 }
Mike Stump11289f42009-09-09 15:08:12 +00001527
John McCalle66edc12009-11-24 19:00:30 +00001528 // This is guaranteed from this point on.
1529 assert(!R.empty() || ADL);
1530
1531 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001532 if (getLangOptions().ObjCNonFragileABI && IvarLookupFollowUp &&
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001533 !(getLangOptions().ObjCDefaultSynthProperties &&
1534 getLangOptions().ObjCNonFragileABI2) &&
Fariborz Jahanianc15dfd82010-07-29 16:53:53 +00001535 Var->isFileVarDecl()) {
Douglas Gregor05fcf842010-11-02 20:36:02 +00001536 ObjCPropertyDecl *Property = canSynthesizeProvisionalIvar(II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001537 if (Property) {
1538 Diag(NameLoc, diag::warn_ivar_variable_conflict) << Var->getDeclName();
1539 Diag(Property->getLocation(), diag::note_property_declare);
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001540 Diag(Var->getLocation(), diag::note_global_declared_at);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001541 }
1542 }
John McCalle66edc12009-11-24 19:00:30 +00001543 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001544 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1545 // C99 DR 316 says that, if a function type comes from a
1546 // function definition (without a prototype), that type is only
1547 // used for checking compatibility. Therefore, when referencing
1548 // the function, we pretend that we don't have the full function
1549 // type.
John McCalle66edc12009-11-24 19:00:30 +00001550 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor3256d042009-06-30 15:47:41 +00001551 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001552
Douglas Gregor3256d042009-06-30 15:47:41 +00001553 QualType T = Func->getType();
1554 QualType NoProtoType = T;
John McCall9dd450b2009-09-21 23:43:11 +00001555 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Eli Friedmanb41ad0f2010-05-17 02:50:18 +00001556 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType(),
1557 Proto->getExtInfo());
John McCall7decc9e2010-11-18 06:31:45 +00001558 // Note that functions are r-values in C.
1559 return BuildDeclRefExpr(Func, NoProtoType, VK_RValue, NameLoc, &SS);
Douglas Gregor3256d042009-06-30 15:47:41 +00001560 }
1561 }
Mike Stump11289f42009-09-09 15:08:12 +00001562
John McCall2d74de92009-12-01 22:10:20 +00001563 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001564 // C++ [class.mfct.non-static]p3:
1565 // When an id-expression that is not part of a class member access
1566 // syntax and not used to form a pointer to member is used in the
1567 // body of a non-static member function of class X, if name lookup
1568 // resolves the name in the id-expression to a non-static non-type
1569 // member of some class C, the id-expression is transformed into a
1570 // class member access expression using (*this) as the
1571 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001572 //
1573 // But we don't actually need to do this for '&' operands if R
1574 // resolved to a function or overloaded function set, because the
1575 // expression is ill-formed if it actually works out to be a
1576 // non-static member function:
1577 //
1578 // C++ [expr.ref]p4:
1579 // Otherwise, if E1.E2 refers to a non-static member function. . .
1580 // [t]he expression can be used only as the left-hand operand of a
1581 // member function call.
1582 //
1583 // There are other safeguards against such uses, but it's important
1584 // to get this right here so that we don't end up making a
1585 // spuriously dependent expression if we're inside a dependent
1586 // instance method.
John McCall57500772009-12-16 12:17:52 +00001587 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001588 bool MightBeImplicitMember;
1589 if (!isAddressOfOperand)
1590 MightBeImplicitMember = true;
1591 else if (!SS.isEmpty())
1592 MightBeImplicitMember = false;
1593 else if (R.isOverloadedResult())
1594 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001595 else if (R.isUnresolvableResult())
1596 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001597 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001598 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1599 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001600
1601 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001602 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001603 }
1604
John McCalle66edc12009-11-24 19:00:30 +00001605 if (TemplateArgs)
1606 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001607
John McCalle66edc12009-11-24 19:00:30 +00001608 return BuildDeclarationNameExpr(SS, R, ADL);
1609}
1610
John McCall57500772009-12-16 12:17:52 +00001611/// Builds an expression which might be an implicit member expression.
John McCalldadc5752010-08-24 06:29:42 +00001612ExprResult
John McCall57500772009-12-16 12:17:52 +00001613Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1614 LookupResult &R,
1615 const TemplateArgumentListInfo *TemplateArgs) {
1616 switch (ClassifyImplicitMemberAccess(*this, R)) {
1617 case IMA_Instance:
1618 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1619
John McCall57500772009-12-16 12:17:52 +00001620 case IMA_Mixed:
1621 case IMA_Mixed_Unrelated:
1622 case IMA_Unresolved:
1623 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1624
1625 case IMA_Static:
1626 case IMA_Mixed_StaticContext:
1627 case IMA_Unresolved_StaticContext:
1628 if (TemplateArgs)
1629 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1630 return BuildDeclarationNameExpr(SS, R, false);
1631
1632 case IMA_Error_StaticContext:
1633 case IMA_Error_Unrelated:
1634 DiagnoseInstanceReference(*this, SS, R);
1635 return ExprError();
1636 }
1637
1638 llvm_unreachable("unexpected instance member access kind");
1639 return ExprError();
1640}
1641
John McCall10eae182009-11-30 22:42:35 +00001642/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1643/// declaration name, generally during template instantiation.
1644/// There's a large number of things which don't need to be done along
1645/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001646ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001647Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001648 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001649 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001650 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001651 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001652
John McCall0b66eb32010-05-01 00:40:08 +00001653 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001654 return ExprError();
1655
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001656 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001657 LookupQualifiedName(R, DC);
1658
1659 if (R.isAmbiguous())
1660 return ExprError();
1661
1662 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001663 Diag(NameInfo.getLoc(), diag::err_no_member)
1664 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001665 return ExprError();
1666 }
1667
1668 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1669}
1670
1671/// LookupInObjCMethod - The parser has read a name in, and Sema has
1672/// detected that we're currently inside an ObjC method. Perform some
1673/// additional lookup.
1674///
1675/// Ideally, most of this would be done by lookup, but there's
1676/// actually quite a lot of extra work involved.
1677///
1678/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001679ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001680Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001681 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001682 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001683 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001684
John McCalle66edc12009-11-24 19:00:30 +00001685 // There are two cases to handle here. 1) scoped lookup could have failed,
1686 // in which case we should look for an ivar. 2) scoped lookup could have
1687 // found a decl, but that decl is outside the current instance method (i.e.
1688 // a global variable). In these two cases, we do a lookup for an ivar with
1689 // this name, if the lookup sucedes, we replace it our current decl.
1690
1691 // If we're in a class method, we don't normally want to look for
1692 // ivars. But if we don't find anything else, and there's an
1693 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001694 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001695
1696 bool LookForIvars;
1697 if (Lookup.empty())
1698 LookForIvars = true;
1699 else if (IsClassMethod)
1700 LookForIvars = false;
1701 else
1702 LookForIvars = (Lookup.isSingleResult() &&
1703 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001704 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001705 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001706 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001707 ObjCInterfaceDecl *ClassDeclared;
1708 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1709 // Diagnose using an ivar in a class method.
1710 if (IsClassMethod)
1711 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1712 << IV->getDeclName());
1713
1714 // If we're referencing an invalid decl, just return this as a silent
1715 // error node. The error diagnostic was already emitted on the decl.
1716 if (IV->isInvalidDecl())
1717 return ExprError();
1718
1719 // Check if referencing a field with __attribute__((deprecated)).
1720 if (DiagnoseUseOfDecl(IV, Loc))
1721 return ExprError();
1722
1723 // Diagnose the use of an ivar outside of the declaring class.
1724 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1725 ClassDeclared != IFace)
1726 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1727
1728 // FIXME: This should use a new expr for a direct reference, don't
1729 // turn this into Self->ivar, just return a BareIVarExpr or something.
1730 IdentifierInfo &II = Context.Idents.get("self");
1731 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001732 SelfName.setIdentifier(&II, SourceLocation());
John McCalle66edc12009-11-24 19:00:30 +00001733 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001734 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001735 SelfName, false, false);
1736 if (SelfExpr.isInvalid())
1737 return ExprError();
1738
John McCall27584242010-12-06 20:48:59 +00001739 Expr *SelfE = SelfExpr.take();
1740 DefaultLvalueConversion(SelfE);
1741
John McCalle66edc12009-11-24 19:00:30 +00001742 MarkDeclarationReferenced(Loc, IV);
1743 return Owned(new (Context)
1744 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John McCall27584242010-12-06 20:48:59 +00001745 SelfE, true, true));
John McCalle66edc12009-11-24 19:00:30 +00001746 }
Chris Lattner87313662010-04-12 05:10:17 +00001747 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001748 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001749 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001750 ObjCInterfaceDecl *ClassDeclared;
1751 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1752 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1753 IFace == ClassDeclared)
1754 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1755 }
1756 }
1757
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001758 if (Lookup.empty() && II && AllowBuiltinCreation) {
1759 // FIXME. Consolidate this with similar code in LookupName.
1760 if (unsigned BuiltinID = II->getBuiltinID()) {
1761 if (!(getLangOptions().CPlusPlus &&
1762 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1763 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1764 S, Lookup.isForRedeclaration(),
1765 Lookup.getNameLoc());
1766 if (D) Lookup.addDecl(D);
1767 }
1768 }
1769 }
John McCalle66edc12009-11-24 19:00:30 +00001770 // Sentinel value saying that we didn't do anything special.
1771 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001772}
John McCalld14a8642009-11-21 08:51:07 +00001773
John McCall16df1e52010-03-30 21:47:33 +00001774/// \brief Cast a base object to a member's actual type.
1775///
1776/// Logically this happens in three phases:
1777///
1778/// * First we cast from the base type to the naming class.
1779/// The naming class is the class into which we were looking
1780/// when we found the member; it's the qualifier type if a
1781/// qualifier was provided, and otherwise it's the base type.
1782///
1783/// * Next we cast from the naming class to the declaring class.
1784/// If the member we found was brought into a class's scope by
1785/// a using declaration, this is that class; otherwise it's
1786/// the class declaring the member.
1787///
1788/// * Finally we cast from the declaring class to the "true"
1789/// declaring class of the member. This conversion does not
1790/// obey access control.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001791bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001792Sema::PerformObjectMemberConversion(Expr *&From,
1793 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001794 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001795 NamedDecl *Member) {
1796 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1797 if (!RD)
1798 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001799
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001800 QualType DestRecordType;
1801 QualType DestType;
1802 QualType FromRecordType;
1803 QualType FromType = From->getType();
1804 bool PointerConversions = false;
1805 if (isa<FieldDecl>(Member)) {
1806 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001807
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001808 if (FromType->getAs<PointerType>()) {
1809 DestType = Context.getPointerType(DestRecordType);
1810 FromRecordType = FromType->getPointeeType();
1811 PointerConversions = true;
1812 } else {
1813 DestType = DestRecordType;
1814 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001815 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001816 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1817 if (Method->isStatic())
1818 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001819
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001820 DestType = Method->getThisType(Context);
1821 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001822
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001823 if (FromType->getAs<PointerType>()) {
1824 FromRecordType = FromType->getPointeeType();
1825 PointerConversions = true;
1826 } else {
1827 FromRecordType = FromType;
1828 DestType = DestRecordType;
1829 }
1830 } else {
1831 // No conversion necessary.
1832 return false;
1833 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001834
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001835 if (DestType->isDependentType() || FromType->isDependentType())
1836 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001837
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001838 // If the unqualified types are the same, no conversion is necessary.
1839 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1840 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001841
John McCall16df1e52010-03-30 21:47:33 +00001842 SourceRange FromRange = From->getSourceRange();
1843 SourceLocation FromLoc = FromRange.getBegin();
1844
John McCall2536c6d2010-08-25 10:28:54 +00001845 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001846
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001847 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001848 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001849 // class name.
1850 //
1851 // If the member was a qualified name and the qualified referred to a
1852 // specific base subobject type, we'll cast to that intermediate type
1853 // first and then to the object in which the member is declared. That allows
1854 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1855 //
1856 // class Base { public: int x; };
1857 // class Derived1 : public Base { };
1858 // class Derived2 : public Base { };
1859 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1860 //
1861 // void VeryDerived::f() {
1862 // x = 17; // error: ambiguous base subobjects
1863 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1864 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001865 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00001866 QualType QType = QualType(Qualifier->getAsType(), 0);
1867 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1868 assert(QType->isRecordType() && "lookup done with non-record type");
1869
1870 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1871
1872 // In C++98, the qualifier type doesn't actually have to be a base
1873 // type of the object type, in which case we just ignore it.
1874 // Otherwise build the appropriate casts.
1875 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00001876 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001877 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001878 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00001879 return true;
1880
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001881 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00001882 QType = Context.getPointerType(QType);
John McCall2536c6d2010-08-25 10:28:54 +00001883 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
1884 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00001885
1886 FromType = QType;
1887 FromRecordType = QRecordType;
1888
1889 // If the qualifier type was the same as the destination type,
1890 // we're done.
1891 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1892 return false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001893 }
1894 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001895
John McCall16df1e52010-03-30 21:47:33 +00001896 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001897
John McCall16df1e52010-03-30 21:47:33 +00001898 // If we actually found the member through a using declaration, cast
1899 // down to the using declaration's type.
1900 //
1901 // Pointer equality is fine here because only one declaration of a
1902 // class ever has member declarations.
1903 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
1904 assert(isa<UsingShadowDecl>(FoundDecl));
1905 QualType URecordType = Context.getTypeDeclType(
1906 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
1907
1908 // We only need to do this if the naming-class to declaring-class
1909 // conversion is non-trivial.
1910 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
1911 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00001912 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001913 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001914 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00001915 return true;
Alexis Huntc46382e2010-04-28 23:02:27 +00001916
John McCall16df1e52010-03-30 21:47:33 +00001917 QualType UType = URecordType;
1918 if (PointerConversions)
1919 UType = Context.getPointerType(UType);
John McCalle3027922010-08-25 11:45:40 +00001920 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001921 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00001922 FromType = UType;
1923 FromRecordType = URecordType;
1924 }
1925
1926 // We don't do access control for the conversion from the
1927 // declaring class to the true declaring class.
1928 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001929 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001930
John McCallcf142162010-08-07 06:22:56 +00001931 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00001932 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
1933 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00001934 IgnoreAccess))
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001935 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001936
John McCalle3027922010-08-25 11:45:40 +00001937 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001938 VK, &BasePath);
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001939 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001940}
Douglas Gregor3256d042009-06-30 15:47:41 +00001941
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001942/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00001943static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00001944 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalla8ae2222010-04-06 21:38:20 +00001945 DeclAccessPair FoundDecl,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001946 const DeclarationNameInfo &MemberNameInfo,
1947 QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +00001948 ExprValueKind VK, ExprObjectKind OK,
John McCalle66edc12009-11-24 19:00:30 +00001949 const TemplateArgumentListInfo *TemplateArgs = 0) {
1950 NestedNameSpecifier *Qualifier = 0;
1951 SourceRange QualifierRange;
John McCall10eae182009-11-30 22:42:35 +00001952 if (SS.isSet()) {
1953 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1954 QualifierRange = SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001955 }
Mike Stump11289f42009-09-09 15:08:12 +00001956
John McCalle66edc12009-11-24 19:00:30 +00001957 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001958 Member, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00001959 TemplateArgs, Ty, VK, OK);
Douglas Gregorc1905232009-08-26 22:36:53 +00001960}
1961
John McCallfeb624a2010-11-23 20:48:44 +00001962static ExprResult
1963BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1964 const CXXScopeSpec &SS, FieldDecl *Field,
1965 DeclAccessPair FoundDecl,
1966 const DeclarationNameInfo &MemberNameInfo) {
1967 // x.a is an l-value if 'a' has a reference type. Otherwise:
1968 // x.a is an l-value/x-value/pr-value if the base is (and note
1969 // that *x is always an l-value), except that if the base isn't
1970 // an ordinary object then we must have an rvalue.
1971 ExprValueKind VK = VK_LValue;
1972 ExprObjectKind OK = OK_Ordinary;
1973 if (!IsArrow) {
1974 if (BaseExpr->getObjectKind() == OK_Ordinary)
1975 VK = BaseExpr->getValueKind();
1976 else
1977 VK = VK_RValue;
1978 }
1979 if (VK != VK_RValue && Field->isBitField())
1980 OK = OK_BitField;
1981
1982 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1983 QualType MemberType = Field->getType();
1984 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1985 MemberType = Ref->getPointeeType();
1986 VK = VK_LValue;
1987 } else {
1988 QualType BaseType = BaseExpr->getType();
1989 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1990
1991 Qualifiers BaseQuals = BaseType.getQualifiers();
1992
1993 // GC attributes are never picked up by members.
1994 BaseQuals.removeObjCGCAttr();
1995
1996 // CVR attributes from the base are picked up by members,
1997 // except that 'mutable' members don't pick up 'const'.
1998 if (Field->isMutable()) BaseQuals.removeConst();
1999
2000 Qualifiers MemberQuals
2001 = S.Context.getCanonicalType(MemberType).getQualifiers();
2002
2003 // TR 18037 does not allow fields to be declared with address spaces.
2004 assert(!MemberQuals.hasAddressSpace());
2005
2006 Qualifiers Combined = BaseQuals + MemberQuals;
2007 if (Combined != MemberQuals)
2008 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2009 }
2010
2011 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
2012 if (S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2013 FoundDecl, Field))
2014 return ExprError();
2015 return S.Owned(BuildMemberExpr(S.Context, BaseExpr, IsArrow, SS,
2016 Field, FoundDecl, MemberNameInfo,
2017 MemberType, VK, OK));
2018}
2019
John McCall2d74de92009-12-01 22:10:20 +00002020/// Builds an implicit member access expression. The current context
2021/// is known to be an instance method, and the given unqualified lookup
2022/// set is known to contain only instance members, at least one of which
2023/// is from an appropriate type.
John McCalldadc5752010-08-24 06:29:42 +00002024ExprResult
John McCall2d74de92009-12-01 22:10:20 +00002025Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2026 LookupResult &R,
2027 const TemplateArgumentListInfo *TemplateArgs,
2028 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00002029 assert(!R.empty() && !R.isAmbiguous());
2030
John McCalld14a8642009-11-21 08:51:07 +00002031 SourceLocation Loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00002032
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002033 // We may have found a field within an anonymous union or struct
2034 // (C++ [class.union]).
Douglas Gregor6493d9c2009-10-22 07:08:30 +00002035 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCalle66edc12009-11-24 19:00:30 +00002036 // FIXME: template-ids inside anonymous structs?
Francois Pichet783dd6e2010-11-21 06:08:52 +00002037 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
2038 return BuildAnonymousStructUnionMemberReference(Loc, FD);
2039
Sebastian Redlffbcf962009-01-18 18:53:16 +00002040
John McCall2d74de92009-12-01 22:10:20 +00002041 // If this is known to be an instance access, go ahead and build a
2042 // 'this' expression now.
John McCall87fe5d52010-05-20 01:18:31 +00002043 DeclContext *DC = getFunctionLevelDeclContext();
2044 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCall2d74de92009-12-01 22:10:20 +00002045 Expr *This = 0; // null signifies implicit access
2046 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00002047 SourceLocation Loc = R.getNameLoc();
2048 if (SS.getRange().isValid())
2049 Loc = SS.getRange().getBegin();
2050 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002051 }
2052
John McCallb268a282010-08-23 23:25:46 +00002053 return BuildMemberReferenceExpr(This, ThisType,
John McCall2d74de92009-12-01 22:10:20 +00002054 /*OpLoc*/ SourceLocation(),
2055 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00002056 SS,
2057 /*FirstQualifierInScope*/ 0,
2058 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00002059}
2060
John McCalle66edc12009-11-24 19:00:30 +00002061bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002062 const LookupResult &R,
2063 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002064 // Only when used directly as the postfix-expression of a call.
2065 if (!HasTrailingLParen)
2066 return false;
2067
2068 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002069 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002070 return false;
2071
2072 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002073 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002074 return false;
2075
2076 // Turn off ADL when we find certain kinds of declarations during
2077 // normal lookup:
2078 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2079 NamedDecl *D = *I;
2080
2081 // C++0x [basic.lookup.argdep]p3:
2082 // -- a declaration of a class member
2083 // Since using decls preserve this property, we check this on the
2084 // original decl.
John McCall57500772009-12-16 12:17:52 +00002085 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002086 return false;
2087
2088 // C++0x [basic.lookup.argdep]p3:
2089 // -- a block-scope function declaration that is not a
2090 // using-declaration
2091 // NOTE: we also trigger this for function templates (in fact, we
2092 // don't check the decl type at all, since all other decl types
2093 // turn off ADL anyway).
2094 if (isa<UsingShadowDecl>(D))
2095 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2096 else if (D->getDeclContext()->isFunctionOrMethod())
2097 return false;
2098
2099 // C++0x [basic.lookup.argdep]p3:
2100 // -- a declaration that is neither a function or a function
2101 // template
2102 // And also for builtin functions.
2103 if (isa<FunctionDecl>(D)) {
2104 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2105
2106 // But also builtin functions.
2107 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2108 return false;
2109 } else if (!isa<FunctionTemplateDecl>(D))
2110 return false;
2111 }
2112
2113 return true;
2114}
2115
2116
John McCalld14a8642009-11-21 08:51:07 +00002117/// Diagnoses obvious problems with the use of the given declaration
2118/// as an expression. This is only actually called for lookups that
2119/// were not overloaded, and it doesn't promise that the declaration
2120/// will in fact be used.
2121static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2122 if (isa<TypedefDecl>(D)) {
2123 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2124 return true;
2125 }
2126
2127 if (isa<ObjCInterfaceDecl>(D)) {
2128 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2129 return true;
2130 }
2131
2132 if (isa<NamespaceDecl>(D)) {
2133 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2134 return true;
2135 }
2136
2137 return false;
2138}
2139
John McCalldadc5752010-08-24 06:29:42 +00002140ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002141Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002142 LookupResult &R,
2143 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002144 // If this is a single, fully-resolved result and we don't need ADL,
2145 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002146 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002147 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2148 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002149
2150 // We only need to check the declaration if there's exactly one
2151 // result, because in the overloaded case the results can only be
2152 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002153 if (R.isSingleResult() &&
2154 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002155 return ExprError();
2156
John McCall58cc69d2010-01-27 01:50:18 +00002157 // Otherwise, just build an unresolved lookup expression. Suppress
2158 // any lookup-related diagnostics; we'll hash these out later, when
2159 // we've picked a target.
2160 R.suppressDiagnostics();
2161
John McCalld14a8642009-11-21 08:51:07 +00002162 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002163 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00002164 (NestedNameSpecifier*) SS.getScopeRep(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002165 SS.getRange(), R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002166 NeedsADL, R.isOverloadedResult(),
2167 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002168
2169 return Owned(ULE);
2170}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002171
John McCall7decc9e2010-11-18 06:31:45 +00002172static ExprValueKind getValueKindForDecl(ASTContext &Context,
2173 const ValueDecl *D) {
John McCall4bc41ae2010-11-18 19:01:18 +00002174 // FIXME: It's not clear to me why NonTypeTemplateParmDecl is a VarDecl.
2175 if (isa<VarDecl>(D) && !isa<NonTypeTemplateParmDecl>(D)) return VK_LValue;
2176 if (isa<FieldDecl>(D)) return VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00002177 if (!Context.getLangOptions().CPlusPlus) return VK_RValue;
2178 if (isa<FunctionDecl>(D)) {
2179 if (isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance())
2180 return VK_RValue;
2181 return VK_LValue;
2182 }
2183 return Expr::getValueKindForType(D->getType());
2184}
2185
John McCalld14a8642009-11-21 08:51:07 +00002186
2187/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002188ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002189Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002190 const DeclarationNameInfo &NameInfo,
2191 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002192 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002193 assert(!isa<FunctionTemplateDecl>(D) &&
2194 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002195
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002196 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002197 if (CheckDeclInExpr(*this, Loc, D))
2198 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002199
Douglas Gregore7488b92009-12-01 16:58:18 +00002200 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2201 // Specifically diagnose references to class templates that are missing
2202 // a template argument list.
2203 Diag(Loc, diag::err_template_decl_ref)
2204 << Template << SS.getRange();
2205 Diag(Template->getLocation(), diag::note_template_decl_here);
2206 return ExprError();
2207 }
2208
2209 // Make sure that we're referring to a value.
2210 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2211 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002212 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002213 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002214 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002215 return ExprError();
2216 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002217
Douglas Gregor171c45a2009-02-18 21:56:37 +00002218 // Check whether this declaration can be used. Note that we suppress
2219 // this check when we're going to perform argument-dependent lookup
2220 // on this function name, because this might not be the function
2221 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002222 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002223 return ExprError();
2224
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002225 // Only create DeclRefExpr's for valid Decl's.
2226 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002227 return ExprError();
2228
Francois Pichet783dd6e2010-11-21 06:08:52 +00002229 // Handle anonymous.
2230 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(VD))
2231 return BuildAnonymousStructUnionMemberReference(Loc, FD);
2232
John McCall7decc9e2010-11-18 06:31:45 +00002233 ExprValueKind VK = getValueKindForDecl(Context, VD);
2234
Chris Lattner2a9d9892008-10-20 05:16:36 +00002235 // If the identifier reference is inside a block, and it refers to a value
2236 // that is outside the block, create a BlockDeclRefExpr instead of a
2237 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2238 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002239 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002240 // We do not do this for things like enum constants, global variables, etc,
2241 // as they do not get snapshotted.
2242 //
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002243 if (getCurBlock() &&
Douglas Gregor9a28e842010-03-01 23:15:13 +00002244 ShouldSnapshotBlockValueReference(*this, getCurBlock(), VD)) {
Mike Stump7dafa0d2010-01-05 02:56:35 +00002245 if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
2246 Diag(Loc, diag::err_ref_vm_type);
2247 Diag(D->getLocation(), diag::note_declared_at);
2248 return ExprError();
2249 }
2250
Fariborz Jahanianfa24e102010-03-16 23:39:51 +00002251 if (VD->getType()->isArrayType()) {
Mike Stump8971a862010-01-05 03:10:36 +00002252 Diag(Loc, diag::err_ref_array_type);
2253 Diag(D->getLocation(), diag::note_declared_at);
2254 return ExprError();
2255 }
2256
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00002257 MarkDeclarationReferenced(Loc, VD);
Eli Friedman7fa3faa2009-03-22 23:00:19 +00002258 QualType ExprTy = VD->getType().getNonReferenceType();
John McCall7decc9e2010-11-18 06:31:45 +00002259
Steve Naroff1d95e5a2008-10-10 01:28:17 +00002260 // The BlocksAttr indicates the variable is bound by-reference.
Fariborz Jahaniana3e54bd2010-11-16 19:29:39 +00002261 bool byrefVar = (VD->getAttr<BlocksAttr>() != 0);
Fariborz Jahanian70c0b082010-07-12 17:26:57 +00002262 QualType T = VD->getType();
Fariborz Jahaniana3e54bd2010-11-16 19:29:39 +00002263 BlockDeclRefExpr *BDRE;
2264
2265 if (!byrefVar) {
2266 // This is to record that a 'const' was actually synthesize and added.
2267 bool constAdded = !ExprTy.isConstQualified();
2268 // Variable will be bound by-copy, make it const within the closure.
2269 ExprTy.addConst();
John McCall7decc9e2010-11-18 06:31:45 +00002270 BDRE = new (Context) BlockDeclRefExpr(VD, ExprTy, VK,
2271 Loc, false, constAdded);
Fariborz Jahaniana3e54bd2010-11-16 19:29:39 +00002272 }
2273 else
John McCall7decc9e2010-11-18 06:31:45 +00002274 BDRE = new (Context) BlockDeclRefExpr(VD, ExprTy, VK, Loc, true);
Fariborz Jahaniana3e54bd2010-11-16 19:29:39 +00002275
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00002276 if (getLangOptions().CPlusPlus) {
2277 if (!T->isDependentType() && !T->isReferenceType()) {
2278 Expr *E = new (Context)
2279 DeclRefExpr(const_cast<ValueDecl*>(BDRE->getDecl()), T,
John McCall7decc9e2010-11-18 06:31:45 +00002280 VK, SourceLocation());
Fariborz Jahanian2a5deb52010-11-11 00:11:38 +00002281 if (T->getAs<RecordType>())
2282 if (!T->isUnionType()) {
2283 ExprResult Res = PerformCopyInitialization(
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00002284 InitializedEntity::InitializeBlock(VD->getLocation(),
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002285 T, false),
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00002286 SourceLocation(),
2287 Owned(E));
Fariborz Jahanian2a5deb52010-11-11 00:11:38 +00002288 if (!Res.isInvalid()) {
Douglas Gregora40433a2010-12-07 00:41:46 +00002289 Res = MaybeCreateExprWithCleanups(Res);
Fariborz Jahanian2a5deb52010-11-11 00:11:38 +00002290 Expr *Init = Res.takeAs<Expr>();
2291 BDRE->setCopyConstructorExpr(Init);
2292 }
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00002293 }
Fariborz Jahanianea882cd2010-06-04 21:35:44 +00002294 }
2295 }
2296 return Owned(BDRE);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00002297 }
2298 // If this reference is not in a block or if the referenced variable is
2299 // within the block, create a normal DeclRefExpr.
Douglas Gregor4619e432008-12-05 23:32:09 +00002300
John McCall7decc9e2010-11-18 06:31:45 +00002301 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002302 NameInfo, &SS);
Chris Lattner17ed4872006-11-20 04:58:19 +00002303}
Chris Lattnere168f762006-11-10 05:29:30 +00002304
John McCalldadc5752010-08-24 06:29:42 +00002305ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Sebastian Redlffbcf962009-01-18 18:53:16 +00002306 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002307 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002308
Chris Lattnere168f762006-11-10 05:29:30 +00002309 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002310 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002311 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2312 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2313 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002314 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002315
Chris Lattnera81a0272008-01-12 08:14:25 +00002316 // Pre-defined identifiers are of type char[x], where x is the length of the
2317 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002318
Anders Carlsson2fb08242009-09-08 18:24:21 +00002319 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002320 if (!currentDecl && getCurBlock())
2321 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002322 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002323 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002324 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002325 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002326
Anders Carlsson0b209a82009-09-11 01:22:35 +00002327 QualType ResTy;
2328 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2329 ResTy = Context.DependentTy;
2330 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002331 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002332
Anders Carlsson0b209a82009-09-11 01:22:35 +00002333 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002334 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002335 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2336 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002337 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002338}
2339
John McCalldadc5752010-08-24 06:29:42 +00002340ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002341 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002342 bool Invalid = false;
2343 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2344 if (Invalid)
2345 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002346
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002347 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2348 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00002349 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002350 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002351
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002352 QualType Ty;
2353 if (!getLangOptions().CPlusPlus)
2354 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2355 else if (Literal.isWide())
2356 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002357 else if (Literal.isMultiChar())
2358 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002359 else
2360 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002361
Sebastian Redl20614a72009-01-20 22:23:13 +00002362 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2363 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002364 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002365}
2366
John McCalldadc5752010-08-24 06:29:42 +00002367ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002368 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002369 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2370 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002371 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002372 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002373 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002374 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002375 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002376
Chris Lattner23b7eb62007-06-15 23:05:46 +00002377 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002378 // Add padding so that NumericLiteralParser can overread by one character.
2379 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002380 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002381
Chris Lattner67ca9252007-05-21 01:08:44 +00002382 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002383 bool Invalid = false;
2384 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2385 if (Invalid)
2386 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002387
Mike Stump11289f42009-09-09 15:08:12 +00002388 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002389 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002390 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002391 return ExprError();
2392
Chris Lattner1c20a172007-08-26 03:42:43 +00002393 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002394
Chris Lattner1c20a172007-08-26 03:42:43 +00002395 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002396 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002397 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002398 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002399 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002400 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002401 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002402 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002403
2404 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2405
John McCall53b93a02009-12-24 09:08:04 +00002406 using llvm::APFloat;
2407 APFloat Val(Format);
2408
2409 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002410
2411 // Overflow is always an error, but underflow is only an error if
2412 // we underflowed to zero (APFloat reports denormals as underflow).
2413 if ((result & APFloat::opOverflow) ||
2414 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002415 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002416 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002417 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002418 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002419 APFloat::getLargest(Format).toString(buffer);
2420 } else {
John McCall62abc942010-02-26 23:35:57 +00002421 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002422 APFloat::getSmallest(Format).toString(buffer);
2423 }
2424
2425 Diag(Tok.getLocation(), diagnostic)
2426 << Ty
2427 << llvm::StringRef(buffer.data(), buffer.size());
2428 }
2429
2430 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002431 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002432
Peter Collingbourne0b69e1a2010-12-04 01:50:56 +00002433 if (getLangOptions().SinglePrecisionConstants && Ty == Context.DoubleTy)
2434 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2435
Chris Lattner1c20a172007-08-26 03:42:43 +00002436 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002437 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002438 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002439 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002440
Neil Boothac582c52007-08-29 22:00:19 +00002441 // long long is a C99 feature.
2442 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002443 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002444 Diag(Tok.getLocation(), diag::ext_longlong);
2445
Chris Lattner67ca9252007-05-21 01:08:44 +00002446 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002447 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002448
Chris Lattner67ca9252007-05-21 01:08:44 +00002449 if (Literal.GetIntegerValue(ResultVal)) {
2450 // If this value didn't fit into uintmax_t, warn and force to ull.
2451 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002452 Ty = Context.UnsignedLongLongTy;
2453 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002454 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002455 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002456 // If this value fits into a ULL, try to figure out what else it fits into
2457 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002458
Chris Lattner67ca9252007-05-21 01:08:44 +00002459 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2460 // be an unsigned int.
2461 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2462
2463 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002464 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002465 if (!Literal.isLong && !Literal.isLongLong) {
2466 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002467 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002468
Chris Lattner67ca9252007-05-21 01:08:44 +00002469 // Does it fit in a unsigned int?
2470 if (ResultVal.isIntN(IntSize)) {
2471 // Does it fit in a signed int?
2472 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002473 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002474 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002475 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002476 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002477 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002478 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002479
Chris Lattner67ca9252007-05-21 01:08:44 +00002480 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002481 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002482 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002483
Chris Lattner67ca9252007-05-21 01:08:44 +00002484 // Does it fit in a unsigned long?
2485 if (ResultVal.isIntN(LongSize)) {
2486 // Does it fit in a signed long?
2487 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002488 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002489 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002490 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002491 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002492 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002493 }
2494
Chris Lattner67ca9252007-05-21 01:08:44 +00002495 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002496 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002497 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002498
Chris Lattner67ca9252007-05-21 01:08:44 +00002499 // Does it fit in a unsigned long long?
2500 if (ResultVal.isIntN(LongLongSize)) {
2501 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002502 // To be compatible with MSVC, hex integer literals ending with the
2503 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002504 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2505 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002506 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002507 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002508 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002509 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002510 }
2511 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002512
Chris Lattner67ca9252007-05-21 01:08:44 +00002513 // If we still couldn't decide a type, we probably have something that
2514 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002515 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002516 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002517 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002518 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002519 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002520
Chris Lattner55258cf2008-05-09 05:59:00 +00002521 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002522 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002523 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002524 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002525 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002526
Chris Lattner1c20a172007-08-26 03:42:43 +00002527 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2528 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002529 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002530 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002531
2532 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002533}
2534
John McCalldadc5752010-08-24 06:29:42 +00002535ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002536 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002537 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002538 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002539}
2540
Steve Naroff71b59a92007-06-04 22:22:31 +00002541/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00002542/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002543bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00002544 SourceLocation OpLoc,
John McCall36e7fe32010-10-12 00:20:44 +00002545 SourceRange ExprRange,
Sebastian Redl6f282892008-11-11 17:56:53 +00002546 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002547 if (exprType->isDependentType())
2548 return false;
2549
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002550 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2551 // the result is the size of the referenced type."
2552 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2553 // result shall be the alignment of the referenced type."
2554 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2555 exprType = Ref->getPointeeType();
2556
Steve Naroff043d45d2007-05-15 02:32:35 +00002557 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00002558 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002559 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00002560 if (isSizeof)
2561 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2562 return false;
2563 }
Mike Stump11289f42009-09-09 15:08:12 +00002564
Chris Lattner62975a72009-04-24 00:30:45 +00002565 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00002566 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002567 Diag(OpLoc, diag::ext_sizeof_void_type)
2568 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00002569 return false;
2570 }
Mike Stump11289f42009-09-09 15:08:12 +00002571
Chris Lattner62975a72009-04-24 00:30:45 +00002572 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002573 PDiag(diag::err_sizeof_alignof_incomplete_type)
2574 << int(!isSizeof) << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002575 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002576
Chris Lattner62975a72009-04-24 00:30:45 +00002577 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCall8b07ec22010-05-15 11:32:37 +00002578 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002579 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002580 << exprType << isSizeof << ExprRange;
2581 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00002582 }
Mike Stump11289f42009-09-09 15:08:12 +00002583
Chris Lattner62975a72009-04-24 00:30:45 +00002584 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002585}
2586
John McCall36e7fe32010-10-12 00:20:44 +00002587static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2588 SourceRange ExprRange) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002589 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002590
Mike Stump11289f42009-09-09 15:08:12 +00002591 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002592 if (isa<DeclRefExpr>(E))
2593 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002594
2595 // Cannot know anything else if the expression is dependent.
2596 if (E->isTypeDependent())
2597 return false;
2598
Douglas Gregor71235ec2009-05-02 02:18:30 +00002599 if (E->getBitField()) {
John McCall36e7fe32010-10-12 00:20:44 +00002600 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor71235ec2009-05-02 02:18:30 +00002601 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002602 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002603
2604 // Alignment of a field access is always okay, so long as it isn't a
2605 // bit-field.
2606 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002607 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002608 return false;
2609
John McCall36e7fe32010-10-12 00:20:44 +00002610 return S.CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
Chris Lattner8dff0172009-01-24 20:17:12 +00002611}
2612
Douglas Gregor0950e412009-03-13 21:01:28 +00002613/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002614ExprResult
John McCallbcd03502009-12-07 02:54:59 +00002615Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall4c98fd82009-11-04 07:28:41 +00002616 SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00002617 bool isSizeOf, SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002618 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002619 return ExprError();
2620
John McCallbcd03502009-12-07 02:54:59 +00002621 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002622
Douglas Gregor0950e412009-03-13 21:01:28 +00002623 if (!T->isDependentType() &&
2624 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2625 return ExprError();
2626
2627 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCallbcd03502009-12-07 02:54:59 +00002628 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregor0950e412009-03-13 21:01:28 +00002629 Context.getSizeType(), OpLoc,
2630 R.getEnd()));
2631}
2632
2633/// \brief Build a sizeof or alignof expression given an expression
2634/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002635ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00002636Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00002637 bool isSizeOf, SourceRange R) {
2638 // Verify that the operand is valid.
2639 bool isInvalid = false;
2640 if (E->isTypeDependent()) {
2641 // Delay type-checking for type-dependent expressions.
2642 } else if (!isSizeOf) {
John McCall36e7fe32010-10-12 00:20:44 +00002643 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002644 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00002645 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2646 isInvalid = true;
John McCall36226622010-10-12 02:09:17 +00002647 } else if (E->getType()->isPlaceholderType()) {
2648 ExprResult PE = CheckPlaceholderExpr(E, OpLoc);
2649 if (PE.isInvalid()) return ExprError();
2650 return CreateSizeOfAlignOfExpr(PE.take(), OpLoc, isSizeOf, R);
Douglas Gregor0950e412009-03-13 21:01:28 +00002651 } else {
2652 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2653 }
2654
2655 if (isInvalid)
2656 return ExprError();
2657
2658 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2659 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2660 Context.getSizeType(), OpLoc,
2661 R.getEnd()));
2662}
2663
Sebastian Redl6f282892008-11-11 17:56:53 +00002664/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2665/// the same for @c alignof and @c __alignof
2666/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002667ExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00002668Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2669 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002670 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002671 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002672
Sebastian Redl6f282892008-11-11 17:56:53 +00002673 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002674 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002675 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
John McCallbcd03502009-12-07 02:54:59 +00002676 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002677 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002678
Douglas Gregor0950e412009-03-13 21:01:28 +00002679 Expr *ArgEx = (Expr *)TyOrEx;
John McCalldadc5752010-08-24 06:29:42 +00002680 ExprResult Result
Douglas Gregor0950e412009-03-13 21:01:28 +00002681 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2682
Douglas Gregor0950e412009-03-13 21:01:28 +00002683 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002684}
2685
John McCall4bc41ae2010-11-18 19:01:18 +00002686static QualType CheckRealImagOperand(Sema &S, Expr *&V, SourceLocation Loc,
2687 bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002688 if (V->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002689 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002690
John McCall34376a62010-12-04 03:47:34 +00002691 // _Real and _Imag are only l-values for normal l-values.
2692 if (V->getObjectKind() != OK_Ordinary)
John McCall27584242010-12-06 20:48:59 +00002693 S.DefaultLvalueConversion(V);
John McCall34376a62010-12-04 03:47:34 +00002694
Chris Lattnere267f5d2007-08-26 05:39:26 +00002695 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00002696 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002697 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002698
Chris Lattnere267f5d2007-08-26 05:39:26 +00002699 // Otherwise they pass through real integer and floating point types here.
2700 if (V->getType()->isArithmeticType())
2701 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002702
John McCall36226622010-10-12 02:09:17 +00002703 // Test for placeholders.
John McCall4bc41ae2010-11-18 19:01:18 +00002704 ExprResult PR = S.CheckPlaceholderExpr(V, Loc);
John McCall36226622010-10-12 02:09:17 +00002705 if (PR.isInvalid()) return QualType();
2706 if (PR.take() != V) {
2707 V = PR.take();
John McCall4bc41ae2010-11-18 19:01:18 +00002708 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00002709 }
2710
Chris Lattnere267f5d2007-08-26 05:39:26 +00002711 // Reject anything else.
John McCall4bc41ae2010-11-18 19:01:18 +00002712 S.Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00002713 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002714 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002715}
2716
2717
Chris Lattnere168f762006-11-10 05:29:30 +00002718
John McCalldadc5752010-08-24 06:29:42 +00002719ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002720Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002721 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002722 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002723 switch (Kind) {
2724 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002725 case tok::plusplus: Opc = UO_PostInc; break;
2726 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002727 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002728
John McCallb268a282010-08-23 23:25:46 +00002729 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002730}
2731
John McCall4bc41ae2010-11-18 19:01:18 +00002732/// Expressions of certain arbitrary types are forbidden by C from
2733/// having l-value type. These are:
2734/// - 'void', but not qualified void
2735/// - function types
2736///
2737/// The exact rule here is C99 6.3.2.1:
2738/// An lvalue is an expression with an object type or an incomplete
2739/// type other than void.
2740static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
2741 return ((T->isVoidType() && !T.hasQualifiers()) ||
2742 T->isFunctionType());
2743}
2744
John McCalldadc5752010-08-24 06:29:42 +00002745ExprResult
John McCallb268a282010-08-23 23:25:46 +00002746Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2747 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002748 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002749 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002750 if (Result.isInvalid()) return ExprError();
2751 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002752
John McCallb268a282010-08-23 23:25:46 +00002753 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00002754
Douglas Gregor40412ac2008-11-19 17:17:41 +00002755 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002756 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002757 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002758 Context.DependentTy,
2759 VK_LValue, OK_Ordinary,
2760 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002761 }
2762
Mike Stump11289f42009-09-09 15:08:12 +00002763 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002764 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002765 LHSExp->getType()->isEnumeralType() ||
2766 RHSExp->getType()->isRecordType() ||
2767 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00002768 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00002769 }
2770
John McCallb268a282010-08-23 23:25:46 +00002771 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00002772}
2773
2774
John McCalldadc5752010-08-24 06:29:42 +00002775ExprResult
John McCallb268a282010-08-23 23:25:46 +00002776Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2777 Expr *Idx, SourceLocation RLoc) {
2778 Expr *LHSExp = Base;
2779 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00002780
Chris Lattner36d572b2007-07-16 00:14:47 +00002781 // Perform default conversions.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002782 if (!LHSExp->getType()->getAs<VectorType>())
2783 DefaultFunctionArrayLvalueConversion(LHSExp);
2784 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002785
Chris Lattner36d572b2007-07-16 00:14:47 +00002786 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00002787 ExprValueKind VK = VK_LValue;
2788 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00002789
Steve Naroffc1aadb12007-03-28 21:49:40 +00002790 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00002791 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00002792 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00002793 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00002794 Expr *BaseExpr, *IndexExpr;
2795 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002796 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2797 BaseExpr = LHSExp;
2798 IndexExpr = RHSExp;
2799 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002800 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00002801 BaseExpr = LHSExp;
2802 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002803 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002804 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00002805 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00002806 BaseExpr = RHSExp;
2807 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002808 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002809 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002810 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002811 BaseExpr = LHSExp;
2812 IndexExpr = RHSExp;
2813 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002814 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002815 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002816 // Handle the uncommon case of "123[Ptr]".
2817 BaseExpr = RHSExp;
2818 IndexExpr = LHSExp;
2819 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00002820 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00002821 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00002822 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00002823 VK = LHSExp->getValueKind();
2824 if (VK != VK_RValue)
2825 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00002826
Chris Lattner36d572b2007-07-16 00:14:47 +00002827 // FIXME: need to deal with const...
2828 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002829 } else if (LHSTy->isArrayType()) {
2830 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00002831 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00002832 // wasn't promoted because of the C90 rule that doesn't
2833 // allow promoting non-lvalue arrays. Warn, then
2834 // force the promotion here.
2835 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2836 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002837 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
John McCalle3027922010-08-25 11:45:40 +00002838 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002839 LHSTy = LHSExp->getType();
2840
2841 BaseExpr = LHSExp;
2842 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002843 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002844 } else if (RHSTy->isArrayType()) {
2845 // Same as previous, except for 123[f().a] case
2846 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2847 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002848 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
John McCalle3027922010-08-25 11:45:40 +00002849 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002850 RHSTy = RHSExp->getType();
2851
2852 BaseExpr = RHSExp;
2853 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002854 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00002855 } else {
Chris Lattner003af242009-04-25 22:50:55 +00002856 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2857 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002858 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00002859 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00002860 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00002861 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2862 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00002863
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002864 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00002865 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2866 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00002867 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2868
Douglas Gregorac1fb652009-03-24 19:52:54 +00002869 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00002870 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2871 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00002872 // incomplete types are not object types.
2873 if (ResultType->isFunctionType()) {
2874 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2875 << ResultType << BaseExpr->getSourceRange();
2876 return ExprError();
2877 }
Mike Stump11289f42009-09-09 15:08:12 +00002878
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00002879 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
2880 // GNU extension: subscripting on pointer to void
2881 Diag(LLoc, diag::ext_gnu_void_ptr)
2882 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00002883
2884 // C forbids expressions of unqualified void type from being l-values.
2885 // See IsCForbiddenLValueType.
2886 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00002887 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00002888 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00002889 PDiag(diag::err_subscript_incomplete_type)
2890 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00002891 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002892
Chris Lattner62975a72009-04-24 00:30:45 +00002893 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00002894 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00002895 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2896 << ResultType << BaseExpr->getSourceRange();
2897 return ExprError();
2898 }
Mike Stump11289f42009-09-09 15:08:12 +00002899
John McCall4bc41ae2010-11-18 19:01:18 +00002900 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
2901 !IsCForbiddenLValueType(Context, ResultType));
2902
Mike Stump4e1f26a2009-02-19 03:04:26 +00002903 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002904 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00002905}
2906
John McCall4bc41ae2010-11-18 19:01:18 +00002907/// Check an ext-vector component access expression.
2908///
2909/// VK should be set in advance to the value kind of the base
2910/// expression.
2911static QualType
2912CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
2913 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00002914 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00002915 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2916 // see FIXME there.
2917 //
2918 // FIXME: This logic can be greatly simplified by splitting it along
2919 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00002920 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00002921
Steve Narofff8fd09e2007-07-27 22:15:19 +00002922 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002923 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002924
Mike Stump4e1f26a2009-02-19 03:04:26 +00002925 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00002926 // special names that indicate a subset of exactly half the elements are
2927 // to be selected.
2928 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00002929
Nate Begemanbb70bf62009-01-18 01:47:54 +00002930 // This flag determines whether or not CompName has an 's' char prefix,
2931 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00002932 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00002933
John McCall4bc41ae2010-11-18 19:01:18 +00002934 bool HasRepeated = false;
2935 bool HasIndex[16] = {};
2936
2937 int Idx;
2938
Nate Begemanf322eab2008-05-09 06:41:27 +00002939 // Check that we've found one of the special components, or that the component
2940 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002941 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00002942 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2943 HalvingSwizzle = true;
John McCall4bc41ae2010-11-18 19:01:18 +00002944 } else if (!HexSwizzle &&
2945 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
2946 do {
2947 if (HasIndex[Idx]) HasRepeated = true;
2948 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00002949 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00002950 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
2951 } else {
2952 if (HexSwizzle) compStr++;
2953 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
2954 if (HasIndex[Idx]) HasRepeated = true;
2955 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00002956 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00002957 }
Chris Lattner7e152db2007-08-02 22:33:49 +00002958 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00002959
Mike Stump4e1f26a2009-02-19 03:04:26 +00002960 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00002961 // We didn't get to the end of the string. This means the component names
2962 // didn't come from the same set *or* we encountered an illegal name.
John McCall4bc41ae2010-11-18 19:01:18 +00002963 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramere8394df2010-08-11 14:47:12 +00002964 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00002965 return QualType();
2966 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002967
Nate Begemanbb70bf62009-01-18 01:47:54 +00002968 // Ensure no component accessor exceeds the width of the vector type it
2969 // operates on.
2970 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002971 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002972
2973 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00002974 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002975
2976 while (*compStr) {
2977 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall4bc41ae2010-11-18 19:01:18 +00002978 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begemanbb70bf62009-01-18 01:47:54 +00002979 << baseType << SourceRange(CompLoc);
2980 return QualType();
2981 }
2982 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00002983 }
Nate Begemanf322eab2008-05-09 06:41:27 +00002984
Steve Narofff8fd09e2007-07-27 22:15:19 +00002985 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002986 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00002987 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00002988 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00002989 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00002990 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00002991 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002992 if (HexSwizzle)
2993 CompSize--;
2994
Steve Narofff8fd09e2007-07-27 22:15:19 +00002995 if (CompSize == 1)
2996 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002997
John McCall4bc41ae2010-11-18 19:01:18 +00002998 if (HasRepeated) VK = VK_RValue;
2999
3000 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003001 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00003002 // diagostics look bad. We want extended vector types to appear built-in.
John McCall4bc41ae2010-11-18 19:01:18 +00003003 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3004 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3005 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00003006 }
3007 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00003008}
3009
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003010static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00003011 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003012 const Selector &Sel,
3013 ASTContext &Context) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003014 if (Member)
3015 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3016 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003017 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003018 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00003019
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003020 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3021 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003022 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3023 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003024 return D;
3025 }
3026 return 0;
3027}
3028
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003029static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3030 IdentifierInfo *Member,
3031 const Selector &Sel,
3032 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003033 // Check protocols on qualified interfaces.
3034 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00003035 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003036 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003037 if (Member)
3038 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3039 GDecl = PD;
3040 break;
3041 }
3042 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003043 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003044 GDecl = OMD;
3045 break;
3046 }
3047 }
3048 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00003049 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003050 E = QIdTy->qual_end(); I != E; ++I) {
3051 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003052 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3053 Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003054 if (GDecl)
3055 return GDecl;
3056 }
3057 }
3058 return GDecl;
3059}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00003060
John McCalldadc5752010-08-24 06:29:42 +00003061ExprResult
John McCallb268a282010-08-23 23:25:46 +00003062Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCall2d74de92009-12-01 22:10:20 +00003063 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003064 const CXXScopeSpec &SS,
3065 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003066 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003067 const TemplateArgumentListInfo *TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00003068 // Even in dependent contexts, try to diagnose base expressions with
3069 // obviously wrong types, e.g.:
3070 //
3071 // T* t;
3072 // t.f;
3073 //
3074 // In Obj-C++, however, the above expression is valid, since it could be
3075 // accessing the 'f' property if T is an Obj-C interface. The extra check
3076 // allows this, while still reporting an error if T is a struct pointer.
3077 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00003078 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00003079 if (PT && (!getLangOptions().ObjC1 ||
3080 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00003081 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003082 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00003083 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00003084 return ExprError();
3085 }
3086 }
3087
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003088 assert(BaseType->isDependentType() ||
3089 NameInfo.getName().isDependentName() ||
Douglas Gregor41f90302010-04-12 20:54:26 +00003090 isDependentScopeSpecifier(SS));
John McCall10eae182009-11-30 22:42:35 +00003091
3092 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3093 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00003094 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003095 IsArrow, OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003096 SS.getScopeRep(),
John McCall10eae182009-11-30 22:42:35 +00003097 SS.getRange(),
3098 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003099 NameInfo, TemplateArgs));
John McCall10eae182009-11-30 22:42:35 +00003100}
3101
3102/// We know that the given qualified member reference points only to
3103/// declarations which do not belong to the static type of the base
3104/// expression. Diagnose the problem.
3105static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3106 Expr *BaseExpr,
3107 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003108 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003109 const LookupResult &R) {
John McCallcd4b4772009-12-02 03:53:29 +00003110 // If this is an implicit member access, use a different set of
3111 // diagnostics.
3112 if (!BaseExpr)
3113 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall10eae182009-11-30 22:42:35 +00003114
John McCall1e67dd62010-04-27 01:43:38 +00003115 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_of_unrelated)
3116 << SS.getRange() << R.getRepresentativeDecl() << BaseType;
John McCall10eae182009-11-30 22:42:35 +00003117}
3118
3119// Check whether the declarations we found through a nested-name
3120// specifier in a member expression are actually members of the base
3121// type. The restriction here is:
3122//
3123// C++ [expr.ref]p2:
3124// ... In these cases, the id-expression shall name a
3125// member of the class or of one of its base classes.
3126//
3127// So it's perfectly legitimate for the nested-name specifier to name
3128// an unrelated class, and for us to find an overload set including
3129// decls from classes which are not superclasses, as long as the decl
3130// we actually pick through overload resolution is from a superclass.
3131bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3132 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003133 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003134 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00003135 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3136 if (!BaseRT) {
3137 // We can't check this yet because the base type is still
3138 // dependent.
3139 assert(BaseType->isDependentType());
3140 return false;
3141 }
3142 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00003143
3144 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00003145 // If this is an implicit member reference and we find a
3146 // non-instance member, it's not an error.
John McCalla8ae2222010-04-06 21:38:20 +00003147 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCall2d74de92009-12-01 22:10:20 +00003148 return false;
John McCall10eae182009-11-30 22:42:35 +00003149
John McCall2d74de92009-12-01 22:10:20 +00003150 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman75300492010-07-27 20:51:02 +00003151 DeclContext *DC = (*I)->getDeclContext();
3152 while (DC->isTransparentContext())
3153 DC = DC->getParent();
John McCall2d74de92009-12-01 22:10:20 +00003154
Douglas Gregora9c3e822010-07-28 22:27:52 +00003155 if (!DC->isRecord())
3156 continue;
3157
John McCall2d74de92009-12-01 22:10:20 +00003158 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman75300492010-07-27 20:51:02 +00003159 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCall2d74de92009-12-01 22:10:20 +00003160
3161 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3162 return false;
3163 }
3164
John McCallcd4b4772009-12-02 03:53:29 +00003165 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCall2d74de92009-12-01 22:10:20 +00003166 return true;
3167}
3168
3169static bool
3170LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3171 SourceRange BaseRange, const RecordType *RTy,
John McCalle9cccd82010-06-16 08:42:20 +00003172 SourceLocation OpLoc, CXXScopeSpec &SS,
3173 bool HasTemplateArgs) {
John McCall2d74de92009-12-01 22:10:20 +00003174 RecordDecl *RDecl = RTy->getDecl();
3175 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor89336232010-03-29 23:34:08 +00003176 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCall2d74de92009-12-01 22:10:20 +00003177 << BaseRange))
3178 return true;
3179
John McCalle9cccd82010-06-16 08:42:20 +00003180 if (HasTemplateArgs) {
3181 // LookupTemplateName doesn't expect these both to exist simultaneously.
3182 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3183
3184 bool MOUS;
3185 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3186 return false;
3187 }
3188
John McCall2d74de92009-12-01 22:10:20 +00003189 DeclContext *DC = RDecl;
3190 if (SS.isSet()) {
3191 // If the member name was a qualified-id, look into the
3192 // nested-name-specifier.
3193 DC = SemaRef.computeDeclContext(SS, false);
3194
John McCall0b66eb32010-05-01 00:40:08 +00003195 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCallcd4b4772009-12-02 03:53:29 +00003196 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3197 << SS.getRange() << DC;
3198 return true;
3199 }
3200
John McCall2d74de92009-12-01 22:10:20 +00003201 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003202
John McCall2d74de92009-12-01 22:10:20 +00003203 if (!isa<TypeDecl>(DC)) {
3204 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3205 << DC << SS.getRange();
3206 return true;
John McCall10eae182009-11-30 22:42:35 +00003207 }
3208 }
3209
John McCall2d74de92009-12-01 22:10:20 +00003210 // The record definition is complete, now look up the member.
3211 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00003212
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003213 if (!R.empty())
3214 return false;
3215
3216 // We didn't find anything with the given name, so try to correct
3217 // for typos.
3218 DeclarationName Name = R.getLookupName();
Alexis Huntc46382e2010-04-28 23:02:27 +00003219 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003220 !R.empty() &&
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003221 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3222 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3223 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003224 << FixItHint::CreateReplacement(R.getNameLoc(),
3225 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003226 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3227 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3228 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003229 return false;
3230 } else {
3231 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003232 R.setLookupName(Name);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003233 }
3234
John McCall10eae182009-11-30 22:42:35 +00003235 return false;
3236}
3237
John McCalldadc5752010-08-24 06:29:42 +00003238ExprResult
John McCallb268a282010-08-23 23:25:46 +00003239Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00003240 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003241 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003242 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003243 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003244 const TemplateArgumentListInfo *TemplateArgs) {
John McCallcd4b4772009-12-02 03:53:29 +00003245 if (BaseType->isDependentType() ||
3246 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallb268a282010-08-23 23:25:46 +00003247 return ActOnDependentMemberExpr(Base, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003248 IsArrow, OpLoc,
3249 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003250 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003251
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003252 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00003253
John McCall2d74de92009-12-01 22:10:20 +00003254 // Implicit member accesses.
3255 if (!Base) {
3256 QualType RecordTy = BaseType;
3257 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3258 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3259 RecordTy->getAs<RecordType>(),
John McCalle9cccd82010-06-16 08:42:20 +00003260 OpLoc, SS, TemplateArgs != 0))
John McCall2d74de92009-12-01 22:10:20 +00003261 return ExprError();
3262
3263 // Explicit member accesses.
3264 } else {
John McCalldadc5752010-08-24 06:29:42 +00003265 ExprResult Result =
John McCall2d74de92009-12-01 22:10:20 +00003266 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCall48871652010-08-21 09:40:31 +00003267 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCall2d74de92009-12-01 22:10:20 +00003268
3269 if (Result.isInvalid()) {
3270 Owned(Base);
3271 return ExprError();
3272 }
3273
3274 if (Result.get())
3275 return move(Result);
Sebastian Redlfa1f70f2010-05-07 09:25:11 +00003276
3277 // LookupMemberExpr can modify Base, and thus change BaseType
3278 BaseType = Base->getType();
John McCall10eae182009-11-30 22:42:35 +00003279 }
3280
John McCallb268a282010-08-23 23:25:46 +00003281 return BuildMemberReferenceExpr(Base, BaseType,
John McCall38836f02010-01-15 08:34:02 +00003282 OpLoc, IsArrow, SS, FirstQualifierInScope,
3283 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003284}
3285
John McCalldadc5752010-08-24 06:29:42 +00003286ExprResult
John McCallb268a282010-08-23 23:25:46 +00003287Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCall2d74de92009-12-01 22:10:20 +00003288 SourceLocation OpLoc, bool IsArrow,
3289 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00003290 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00003291 LookupResult &R,
Douglas Gregorb139cd52010-05-01 20:49:11 +00003292 const TemplateArgumentListInfo *TemplateArgs,
3293 bool SuppressQualifierCheck) {
John McCall2d74de92009-12-01 22:10:20 +00003294 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00003295 if (IsArrow) {
3296 assert(BaseType->isPointerType());
3297 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3298 }
John McCalla8ae2222010-04-06 21:38:20 +00003299 R.setBaseObjectType(BaseType);
John McCall10eae182009-11-30 22:42:35 +00003300
John McCallb268a282010-08-23 23:25:46 +00003301 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003302 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3303 DeclarationName MemberName = MemberNameInfo.getName();
3304 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall10eae182009-11-30 22:42:35 +00003305
3306 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00003307 return ExprError();
3308
John McCall10eae182009-11-30 22:42:35 +00003309 if (R.empty()) {
3310 // Rederive where we looked up.
3311 DeclContext *DC = (SS.isSet()
3312 ? computeDeclContext(SS, false)
3313 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00003314
John McCall10eae182009-11-30 22:42:35 +00003315 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00003316 << MemberName << DC
3317 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00003318 return ExprError();
3319 }
3320
John McCall38836f02010-01-15 08:34:02 +00003321 // Diagnose lookups that find only declarations from a non-base
3322 // type. This is possible for either qualified lookups (which may
3323 // have been qualified with an unrelated type) or implicit member
3324 // expressions (which were found with unqualified lookup and thus
3325 // may have come from an enclosing scope). Note that it's okay for
3326 // lookup to find declarations from a non-base type as long as those
3327 // aren't the ones picked by overload resolution.
3328 if ((SS.isSet() || !BaseExpr ||
3329 (isa<CXXThisExpr>(BaseExpr) &&
3330 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00003331 !SuppressQualifierCheck &&
John McCall38836f02010-01-15 08:34:02 +00003332 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00003333 return ExprError();
3334
3335 // Construct an unresolved result if we in fact got an unresolved
3336 // result.
3337 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall58cc69d2010-01-27 01:50:18 +00003338 // Suppress any lookup-related diagnostics; we'll do these when we
3339 // pick a member.
3340 R.suppressDiagnostics();
3341
John McCall10eae182009-11-30 22:42:35 +00003342 UnresolvedMemberExpr *MemExpr
Douglas Gregora6e053e2010-12-15 01:34:56 +00003343 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00003344 BaseExpr, BaseExprType,
3345 IsArrow, OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003346 Qualifier, SS.getRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003347 MemberNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003348 TemplateArgs, R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00003349
3350 return Owned(MemExpr);
3351 }
3352
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003353 assert(R.isSingleResult());
John McCalla8ae2222010-04-06 21:38:20 +00003354 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall10eae182009-11-30 22:42:35 +00003355 NamedDecl *MemberDecl = R.getFoundDecl();
3356
3357 // FIXME: diagnose the presence of template arguments now.
3358
3359 // If the decl being referenced had an error, return an error for this
3360 // sub-expr without emitting another error, in order to avoid cascading
3361 // error cases.
3362 if (MemberDecl->isInvalidDecl())
3363 return ExprError();
3364
John McCall2d74de92009-12-01 22:10:20 +00003365 // Handle the implicit-member-access case.
3366 if (!BaseExpr) {
3367 // If this is not an instance member, convert to a non-member access.
John McCalla8ae2222010-04-06 21:38:20 +00003368 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003369 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCall2d74de92009-12-01 22:10:20 +00003370
Douglas Gregorb15af892010-01-07 23:12:05 +00003371 SourceLocation Loc = R.getNameLoc();
3372 if (SS.getRange().isValid())
3373 Loc = SS.getRange().getBegin();
3374 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003375 }
3376
John McCall10eae182009-11-30 22:42:35 +00003377 bool ShouldCheckUse = true;
3378 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3379 // Don't diagnose the use of a virtual member function unless it's
3380 // explicitly qualified.
3381 if (MD->isVirtual() && !SS.isSet())
3382 ShouldCheckUse = false;
3383 }
3384
3385 // Check the use of this member.
3386 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3387 Owned(BaseExpr);
3388 return ExprError();
3389 }
3390
John McCall34376a62010-12-04 03:47:34 +00003391 // Perform a property load on the base regardless of whether we
3392 // actually need it for the declaration.
3393 if (BaseExpr->getObjectKind() == OK_ObjCProperty)
3394 ConvertPropertyForRValue(BaseExpr);
3395
John McCallfeb624a2010-11-23 20:48:44 +00003396 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3397 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3398 SS, FD, FoundDecl, MemberNameInfo);
John McCall10eae182009-11-30 22:42:35 +00003399
Francois Pichet783dd6e2010-11-21 06:08:52 +00003400 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3401 // We may have found a field within an anonymous union or struct
3402 // (C++ [class.union]).
3403 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
John McCall34376a62010-12-04 03:47:34 +00003404 BaseExpr, OpLoc);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003405
John McCall10eae182009-11-30 22:42:35 +00003406 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3407 MarkDeclarationReferenced(MemberLoc, Var);
3408 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003409 Var, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003410 Var->getType().getNonReferenceType(),
John McCall4bc41ae2010-11-18 19:01:18 +00003411 VK_LValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003412 }
3413
John McCall7decc9e2010-11-18 06:31:45 +00003414 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall10eae182009-11-30 22:42:35 +00003415 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3416 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003417 MemberFn, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003418 MemberFn->getType(),
3419 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3420 OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003421 }
John McCall7decc9e2010-11-18 06:31:45 +00003422 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall10eae182009-11-30 22:42:35 +00003423
3424 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3425 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3426 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003427 Enum, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003428 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003429 }
3430
3431 Owned(BaseExpr);
3432
Douglas Gregor861eb802010-04-25 20:55:08 +00003433 // We found something that we didn't expect. Complain.
John McCall10eae182009-11-30 22:42:35 +00003434 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003435 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregor861eb802010-04-25 20:55:08 +00003436 << MemberName << BaseType << int(IsArrow);
3437 else
3438 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3439 << MemberName << BaseType << int(IsArrow);
John McCall10eae182009-11-30 22:42:35 +00003440
Douglas Gregor861eb802010-04-25 20:55:08 +00003441 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3442 << MemberName;
Douglas Gregor516d6722010-04-25 21:15:30 +00003443 R.suppressDiagnostics();
Douglas Gregor861eb802010-04-25 20:55:08 +00003444 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00003445}
3446
John McCall68fc88ec2010-12-15 16:46:44 +00003447/// Given that normal member access failed on the given expression,
3448/// and given that the expression's type involves builtin-id or
3449/// builtin-Class, decide whether substituting in the redefinition
3450/// types would be profitable. The redefinition type is whatever
3451/// this translation unit tried to typedef to id/Class; we store
3452/// it to the side and then re-use it in places like this.
3453static bool ShouldTryAgainWithRedefinitionType(Sema &S, Expr *&base) {
3454 const ObjCObjectPointerType *opty
3455 = base->getType()->getAs<ObjCObjectPointerType>();
3456 if (!opty) return false;
3457
3458 const ObjCObjectType *ty = opty->getObjectType();
3459
3460 QualType redef;
3461 if (ty->isObjCId()) {
3462 redef = S.Context.ObjCIdRedefinitionType;
3463 } else if (ty->isObjCClass()) {
3464 redef = S.Context.ObjCClassRedefinitionType;
3465 } else {
3466 return false;
3467 }
3468
3469 // Do the substitution as long as the redefinition type isn't just a
3470 // possibly-qualified pointer to builtin-id or builtin-Class again.
3471 opty = redef->getAs<ObjCObjectPointerType>();
3472 if (opty && !opty->getObjectType()->getInterface() != 0)
3473 return false;
3474
3475 S.ImpCastExprToType(base, redef, CK_BitCast);
3476 return true;
3477}
3478
John McCall10eae182009-11-30 22:42:35 +00003479/// Look up the given member of the given non-type-dependent
3480/// expression. This can return in one of two ways:
3481/// * If it returns a sentinel null-but-valid result, the caller will
3482/// assume that lookup was performed and the results written into
3483/// the provided structure. It will take over from there.
3484/// * Otherwise, the returned expression will be produced in place of
3485/// an ordinary member expression.
3486///
3487/// The ObjCImpDecl bit is a gross hack that will need to be properly
3488/// fixed for ObjC++.
John McCalldadc5752010-08-24 06:29:42 +00003489ExprResult
John McCall10eae182009-11-30 22:42:35 +00003490Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00003491 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003492 CXXScopeSpec &SS,
John McCall48871652010-08-21 09:40:31 +00003493 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003494 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00003495
Steve Naroffeaaae462007-12-16 21:42:28 +00003496 // Perform default conversions.
3497 DefaultFunctionArrayConversion(BaseExpr);
John McCall15317a22010-12-15 04:42:30 +00003498 if (IsArrow) DefaultLvalueConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003499
Steve Naroff185616f2007-07-26 03:11:44 +00003500 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00003501 assert(!BaseType->isDependentType());
3502
3503 DeclarationName MemberName = R.getLookupName();
3504 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00003505
John McCall68fc88ec2010-12-15 16:46:44 +00003506 // For later type-checking purposes, turn arrow accesses into dot
3507 // accesses. The only access type we support that doesn't follow
3508 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
3509 // and those never use arrows, so this is unaffected.
3510 if (IsArrow) {
3511 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3512 BaseType = Ptr->getPointeeType();
3513 else if (const ObjCObjectPointerType *Ptr
3514 = BaseType->getAs<ObjCObjectPointerType>())
3515 BaseType = Ptr->getPointeeType();
3516 else if (BaseType->isRecordType()) {
3517 // Recover from arrow accesses to records, e.g.:
3518 // struct MyRecord foo;
3519 // foo->bar
3520 // This is actually well-formed in C++ if MyRecord has an
3521 // overloaded operator->, but that should have been dealt with
3522 // by now.
3523 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3524 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3525 << FixItHint::CreateReplacement(OpLoc, ".");
3526 IsArrow = false;
3527 } else {
3528 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3529 << BaseType << BaseExpr->getSourceRange();
3530 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00003531 }
3532 }
3533
John McCall68fc88ec2010-12-15 16:46:44 +00003534 // Handle field access to simple records.
3535 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
3536 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
3537 RTy, OpLoc, SS, HasTemplateArgs))
3538 return ExprError();
3539
3540 // Returning valid-but-null is how we indicate to the caller that
3541 // the lookup result was filled in.
3542 return Owned((Expr*) 0);
David Chisnall9f57c292009-08-17 16:35:33 +00003543 }
John McCall10eae182009-11-30 22:42:35 +00003544
John McCall68fc88ec2010-12-15 16:46:44 +00003545 // Handle ivar access to Objective-C objects.
3546 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003547 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall68fc88ec2010-12-15 16:46:44 +00003548
3549 // There are three cases for the base type:
3550 // - builtin id (qualified or unqualified)
3551 // - builtin Class (qualified or unqualified)
3552 // - an interface
3553 ObjCInterfaceDecl *IDecl = OTy->getInterface();
3554 if (!IDecl) {
3555 // There's an implicit 'isa' ivar on all objects.
3556 // But we only actually find it this way on objects of type 'id',
3557 // apparently.
3558 if (OTy->isObjCId() && Member->isStr("isa"))
3559 return Owned(new (Context) ObjCIsaExpr(BaseExpr, IsArrow, MemberLoc,
3560 Context.getObjCClassType()));
3561
3562 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3563 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3564 ObjCImpDecl, HasTemplateArgs);
3565 goto fail;
3566 }
3567
3568 ObjCInterfaceDecl *ClassDeclared;
3569 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
3570
3571 if (!IV) {
3572 // Attempt to correct for typos in ivar names.
3573 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3574 LookupMemberName);
3575 if (CorrectTypo(Res, 0, 0, IDecl, false,
3576 IsArrow ? CTC_ObjCIvarLookup
3577 : CTC_ObjCPropertyLookup) &&
3578 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
3579 Diag(R.getNameLoc(),
3580 diag::err_typecheck_member_reference_ivar_suggest)
3581 << IDecl->getDeclName() << MemberName << IV->getDeclName()
3582 << FixItHint::CreateReplacement(R.getNameLoc(),
3583 IV->getNameAsString());
3584 Diag(IV->getLocation(), diag::note_previous_decl)
3585 << IV->getDeclName();
3586 } else {
3587 Res.clear();
3588 Res.setLookupName(Member);
3589
3590 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
3591 << IDecl->getDeclName() << MemberName
3592 << BaseExpr->getSourceRange();
3593 return ExprError();
3594 }
3595 }
3596
3597 // If the decl being referenced had an error, return an error for this
3598 // sub-expr without emitting another error, in order to avoid cascading
3599 // error cases.
3600 if (IV->isInvalidDecl())
3601 return ExprError();
3602
3603 // Check whether we can reference this field.
3604 if (DiagnoseUseOfDecl(IV, MemberLoc))
3605 return ExprError();
3606 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3607 IV->getAccessControl() != ObjCIvarDecl::Package) {
3608 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3609 if (ObjCMethodDecl *MD = getCurMethodDecl())
3610 ClassOfMethodDecl = MD->getClassInterface();
3611 else if (ObjCImpDecl && getCurFunctionDecl()) {
3612 // Case of a c-function declared inside an objc implementation.
3613 // FIXME: For a c-style function nested inside an objc implementation
3614 // class, there is no implementation context available, so we pass
3615 // down the context as argument to this routine. Ideally, this context
3616 // need be passed down in the AST node and somehow calculated from the
3617 // AST for a function decl.
3618 if (ObjCImplementationDecl *IMPD =
3619 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
3620 ClassOfMethodDecl = IMPD->getClassInterface();
3621 else if (ObjCCategoryImplDecl* CatImplClass =
3622 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
3623 ClassOfMethodDecl = CatImplClass->getClassInterface();
3624 }
3625
3626 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3627 if (ClassDeclared != IDecl ||
3628 ClassOfMethodDecl != ClassDeclared)
3629 Diag(MemberLoc, diag::error_private_ivar_access)
3630 << IV->getDeclName();
3631 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3632 // @protected
3633 Diag(MemberLoc, diag::error_protected_ivar_access)
3634 << IV->getDeclName();
3635 }
3636
3637 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3638 MemberLoc, BaseExpr,
3639 IsArrow));
3640 }
3641
3642 // Objective-C property access.
3643 const ObjCObjectPointerType *OPT;
3644 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
3645 // This actually uses the base as an r-value.
3646 DefaultLvalueConversion(BaseExpr);
3647 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr->getType()));
3648
3649 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3650
3651 const ObjCObjectType *OT = OPT->getObjectType();
3652
3653 // id, with and without qualifiers.
3654 if (OT->isObjCId()) {
3655 // Check protocols on qualified interfaces.
3656 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3657 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
3658 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3659 // Check the use of this declaration
3660 if (DiagnoseUseOfDecl(PD, MemberLoc))
3661 return ExprError();
3662
3663 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3664 VK_LValue,
3665 OK_ObjCProperty,
3666 MemberLoc,
3667 BaseExpr));
3668 }
3669
3670 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3671 // Check the use of this method.
3672 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3673 return ExprError();
3674 Selector SetterSel =
3675 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3676 PP.getSelectorTable(), Member);
3677 ObjCMethodDecl *SMD = 0;
3678 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
3679 SetterSel, Context))
3680 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3681 QualType PType = OMD->getSendResultType();
3682
3683 ExprValueKind VK = VK_LValue;
3684 if (!getLangOptions().CPlusPlus &&
3685 IsCForbiddenLValueType(Context, PType))
3686 VK = VK_RValue;
3687 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3688
3689 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
3690 VK, OK,
3691 MemberLoc, BaseExpr));
3692 }
3693 }
3694
3695 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3696 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3697 ObjCImpDecl, HasTemplateArgs);
3698
3699 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3700 << MemberName << BaseType);
3701 }
3702
3703 // 'Class', unqualified only.
3704 if (OT->isObjCClass()) {
3705 // Only works in a method declaration (??!).
3706 ObjCMethodDecl *MD = getCurMethodDecl();
3707 if (!MD) {
3708 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3709 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3710 ObjCImpDecl, HasTemplateArgs);
3711
3712 goto fail;
3713 }
3714
3715 // Also must look for a getter name which uses property syntax.
3716 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003717 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3718 ObjCMethodDecl *Getter;
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003719 if ((Getter = IFace->lookupClassMethod(Sel))) {
3720 // Check the use of this method.
3721 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3722 return ExprError();
John McCall68fc88ec2010-12-15 16:46:44 +00003723 } else
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00003724 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003725 // If we found a getter then this may be a valid dot-reference, we
3726 // will look for the matching setter, in case it is needed.
3727 Selector SetterSel =
John McCall68fc88ec2010-12-15 16:46:44 +00003728 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3729 PP.getSelectorTable(), Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003730 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3731 if (!Setter) {
3732 // If this reference is in an @implementation, also check for 'private'
3733 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00003734 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003735 }
3736 // Look through local category implementations associated with the class.
3737 if (!Setter)
3738 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003739
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003740 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3741 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003742
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003743 if (Getter || Setter) {
3744 QualType PType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003745
John McCall4bc41ae2010-11-18 19:01:18 +00003746 ExprValueKind VK = VK_LValue;
3747 if (Getter) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00003748 PType = Getter->getSendResultType();
John McCall4bc41ae2010-11-18 19:01:18 +00003749 if (!getLangOptions().CPlusPlus &&
3750 IsCForbiddenLValueType(Context, PType))
3751 VK = VK_RValue;
3752 } else {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003753 // Get the expression type from Setter's incoming parameter.
3754 PType = (*(Setter->param_end() -1))->getType();
John McCall4bc41ae2010-11-18 19:01:18 +00003755 }
3756 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3757
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003758 // FIXME: we must check that the setter has property type.
John McCallb7bd14f2010-12-02 01:19:52 +00003759 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
3760 PType, VK, OK,
3761 MemberLoc, BaseExpr));
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003762 }
John McCall68fc88ec2010-12-15 16:46:44 +00003763
3764 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3765 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3766 ObjCImpDecl, HasTemplateArgs);
3767
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003768 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall68fc88ec2010-12-15 16:46:44 +00003769 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003770 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003771
John McCall68fc88ec2010-12-15 16:46:44 +00003772 // Normal property access.
3773 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc,
3774 SourceLocation(), QualType(), false);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003775 }
Alexis Huntc46382e2010-04-28 23:02:27 +00003776
Chris Lattnerb63a7452008-07-21 04:28:12 +00003777 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003778 if (BaseType->isExtVectorType()) {
John McCall15317a22010-12-15 04:42:30 +00003779 // FIXME: this expr should store IsArrow.
Anders Carlssonf571c112009-08-26 18:25:21 +00003780 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall15317a22010-12-15 04:42:30 +00003781 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr->getValueKind());
John McCall4bc41ae2010-11-18 19:01:18 +00003782 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
3783 Member, MemberLoc);
Chris Lattnerb63a7452008-07-21 04:28:12 +00003784 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003785 return ExprError();
John McCall4bc41ae2010-11-18 19:01:18 +00003786
3787 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr,
3788 *Member, MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00003789 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003790
John McCall68fc88ec2010-12-15 16:46:44 +00003791 // Adjust builtin-sel to the appropriate redefinition type if that's
3792 // not just a pointer to builtin-sel again.
3793 if (IsArrow &&
3794 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
3795 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
3796 ImpCastExprToType(BaseExpr, Context.ObjCSelRedefinitionType, CK_BitCast);
3797 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3798 ObjCImpDecl, HasTemplateArgs);
3799 }
3800
3801 // Failure cases.
3802 fail:
3803
3804 // There's a possible road to recovery for function types.
3805 const FunctionType *Fun = 0;
3806
3807 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
3808 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
3809 // fall out, handled below.
3810
3811 // Recover from dot accesses to pointers, e.g.:
3812 // type *foo;
3813 // foo.bar
3814 // This is actually well-formed in two cases:
3815 // - 'type' is an Objective C type
3816 // - 'bar' is a pseudo-destructor name which happens to refer to
3817 // the appropriate pointer type
Argyrios Kyrtzidiscd81fe02011-01-25 23:16:36 +00003818 } else if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
John McCall68fc88ec2010-12-15 16:46:44 +00003819 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
3820 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3821 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3822 << FixItHint::CreateReplacement(OpLoc, "->");
3823
3824 // Recurse as an -> access.
3825 IsArrow = true;
3826 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3827 ObjCImpDecl, HasTemplateArgs);
3828 }
3829 } else {
3830 Fun = BaseType->getAs<FunctionType>();
3831 }
3832
3833 // If the user is trying to apply -> or . to a function pointer
3834 // type, it's probably because they forgot parentheses to call that
3835 // function. Suggest the addition of those parentheses, build the
3836 // call, and continue on.
3837 if (Fun || BaseType == Context.OverloadTy) {
3838 bool TryCall;
3839 if (BaseType == Context.OverloadTy) {
3840 TryCall = true;
3841 } else {
3842 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
3843 TryCall = (FPT->getNumArgs() == 0);
3844 } else {
3845 TryCall = true;
3846 }
3847
3848 if (TryCall) {
3849 QualType ResultTy = Fun->getResultType();
3850 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
3851 (IsArrow && ResultTy->isPointerType() &&
3852 ResultTy->getAs<PointerType>()->getPointeeType()->isRecordType());
3853 }
3854 }
3855
3856
3857 if (TryCall) {
3858 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
3859 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
3860 << QualType(Fun, 0)
3861 << FixItHint::CreateInsertion(Loc, "()");
3862
3863 ExprResult NewBase
3864 = ActOnCallExpr(0, BaseExpr, Loc, MultiExprArg(*this, 0, 0), Loc);
3865 if (NewBase.isInvalid())
3866 return ExprError();
3867 BaseExpr = NewBase.takeAs<Expr>();
3868
3869
3870 DefaultFunctionArrayConversion(BaseExpr);
3871 BaseType = BaseExpr->getType();
3872
3873 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3874 ObjCImpDecl, HasTemplateArgs);
3875 }
3876 }
3877
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003878 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3879 << BaseType << BaseExpr->getSourceRange();
3880
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003881 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00003882}
3883
John McCall10eae182009-11-30 22:42:35 +00003884/// The main callback when the parser finds something like
3885/// expression . [nested-name-specifier] identifier
3886/// expression -> [nested-name-specifier] identifier
3887/// where 'identifier' encompasses a fairly broad spectrum of
3888/// possibilities, including destructor and operator references.
3889///
3890/// \param OpKind either tok::arrow or tok::period
3891/// \param HasTrailingLParen whether the next token is '(', which
3892/// is used to diagnose mis-uses of special members that can
3893/// only be called
3894/// \param ObjCImpDecl the current ObjC @implementation decl;
3895/// this is an ugly hack around the fact that ObjC @implementations
3896/// aren't properly put in the context chain
John McCalldadc5752010-08-24 06:29:42 +00003897ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall15317a22010-12-15 04:42:30 +00003898 SourceLocation OpLoc,
3899 tok::TokenKind OpKind,
3900 CXXScopeSpec &SS,
3901 UnqualifiedId &Id,
3902 Decl *ObjCImpDecl,
3903 bool HasTrailingLParen) {
John McCall10eae182009-11-30 22:42:35 +00003904 if (SS.isSet() && SS.isInvalid())
3905 return ExprError();
3906
Francois Pichet64225792011-01-18 05:04:39 +00003907 // Warn about the explicit constructor calls Microsoft extension.
3908 if (getLangOptions().Microsoft &&
3909 Id.getKind() == UnqualifiedId::IK_ConstructorName)
3910 Diag(Id.getSourceRange().getBegin(),
3911 diag::ext_ms_explicit_constructor_call);
3912
John McCall10eae182009-11-30 22:42:35 +00003913 TemplateArgumentListInfo TemplateArgsBuffer;
3914
3915 // Decompose the name into its component parts.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003916 DeclarationNameInfo NameInfo;
John McCall10eae182009-11-30 22:42:35 +00003917 const TemplateArgumentListInfo *TemplateArgs;
3918 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003919 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003920
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003921 DeclarationName Name = NameInfo.getName();
John McCall10eae182009-11-30 22:42:35 +00003922 bool IsArrow = (OpKind == tok::arrow);
3923
3924 NamedDecl *FirstQualifierInScope
3925 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3926 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3927
3928 // This is a postfix expression, so get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003929 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003930 if (Result.isInvalid()) return ExprError();
3931 Base = Result.take();
John McCall10eae182009-11-30 22:42:35 +00003932
Douglas Gregor41f90302010-04-12 20:54:26 +00003933 if (Base->getType()->isDependentType() || Name.isDependentName() ||
3934 isDependentScopeSpecifier(SS)) {
John McCallb268a282010-08-23 23:25:46 +00003935 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00003936 IsArrow, OpLoc,
3937 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003938 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003939 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003940 LookupResult R(*this, NameInfo, LookupMemberName);
John McCalle9cccd82010-06-16 08:42:20 +00003941 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3942 SS, ObjCImpDecl, TemplateArgs != 0);
Alexis Huntc46382e2010-04-28 23:02:27 +00003943
John McCalle9cccd82010-06-16 08:42:20 +00003944 if (Result.isInvalid()) {
3945 Owned(Base);
3946 return ExprError();
3947 }
John McCall10eae182009-11-30 22:42:35 +00003948
John McCalle9cccd82010-06-16 08:42:20 +00003949 if (Result.get()) {
3950 // The only way a reference to a destructor can be used is to
3951 // immediately call it, which falls into this case. If the
3952 // next token is not a '(', produce a diagnostic and build the
3953 // call now.
3954 if (!HasTrailingLParen &&
3955 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCallb268a282010-08-23 23:25:46 +00003956 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall10eae182009-11-30 22:42:35 +00003957
John McCalle9cccd82010-06-16 08:42:20 +00003958 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00003959 }
3960
John McCallb268a282010-08-23 23:25:46 +00003961 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00003962 OpLoc, IsArrow, SS, FirstQualifierInScope,
3963 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003964 }
3965
3966 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00003967}
3968
John McCalldadc5752010-08-24 06:29:42 +00003969ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003970 FunctionDecl *FD,
3971 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003972 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003973 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003974 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003975 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003976 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003977 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003978 return ExprError();
3979 }
3980
3981 if (Param->hasUninstantiatedDefaultArg()) {
3982 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003983
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003984 // Instantiate the expression.
3985 MultiLevelTemplateArgumentList ArgList
3986 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003987
Nico Weber44887f62010-11-29 18:19:25 +00003988 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003989 = ArgList.getInnermost();
3990 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3991 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003992
Nico Weber44887f62010-11-29 18:19:25 +00003993 ExprResult Result;
3994 {
3995 // C++ [dcl.fct.default]p5:
3996 // The names in the [default argument] expression are bound, and
3997 // the semantic constraints are checked, at the point where the
3998 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003999 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00004000 Result = SubstExpr(UninstExpr, ArgList);
4001 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004002 if (Result.isInvalid())
4003 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004004
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004005 // Check the expression as an initializer for the parameter.
4006 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004007 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004008 InitializationKind Kind
4009 = InitializationKind::CreateCopy(Param->getLocation(),
4010 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4011 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00004012
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004013 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4014 Result = InitSeq.Perform(*this, Entity, Kind,
4015 MultiExprArg(*this, &ResultE, 1));
4016 if (Result.isInvalid())
4017 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004018
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004019 // Build the default argument expression.
4020 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4021 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00004022 }
4023
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004024 // If the default expression creates temporaries, we need to
4025 // push them to the current stack of expression temporaries so they'll
4026 // be properly destroyed.
4027 // FIXME: We should really be rebuilding the default argument with new
4028 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00004029 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4030 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4031 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4032 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4033 ExprTemporaries.push_back(Temporary);
4034 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004035
4036 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00004037 // Just mark all of the declarations in this potentially-evaluated expression
4038 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004039 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00004040 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00004041}
4042
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004043/// ConvertArgumentsForCall - Converts the arguments specified in
4044/// Args/NumArgs to the parameter types of the function FDecl with
4045/// function prototype Proto. Call is the call expression itself, and
4046/// Fn is the function expression. For a C++ member function, this
4047/// routine does not attempt to convert the object argument. Returns
4048/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004049bool
4050Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004051 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004052 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004053 Expr **Args, unsigned NumArgs,
4054 SourceLocation RParenLoc) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00004055 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004056 // assignment, to the types of the corresponding parameter, ...
4057 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00004058 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004059
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004060 // If too few arguments are available (and we don't have default
4061 // arguments for the remaining parameters), don't make the call.
4062 if (NumArgs < NumArgsInProto) {
4063 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4064 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004065 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00004066 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00004067 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004068 }
4069
4070 // If too many are passed and not variadic, error on the extras and drop
4071 // them.
4072 if (NumArgs > NumArgsInProto) {
4073 if (!Proto->isVariadic()) {
4074 Diag(Args[NumArgsInProto]->getLocStart(),
4075 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004076 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004077 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004078 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4079 Args[NumArgs-1]->getLocEnd());
4080 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00004081 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004082 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004083 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004084 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004085 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004086 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004087 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4088 if (Fn->getType()->isBlockPointerType())
4089 CallType = VariadicBlock; // Block
4090 else if (isa<MemberExpr>(Fn))
4091 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004092 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004093 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004094 if (Invalid)
4095 return true;
4096 unsigned TotalNumArgs = AllArgs.size();
4097 for (unsigned i = 0; i < TotalNumArgs; ++i)
4098 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004099
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004100 return false;
4101}
Mike Stump4e1f26a2009-02-19 03:04:26 +00004102
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004103bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4104 FunctionDecl *FDecl,
4105 const FunctionProtoType *Proto,
4106 unsigned FirstProtoArg,
4107 Expr **Args, unsigned NumArgs,
4108 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004109 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004110 unsigned NumArgsInProto = Proto->getNumArgs();
4111 unsigned NumArgsToCheck = NumArgs;
4112 bool Invalid = false;
4113 if (NumArgs != NumArgsInProto)
4114 // Use default arguments for missing arguments
4115 NumArgsToCheck = NumArgsInProto;
4116 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004117 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004118 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004119 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004120
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004121 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004122 if (ArgIx < NumArgs) {
4123 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004124
Eli Friedman3164fb12009-03-22 22:00:50 +00004125 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4126 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00004127 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004128 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00004129 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004130
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004131 // Pass the argument
4132 ParmVarDecl *Param = 0;
4133 if (FDecl && i < FDecl->getNumParams())
4134 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00004135
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004136 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004137 Param? InitializedEntity::InitializeParameter(Context, Param)
4138 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCalldadc5752010-08-24 06:29:42 +00004139 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00004140 SourceLocation(),
4141 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004142 if (ArgE.isInvalid())
4143 return true;
4144
4145 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004146 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00004147 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004148
John McCalldadc5752010-08-24 06:29:42 +00004149 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004150 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004151 if (ArgExpr.isInvalid())
4152 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004153
Anders Carlsson355933d2009-08-25 03:49:14 +00004154 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004155 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004156 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004157 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004158
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004159 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004160 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004161 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004162 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004163 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004164 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004165 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004166 }
4167 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00004168 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004169}
4170
Steve Naroff83895f72007-09-16 03:34:24 +00004171/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00004172/// This provides the location of the left/right parens and a list of comma
4173/// locations.
John McCalldadc5752010-08-24 06:29:42 +00004174ExprResult
John McCallb268a282010-08-23 23:25:46 +00004175Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004176 MultiExprArg args, SourceLocation RParenLoc) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004177 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00004178
4179 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004180 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00004181 if (Result.isInvalid()) return ExprError();
4182 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00004183
John McCallb268a282010-08-23 23:25:46 +00004184 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00004185
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004186 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00004187 // If this is a pseudo-destructor expression, build the call immediately.
4188 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4189 if (NumArgs > 0) {
4190 // Pseudo-destructor calls should not have any arguments.
4191 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00004192 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00004193 SourceRange(Args[0]->getLocStart(),
4194 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00004195
Douglas Gregorad8a3362009-09-04 17:36:40 +00004196 NumArgs = 0;
4197 }
Mike Stump11289f42009-09-09 15:08:12 +00004198
Douglas Gregorad8a3362009-09-04 17:36:40 +00004199 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00004200 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00004201 }
Mike Stump11289f42009-09-09 15:08:12 +00004202
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004203 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00004204 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00004205 // FIXME: Will need to cache the results of name lookup (including ADL) in
4206 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004207 bool Dependent = false;
4208 if (Fn->isTypeDependent())
4209 Dependent = true;
4210 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4211 Dependent = true;
4212
4213 if (Dependent)
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004214 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00004215 Context.DependentTy, VK_RValue,
4216 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004217
4218 // Determine whether this is a call to an object (C++ [over.call.object]).
4219 if (Fn->getType()->isRecordType())
4220 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004221 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004222
John McCall10eae182009-11-30 22:42:35 +00004223 Expr *NakedFn = Fn->IgnoreParens();
4224
4225 // Determine whether this is a call to an unresolved member function.
4226 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4227 // If lookup was unresolved but not dependent (i.e. didn't find
4228 // an unresolved using declaration), it has to be an overloaded
4229 // function set, which means it must contain either multiple
4230 // declarations (all methods or method templates) or a single
4231 // method template.
4232 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor516d6722010-04-25 21:15:30 +00004233 isa<FunctionTemplateDecl>(
4234 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00004235 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00004236
John McCall2d74de92009-12-01 22:10:20 +00004237 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004238 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00004239 }
4240
Douglas Gregore254f902009-02-04 00:32:51 +00004241 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00004242 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004243 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00004244 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00004245 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004246 RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004247 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004248
Anders Carlsson61914b52009-10-03 17:40:22 +00004249 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00004250 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
John McCalle3027922010-08-25 11:45:40 +00004251 if (BO->getOpcode() == BO_PtrMemD ||
4252 BO->getOpcode() == BO_PtrMemI) {
Douglas Gregorc8be9522010-05-04 18:18:31 +00004253 if (const FunctionProtoType *FPT
4254 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00004255 QualType ResultTy = FPT->getCallResultType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00004256 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004257
John McCallb268a282010-08-23 23:25:46 +00004258 CXXMemberCallExpr *TheCall
Abramo Bagnara21e9d862010-12-03 21:39:42 +00004259 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
John McCall7decc9e2010-11-18 06:31:45 +00004260 NumArgs, ResultTy, VK,
John McCallb268a282010-08-23 23:25:46 +00004261 RParenLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004262
4263 if (CheckCallReturnType(FPT->getResultType(),
4264 BO->getRHS()->getSourceRange().getBegin(),
John McCallb268a282010-08-23 23:25:46 +00004265 TheCall, 0))
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004266 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00004267
John McCallb268a282010-08-23 23:25:46 +00004268 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004269 RParenLoc))
4270 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00004271
John McCallb268a282010-08-23 23:25:46 +00004272 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004273 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004274 return ExprError(Diag(Fn->getLocStart(),
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004275 diag::err_typecheck_call_not_function)
4276 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson61914b52009-10-03 17:40:22 +00004277 }
4278 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004279 }
4280
Douglas Gregore254f902009-02-04 00:32:51 +00004281 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004282 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00004283 // lookup and whether there were any explicitly-specified template arguments.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004284
Eli Friedmane14b1992009-12-26 03:35:45 +00004285 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00004286 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4287 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4288 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
4289 RParenLoc);
4290 }
4291
John McCall57500772009-12-16 12:17:52 +00004292 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00004293 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4294 if (UnOp->getOpcode() == UO_AddrOf)
4295 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4296
John McCall57500772009-12-16 12:17:52 +00004297 if (isa<DeclRefExpr>(NakedFn))
4298 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4299
John McCall2d74de92009-12-01 22:10:20 +00004300 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
4301}
4302
John McCall57500772009-12-16 12:17:52 +00004303/// BuildResolvedCallExpr - Build a call to a resolved expression,
4304/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00004305/// unary-convert to an expression of function-pointer or
4306/// block-pointer type.
4307///
4308/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00004309ExprResult
John McCall2d74de92009-12-01 22:10:20 +00004310Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4311 SourceLocation LParenLoc,
4312 Expr **Args, unsigned NumArgs,
4313 SourceLocation RParenLoc) {
4314 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4315
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004316 // Promote the function operand.
4317 UsualUnaryConversions(Fn);
4318
Chris Lattner08464942007-12-28 05:29:59 +00004319 // Make the call expr early, before semantic checks. This guarantees cleanup
4320 // of arguments and function on error.
John McCallb268a282010-08-23 23:25:46 +00004321 CallExpr *TheCall = new (Context) CallExpr(Context, Fn,
4322 Args, NumArgs,
4323 Context.BoolTy,
John McCall7decc9e2010-11-18 06:31:45 +00004324 VK_RValue,
John McCallb268a282010-08-23 23:25:46 +00004325 RParenLoc);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004326
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004327 const FunctionType *FuncT;
4328 if (!Fn->getType()->isBlockPointerType()) {
4329 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4330 // have type pointer to function".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004331 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004332 if (PT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004333 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4334 << Fn->getType() << Fn->getSourceRange());
John McCall9dd450b2009-09-21 23:43:11 +00004335 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004336 } else { // This is a block call.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004337 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall9dd450b2009-09-21 23:43:11 +00004338 getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004339 }
Chris Lattner08464942007-12-28 05:29:59 +00004340 if (FuncT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004341 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4342 << Fn->getType() << Fn->getSourceRange());
4343
Eli Friedman3164fb12009-03-22 22:00:50 +00004344 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004345 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00004346 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004347 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00004348 return ExprError();
4349
Chris Lattner08464942007-12-28 05:29:59 +00004350 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004351 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00004352 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004353
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004354 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00004355 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004356 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004357 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00004358 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004359 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004360
Douglas Gregord8e97de2009-04-02 15:37:10 +00004361 if (FDecl) {
4362 // Check if we have too few/too many template arguments, based
4363 // on our knowledge of the function definition.
4364 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00004365 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004366 const FunctionProtoType *Proto
4367 = Def->getType()->getAs<FunctionProtoType>();
4368 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004369 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4370 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004371 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00004372
4373 // If the function we're calling isn't a function prototype, but we have
4374 // a function prototype from a prior declaratiom, use that prototype.
4375 if (!FDecl->hasPrototype())
4376 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00004377 }
4378
Steve Naroff0b661582007-08-28 23:30:39 +00004379 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00004380 for (unsigned i = 0; i != NumArgs; i++) {
4381 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00004382
4383 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004384 InitializedEntity Entity
4385 = InitializedEntity::InitializeParameter(Context,
4386 Proto->getArgType(i));
4387 ExprResult ArgE = PerformCopyInitialization(Entity,
4388 SourceLocation(),
4389 Owned(Arg));
4390 if (ArgE.isInvalid())
4391 return true;
4392
4393 Arg = ArgE.takeAs<Expr>();
4394
4395 } else {
4396 DefaultArgumentPromotion(Arg);
Douglas Gregor8e09a722010-10-25 20:39:23 +00004397 }
4398
Douglas Gregor83025412010-10-26 05:45:40 +00004399 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4400 Arg->getType(),
4401 PDiag(diag::err_call_incomplete_argument)
4402 << Arg->getSourceRange()))
4403 return ExprError();
4404
Chris Lattner08464942007-12-28 05:29:59 +00004405 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00004406 }
Steve Naroffae4143e2007-04-26 20:39:23 +00004407 }
Chris Lattner08464942007-12-28 05:29:59 +00004408
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004409 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4410 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004411 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4412 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004413
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00004414 // Check for sentinels
4415 if (NDecl)
4416 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004417
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004418 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004419 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00004420 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004421 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004422
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00004423 if (unsigned BuiltinID = FDecl->getBuiltinID())
4424 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004425 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00004426 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004427 return ExprError();
4428 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004429
John McCallb268a282010-08-23 23:25:46 +00004430 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00004431}
4432
John McCalldadc5752010-08-24 06:29:42 +00004433ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004434Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004435 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00004436 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00004437 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00004438 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00004439
4440 TypeSourceInfo *TInfo;
4441 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4442 if (!TInfo)
4443 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4444
John McCallb268a282010-08-23 23:25:46 +00004445 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00004446}
4447
John McCalldadc5752010-08-24 06:29:42 +00004448ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00004449Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00004450 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00004451 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00004452
Eli Friedman37a186d2008-05-20 05:22:08 +00004453 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004454 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4455 PDiag(diag::err_illegal_decl_array_incomplete_type)
4456 << SourceRange(LParenLoc,
4457 literalExpr->getSourceRange().getEnd())))
4458 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00004459 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004460 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4461 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00004462 } else if (!literalType->isDependentType() &&
4463 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00004464 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00004465 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00004466 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004467 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00004468
Douglas Gregor85dabae2009-12-16 01:38:02 +00004469 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00004470 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004471 InitializationKind Kind
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004472 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004473 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00004474 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00004475 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00004476 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00004477 &literalType);
4478 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004479 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00004480 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00004481
Chris Lattner79413952008-12-04 23:50:19 +00004482 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00004483 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00004484 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004485 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004486 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004487
John McCall7decc9e2010-11-18 06:31:45 +00004488 // In C, compound literals are l-values for some reason.
4489 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
4490
John McCall5d7aa7f2010-01-19 22:33:45 +00004491 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCall7decc9e2010-11-18 06:31:45 +00004492 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004493}
4494
John McCalldadc5752010-08-24 06:29:42 +00004495ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00004496Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004497 SourceLocation RBraceLoc) {
4498 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00004499 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00004500
Steve Naroff30d242c2007-09-15 18:49:24 +00004501 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004502 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004503
Ted Kremenekac034612010-04-13 23:39:13 +00004504 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4505 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004506 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004507 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004508}
4509
John McCalld7646252010-11-14 08:17:51 +00004510/// Prepares for a scalar cast, performing all the necessary stages
4511/// except the final cast and returning the kind required.
4512static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
4513 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4514 // Also, callers should have filtered out the invalid cases with
4515 // pointers. Everything else should be possible.
4516
Abramo Bagnaraba854972011-01-04 09:50:03 +00004517 QualType SrcTy = Src->getType();
John McCalld7646252010-11-14 08:17:51 +00004518 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004519 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004520
John McCall8cb679e2010-11-15 09:13:47 +00004521 switch (SrcTy->getScalarTypeKind()) {
4522 case Type::STK_MemberPointer:
4523 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00004524
John McCall8cb679e2010-11-15 09:13:47 +00004525 case Type::STK_Pointer:
4526 switch (DestTy->getScalarTypeKind()) {
4527 case Type::STK_Pointer:
4528 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00004529 CK_AnyPointerToObjCPointerCast :
4530 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00004531 case Type::STK_Bool:
4532 return CK_PointerToBoolean;
4533 case Type::STK_Integral:
4534 return CK_PointerToIntegral;
4535 case Type::STK_Floating:
4536 case Type::STK_FloatingComplex:
4537 case Type::STK_IntegralComplex:
4538 case Type::STK_MemberPointer:
4539 llvm_unreachable("illegal cast from pointer");
4540 }
4541 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004542
John McCall8cb679e2010-11-15 09:13:47 +00004543 case Type::STK_Bool: // casting from bool is like casting from an integer
4544 case Type::STK_Integral:
4545 switch (DestTy->getScalarTypeKind()) {
4546 case Type::STK_Pointer:
John McCalld7646252010-11-14 08:17:51 +00004547 if (Src->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004548 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004549 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004550 case Type::STK_Bool:
4551 return CK_IntegralToBoolean;
4552 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004553 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004554 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004555 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004556 case Type::STK_IntegralComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004557 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallfcef3cf2010-12-14 17:51:41 +00004558 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004559 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004560 case Type::STK_FloatingComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004561 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004562 CK_IntegralToFloating);
4563 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004564 case Type::STK_MemberPointer:
4565 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004566 }
4567 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004568
John McCall8cb679e2010-11-15 09:13:47 +00004569 case Type::STK_Floating:
4570 switch (DestTy->getScalarTypeKind()) {
4571 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004572 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004573 case Type::STK_Bool:
4574 return CK_FloatingToBoolean;
4575 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004576 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004577 case Type::STK_FloatingComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004578 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallfcef3cf2010-12-14 17:51:41 +00004579 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004580 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004581 case Type::STK_IntegralComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004582 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004583 CK_FloatingToIntegral);
4584 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004585 case Type::STK_Pointer:
4586 llvm_unreachable("valid float->pointer cast?");
4587 case Type::STK_MemberPointer:
4588 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004589 }
4590 break;
4591
John McCall8cb679e2010-11-15 09:13:47 +00004592 case Type::STK_FloatingComplex:
4593 switch (DestTy->getScalarTypeKind()) {
4594 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004595 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004596 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004597 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004598 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00004599 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00004600 if (S.Context.hasSameType(ET, DestTy))
4601 return CK_FloatingComplexToReal;
4602 S.ImpCastExprToType(Src, ET, CK_FloatingComplexToReal);
4603 return CK_FloatingCast;
4604 }
John McCall8cb679e2010-11-15 09:13:47 +00004605 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004606 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004607 case Type::STK_Integral:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004608 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004609 CK_FloatingComplexToReal);
4610 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004611 case Type::STK_Pointer:
4612 llvm_unreachable("valid complex float->pointer cast?");
4613 case Type::STK_MemberPointer:
4614 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004615 }
4616 break;
4617
John McCall8cb679e2010-11-15 09:13:47 +00004618 case Type::STK_IntegralComplex:
4619 switch (DestTy->getScalarTypeKind()) {
4620 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004621 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004622 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004623 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004624 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00004625 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00004626 if (S.Context.hasSameType(ET, DestTy))
4627 return CK_IntegralComplexToReal;
4628 S.ImpCastExprToType(Src, ET, CK_IntegralComplexToReal);
4629 return CK_IntegralCast;
4630 }
John McCall8cb679e2010-11-15 09:13:47 +00004631 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004632 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004633 case Type::STK_Floating:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004634 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004635 CK_IntegralComplexToReal);
4636 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004637 case Type::STK_Pointer:
4638 llvm_unreachable("valid complex int->pointer cast?");
4639 case Type::STK_MemberPointer:
4640 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004641 }
4642 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00004643 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004644
John McCalld7646252010-11-14 08:17:51 +00004645 llvm_unreachable("Unhandled scalar cast");
4646 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00004647}
4648
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004649/// CheckCastTypes - Check type constraints for casting between types.
John McCall7decc9e2010-11-18 06:31:45 +00004650bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
4651 Expr *&castExpr, CastKind& Kind, ExprValueKind &VK,
4652 CXXCastPath &BasePath, bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00004653 if (getLangOptions().CPlusPlus)
Douglas Gregor15417cf2010-11-03 00:35:38 +00004654 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
4655 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00004656 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00004657 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00004658
John McCall7decc9e2010-11-18 06:31:45 +00004659 // We only support r-value casts in C.
4660 VK = VK_RValue;
4661
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004662 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4663 // type needs to be scalar.
4664 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00004665 // We don't necessarily do lvalue-to-rvalue conversions on this.
4666 IgnoredValueConversions(castExpr);
4667
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004668 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00004669 Kind = CK_ToVoid;
Anders Carlssonef918ac2009-10-16 02:35:04 +00004670 return false;
4671 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004672
John McCall34376a62010-12-04 03:47:34 +00004673 DefaultFunctionArrayLvalueConversion(castExpr);
4674
Eli Friedmane98194d2010-07-17 20:43:49 +00004675 if (RequireCompleteType(TyR.getBegin(), castType,
4676 diag::err_typecheck_cast_to_incomplete))
4677 return true;
4678
Anders Carlssonef918ac2009-10-16 02:35:04 +00004679 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004680 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004681 (castType->isStructureType() || castType->isUnionType())) {
4682 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00004683 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004684 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
4685 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004686 Kind = CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00004687 return false;
4688 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004689
Anders Carlsson525b76b2009-10-16 02:48:28 +00004690 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004691 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004692 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004693 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004694 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004695 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004696 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00004697 castExpr->getType()) &&
4698 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004699 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4700 << castExpr->getSourceRange();
4701 break;
4702 }
4703 }
4704 if (Field == FieldEnd)
4705 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
4706 << castExpr->getType() << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004707 Kind = CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00004708 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004709 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004710
Anders Carlsson525b76b2009-10-16 02:48:28 +00004711 // Reject any other conversions to non-scalar types.
4712 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
4713 << castType << castExpr->getSourceRange();
4714 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004715
John McCalld7646252010-11-14 08:17:51 +00004716 // The type we're casting to is known to be a scalar or vector.
4717
4718 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004719 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00004720 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00004721 return Diag(castExpr->getLocStart(),
4722 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004723 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004724 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004725
4726 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00004727 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004728
Anders Carlsson525b76b2009-10-16 02:48:28 +00004729 if (castType->isVectorType())
4730 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
4731 if (castExpr->getType()->isVectorType())
4732 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
4733
John McCalld7646252010-11-14 08:17:51 +00004734 // The source and target types are both scalars, i.e.
4735 // - arithmetic types (fundamental, enum, and complex)
4736 // - all kinds of pointers
4737 // Note that member pointers were filtered out with C++, above.
4738
Anders Carlsson43d70f82009-10-16 05:23:41 +00004739 if (isa<ObjCSelectorExpr>(castExpr))
4740 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004741
John McCalld7646252010-11-14 08:17:51 +00004742 // If either type is a pointer, the other type has to be either an
4743 // integer or a pointer.
Anders Carlsson525b76b2009-10-16 02:48:28 +00004744 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004745 QualType castExprType = castExpr->getType();
Douglas Gregor6972a622010-06-16 00:35:25 +00004746 if (!castExprType->isIntegralType(Context) &&
Douglas Gregorb90df602010-06-16 00:17:44 +00004747 castExprType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004748 return Diag(castExpr->getLocStart(),
4749 diag::err_cast_pointer_from_non_pointer_int)
4750 << castExprType << castExpr->getSourceRange();
4751 } else if (!castExpr->getType()->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00004752 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004753 return Diag(castExpr->getLocStart(),
4754 diag::err_cast_pointer_to_non_pointer_int)
4755 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004756 }
Anders Carlsson094c4592009-10-18 18:12:03 +00004757
John McCalld7646252010-11-14 08:17:51 +00004758 Kind = PrepareScalarCast(*this, castExpr, castType);
John McCall2b5c1b22010-08-12 21:44:57 +00004759
John McCalld7646252010-11-14 08:17:51 +00004760 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00004761 CheckCastAlign(castExpr, castType, TyR);
4762
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004763 return false;
4764}
4765
Anders Carlsson525b76b2009-10-16 02:48:28 +00004766bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004767 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004768 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004769
Anders Carlssonde71adf2007-11-27 05:51:55 +00004770 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004771 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004772 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004773 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004774 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004775 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004776 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004777 } else
4778 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004779 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004780 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004781
John McCalle3027922010-08-25 11:45:40 +00004782 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004783 return false;
4784}
4785
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004786bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
John McCalle3027922010-08-25 11:45:40 +00004787 CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004788 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004789
Anders Carlsson43d70f82009-10-16 05:23:41 +00004790 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004791
Nate Begemanc8961a42009-06-27 22:05:55 +00004792 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4793 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00004794 if (SrcTy->isVectorType()) {
4795 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
4796 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4797 << DestTy << SrcTy << R;
John McCalle3027922010-08-25 11:45:40 +00004798 Kind = CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00004799 return false;
4800 }
4801
Nate Begemanbd956c42009-06-28 02:36:38 +00004802 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004803 // conversion will take place first from scalar to elt type, and then
4804 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004805 if (SrcTy->isPointerType())
4806 return Diag(R.getBegin(),
4807 diag::err_invalid_conversion_between_vector_and_scalar)
4808 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004809
4810 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4811 ImpCastExprToType(CastExpr, DestElemTy,
John McCalld7646252010-11-14 08:17:51 +00004812 PrepareScalarCast(*this, CastExpr, DestElemTy));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004813
John McCalle3027922010-08-25 11:45:40 +00004814 Kind = CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00004815 return false;
4816}
4817
John McCalldadc5752010-08-24 06:29:42 +00004818ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004819Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004820 SourceLocation RParenLoc, Expr *castExpr) {
4821 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004822 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004823
John McCall97513962010-01-15 18:39:57 +00004824 TypeSourceInfo *castTInfo;
4825 QualType castType = GetTypeFromParser(Ty, &castTInfo);
4826 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00004827 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00004828
Nate Begeman5ec4b312009-08-10 23:49:36 +00004829 // If the Expr being casted is a ParenListExpr, handle it specially.
4830 if (isa<ParenListExpr>(castExpr))
John McCallb268a282010-08-23 23:25:46 +00004831 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCalle15bbff2010-01-18 19:35:47 +00004832 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00004833
John McCallb268a282010-08-23 23:25:46 +00004834 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00004835}
4836
John McCalldadc5752010-08-24 06:29:42 +00004837ExprResult
John McCallebe54742010-01-15 18:56:44 +00004838Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00004839 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00004840 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00004841 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00004842 CXXCastPath BasePath;
John McCallebe54742010-01-15 18:56:44 +00004843 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
John McCall7decc9e2010-11-18 06:31:45 +00004844 Kind, VK, BasePath))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004845 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00004846
John McCallcf142162010-08-07 06:22:56 +00004847 return Owned(CStyleCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +00004848 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00004849 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00004850 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004851}
4852
Nate Begeman5ec4b312009-08-10 23:49:36 +00004853/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4854/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004855ExprResult
John McCallb268a282010-08-23 23:25:46 +00004856Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004857 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4858 if (!E)
4859 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00004860
John McCalldadc5752010-08-24 06:29:42 +00004861 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004862
Nate Begeman5ec4b312009-08-10 23:49:36 +00004863 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004864 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4865 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004866
John McCallb268a282010-08-23 23:25:46 +00004867 if (Result.isInvalid()) return ExprError();
4868
4869 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004870}
4871
John McCalldadc5752010-08-24 06:29:42 +00004872ExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00004873Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00004874 SourceLocation RParenLoc, Expr *Op,
John McCalle15bbff2010-01-18 19:35:47 +00004875 TypeSourceInfo *TInfo) {
John McCallb268a282010-08-23 23:25:46 +00004876 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCalle15bbff2010-01-18 19:35:47 +00004877 QualType Ty = TInfo->getType();
John Thompson781ad172010-06-30 22:55:51 +00004878 bool isAltiVecLiteral = false;
Mike Stump11289f42009-09-09 15:08:12 +00004879
John Thompson781ad172010-06-30 22:55:51 +00004880 // Check for an altivec literal,
4881 // i.e. all the elements are integer constants.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004882 if (getLangOptions().AltiVec && Ty->isVectorType()) {
4883 if (PE->getNumExprs() == 0) {
4884 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
4885 return ExprError();
4886 }
John Thompson781ad172010-06-30 22:55:51 +00004887 if (PE->getNumExprs() == 1) {
4888 if (!PE->getExpr(0)->getType()->isVectorType())
4889 isAltiVecLiteral = true;
4890 }
4891 else
4892 isAltiVecLiteral = true;
4893 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00004894
John Thompson781ad172010-06-30 22:55:51 +00004895 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
4896 // then handle it as such.
4897 if (isAltiVecLiteral) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004898 llvm::SmallVector<Expr *, 8> initExprs;
4899 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4900 initExprs.push_back(PE->getExpr(i));
4901
4902 // FIXME: This means that pretty-printing the final AST will produce curly
4903 // braces instead of the original commas.
Ted Kremenekac034612010-04-13 23:39:13 +00004904 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
4905 &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00004906 initExprs.size(), RParenLoc);
4907 E->setType(Ty);
John McCallb268a282010-08-23 23:25:46 +00004908 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004909 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004910 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00004911 // sequence of BinOp comma operators.
John McCalldadc5752010-08-24 06:29:42 +00004912 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCallb268a282010-08-23 23:25:46 +00004913 if (Result.isInvalid()) return ExprError();
4914 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004915 }
4916}
4917
John McCalldadc5752010-08-24 06:29:42 +00004918ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00004919 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004920 MultiExprArg Val,
John McCallba7bf592010-08-24 05:47:05 +00004921 ParsedType TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004922 unsigned nexprs = Val.size();
4923 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004924 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4925 Expr *expr;
4926 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4927 expr = new (Context) ParenExpr(L, R, exprs[0]);
4928 else
4929 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004930 return Owned(expr);
4931}
4932
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004933/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4934/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004935/// C99 6.5.15
4936QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCall7decc9e2010-11-18 06:31:45 +00004937 Expr *&SAVE, ExprValueKind &VK,
John McCall4bc41ae2010-11-18 19:01:18 +00004938 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004939 SourceLocation QuestionLoc) {
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004940 // If both LHS and RHS are overloaded functions, try to resolve them.
4941 if (Context.hasSameType(LHS->getType(), RHS->getType()) &&
4942 LHS->getType()->isSpecificBuiltinType(BuiltinType::Overload)) {
4943 ExprResult LHSResult = CheckPlaceholderExpr(LHS, QuestionLoc);
4944 if (LHSResult.isInvalid())
4945 return QualType();
4946
4947 ExprResult RHSResult = CheckPlaceholderExpr(RHS, QuestionLoc);
4948 if (RHSResult.isInvalid())
4949 return QualType();
4950
4951 LHS = LHSResult.take();
4952 RHS = RHSResult.take();
4953 }
4954
Sebastian Redl1a99f442009-04-16 17:51:27 +00004955 // C++ is sufficiently different to merit its own checker.
4956 if (getLangOptions().CPlusPlus)
John McCall4bc41ae2010-11-18 19:01:18 +00004957 return CXXCheckConditionalOperands(Cond, LHS, RHS, SAVE,
4958 VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004959
4960 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004961 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004962
Chris Lattner432cff52009-02-18 04:28:32 +00004963 UsualUnaryConversions(Cond);
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00004964 if (SAVE) {
4965 SAVE = LHS = Cond;
4966 }
4967 else
4968 UsualUnaryConversions(LHS);
Chris Lattner432cff52009-02-18 04:28:32 +00004969 UsualUnaryConversions(RHS);
4970 QualType CondTy = Cond->getType();
4971 QualType LHSTy = LHS->getType();
4972 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004973
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004974 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004975 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00004976 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4977 // Throw an error if its not either.
4978 if (getLangOptions().OpenCL) {
4979 if (!CondTy->isVectorType()) {
4980 Diag(Cond->getLocStart(),
4981 diag::err_typecheck_cond_expect_scalar_or_vector)
4982 << CondTy;
4983 return QualType();
4984 }
4985 }
4986 else {
4987 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4988 << CondTy;
4989 return QualType();
4990 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004991 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004992
Chris Lattnere2949f42008-01-06 22:42:25 +00004993 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004994 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4995 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00004996
Nate Begemanabb5a732010-09-20 22:41:17 +00004997 // OpenCL: If the condition is a vector, and both operands are scalar,
4998 // attempt to implicity convert them to the vector type to act like the
4999 // built in select.
5000 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5001 // Both operands should be of scalar type.
5002 if (!LHSTy->isScalarType()) {
5003 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5004 << CondTy;
5005 return QualType();
5006 }
5007 if (!RHSTy->isScalarType()) {
5008 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5009 << CondTy;
5010 return QualType();
5011 }
5012 // Implicity convert these scalars to the type of the condition.
5013 ImpCastExprToType(LHS, CondTy, CK_IntegralCast);
5014 ImpCastExprToType(RHS, CondTy, CK_IntegralCast);
5015 }
5016
Chris Lattnere2949f42008-01-06 22:42:25 +00005017 // If both operands have arithmetic type, do the usual arithmetic conversions
5018 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00005019 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5020 UsualArithmeticConversions(LHS, RHS);
5021 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00005022 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005023
Chris Lattnere2949f42008-01-06 22:42:25 +00005024 // If both operands are the same structure or union type, the result is that
5025 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005026 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5027 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00005028 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005029 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00005030 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00005031 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00005032 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005033 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005034
Chris Lattnere2949f42008-01-06 22:42:25 +00005035 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00005036 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00005037 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5038 if (!LHSTy->isVoidType())
5039 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5040 << RHS->getSourceRange();
5041 if (!RHSTy->isVoidType())
5042 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5043 << LHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005044 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid);
5045 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00005046 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00005047 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00005048 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5049 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00005050 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005051 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005052 // promote the null to a pointer.
John McCall8cb679e2010-11-15 09:13:47 +00005053 ImpCastExprToType(RHS, LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005054 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005055 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005056 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005057 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00005058 ImpCastExprToType(LHS, RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005059 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005060 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005061
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005062 // All objective-c pointer type analysis is done here.
5063 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5064 QuestionLoc);
5065 if (!compositeType.isNull())
5066 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005067
5068
Steve Naroff05efa972009-07-01 14:36:47 +00005069 // Handle block pointer types.
5070 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5071 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5072 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5073 QualType destType = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005074 ImpCastExprToType(LHS, destType, CK_BitCast);
5075 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005076 return destType;
5077 }
5078 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005079 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00005080 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00005081 }
Steve Naroff05efa972009-07-01 14:36:47 +00005082 // We have 2 block pointer types.
5083 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5084 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00005085 return LHSTy;
5086 }
Steve Naroff05efa972009-07-01 14:36:47 +00005087 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005088 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5089 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005090
Steve Naroff05efa972009-07-01 14:36:47 +00005091 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5092 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00005093 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005094 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00005095 // In this situation, we assume void* type. No especially good
5096 // reason, but this is what gcc does, and we do have to pick
5097 // to get a consistent AST.
5098 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005099 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5100 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00005101 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005102 }
Steve Naroff05efa972009-07-01 14:36:47 +00005103 // The block pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00005104 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5105 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00005106 return LHSTy;
5107 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005108
Steve Naroff05efa972009-07-01 14:36:47 +00005109 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5110 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5111 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005112 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5113 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00005114
5115 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5116 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5117 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00005118 QualType destPointee
5119 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005120 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005121 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005122 ImpCastExprToType(LHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005123 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005124 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005125 return destType;
5126 }
5127 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00005128 QualType destPointee
5129 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005130 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005131 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005132 ImpCastExprToType(RHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005133 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005134 ImpCastExprToType(LHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005135 return destType;
5136 }
5137
5138 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5139 // Two identical pointer types are always compatible.
5140 return LHSTy;
5141 }
5142 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5143 rhptee.getUnqualifiedType())) {
5144 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5145 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5146 // In this situation, we assume void* type. No especially good
5147 // reason, but this is what gcc does, and we do have to pick
5148 // to get a consistent AST.
5149 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005150 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5151 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005152 return incompatTy;
5153 }
5154 // The pointer types are compatible.
5155 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5156 // differently qualified versions of compatible types, the result type is
5157 // a pointer to an appropriately qualified version of the *composite*
5158 // type.
5159 // FIXME: Need to calculate the composite type.
5160 // FIXME: Need to add qualifiers
John McCalle3027922010-08-25 11:45:40 +00005161 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5162 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005163 return LHSTy;
5164 }
Mike Stump11289f42009-09-09 15:08:12 +00005165
John McCalle84af4e2010-11-13 01:35:44 +00005166 // GCC compatibility: soften pointer/integer mismatch. Note that
5167 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00005168 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5169 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5170 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005171 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005172 return RHSTy;
5173 }
5174 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5175 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5176 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005177 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005178 return LHSTy;
5179 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00005180
Chris Lattnere2949f42008-01-06 22:42:25 +00005181 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00005182 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5183 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005184 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00005185}
5186
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005187/// FindCompositeObjCPointerType - Helper method to find composite type of
5188/// two objective-c pointer types of the two input expressions.
5189QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
5190 SourceLocation QuestionLoc) {
5191 QualType LHSTy = LHS->getType();
5192 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005193
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005194 // Handle things like Class and struct objc_class*. Here we case the result
5195 // to the pseudo-builtin, because that will be implicitly cast back to the
5196 // redefinition type if an attempt is made to access its fields.
5197 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005198 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005199 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005200 return LHSTy;
5201 }
5202 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005203 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005204 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005205 return RHSTy;
5206 }
5207 // And the same for struct objc_object* / id
5208 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005209 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005210 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005211 return LHSTy;
5212 }
5213 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005214 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005215 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005216 return RHSTy;
5217 }
5218 // And the same for struct objc_selector* / SEL
5219 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005220 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005221 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005222 return LHSTy;
5223 }
5224 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005225 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005226 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005227 return RHSTy;
5228 }
5229 // Check constraints for Objective-C object pointers types.
5230 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005231
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005232 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5233 // Two identical object pointer types are always compatible.
5234 return LHSTy;
5235 }
5236 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5237 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5238 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005239
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005240 // If both operands are interfaces and either operand can be
5241 // assigned to the other, use that type as the composite
5242 // type. This allows
5243 // xxx ? (A*) a : (B*) b
5244 // where B is a subclass of A.
5245 //
5246 // Additionally, as for assignment, if either type is 'id'
5247 // allow silent coercion. Finally, if the types are
5248 // incompatible then make sure to use 'id' as the composite
5249 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005250
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005251 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5252 // It could return the composite type.
5253 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5254 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5255 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5256 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5257 } else if ((LHSTy->isObjCQualifiedIdType() ||
5258 RHSTy->isObjCQualifiedIdType()) &&
5259 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5260 // Need to handle "id<xx>" explicitly.
5261 // GCC allows qualified id and any Objective-C type to devolve to
5262 // id. Currently localizing to here until clear this should be
5263 // part of ObjCQualifiedIdTypesAreCompatible.
5264 compositeType = Context.getObjCIdType();
5265 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5266 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005267 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005268 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5269 ;
5270 else {
5271 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5272 << LHSTy << RHSTy
5273 << LHS->getSourceRange() << RHS->getSourceRange();
5274 QualType incompatTy = Context.getObjCIdType();
John McCalle3027922010-08-25 11:45:40 +00005275 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5276 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005277 return incompatTy;
5278 }
5279 // The object pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00005280 ImpCastExprToType(LHS, compositeType, CK_BitCast);
5281 ImpCastExprToType(RHS, compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005282 return compositeType;
5283 }
5284 // Check Objective-C object pointer types and 'void *'
5285 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5286 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5287 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5288 QualType destPointee
5289 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5290 QualType destType = Context.getPointerType(destPointee);
5291 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005292 ImpCastExprToType(LHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005293 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005294 ImpCastExprToType(RHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005295 return destType;
5296 }
5297 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5298 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5299 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5300 QualType destPointee
5301 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5302 QualType destType = Context.getPointerType(destPointee);
5303 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005304 ImpCastExprToType(RHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005305 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005306 ImpCastExprToType(LHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005307 return destType;
5308 }
5309 return QualType();
5310}
5311
Steve Naroff83895f72007-09-16 03:34:24 +00005312/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005313/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005314ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Sebastian Redlb5d49352009-01-19 22:31:54 +00005315 SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +00005316 Expr *CondExpr, Expr *LHSExpr,
5317 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005318 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5319 // was the condition.
5320 bool isLHSNull = LHSExpr == 0;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005321 Expr *SAVEExpr = 0;
5322 if (isLHSNull) {
5323 LHSExpr = SAVEExpr = CondExpr;
5324 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005325
John McCall7decc9e2010-11-18 06:31:45 +00005326 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005327 ExprObjectKind OK = OK_Ordinary;
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00005328 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr,
John McCall4bc41ae2010-11-18 19:01:18 +00005329 SAVEExpr, VK, OK, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00005330 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005331 return ExprError();
5332
Douglas Gregor7e112b02009-08-26 14:37:04 +00005333 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005334 LHSExpr, ColonLoc,
5335 RHSExpr, SAVEExpr,
John McCall4bc41ae2010-11-18 19:01:18 +00005336 result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005337}
5338
Steve Naroff3f597292007-05-11 22:18:03 +00005339// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005340// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005341// routine is it effectively iqnores the qualifiers on the top level pointee.
5342// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5343// FIXME: add a couple examples in this comment.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005344Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00005345Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Steve Naroff3f597292007-05-11 22:18:03 +00005346 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005347
David Chisnall9f57c292009-08-17 16:35:33 +00005348 if ((lhsType->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005349 (Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType))) ||
David Chisnall9f57c292009-08-17 16:35:33 +00005350 (rhsType->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005351 (Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)))) {
David Chisnall9f57c292009-08-17 16:35:33 +00005352 return Compatible;
5353 }
5354
Steve Naroff1f4d7272007-05-11 04:00:31 +00005355 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005356 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
5357 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005358
Steve Naroff1f4d7272007-05-11 04:00:31 +00005359 // make sure we operate on the canonical type
Chris Lattner574dee62008-07-26 22:17:49 +00005360 lhptee = Context.getCanonicalType(lhptee);
5361 rhptee = Context.getCanonicalType(rhptee);
Steve Naroff1f4d7272007-05-11 04:00:31 +00005362
Chris Lattner9bad62c2008-01-04 18:04:52 +00005363 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005364
5365 // C99 6.5.16.1p1: This following citation is common to constraints
5366 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5367 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianece85822009-02-17 18:27:45 +00005368 // FIXME: Handle ExtQualType
Douglas Gregor9a657932008-10-21 23:43:52 +00005369 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner9bad62c2008-01-04 18:04:52 +00005370 ConvTy = CompatiblePointerDiscardsQualifiers;
Steve Naroff3f597292007-05-11 22:18:03 +00005371
Mike Stump4e1f26a2009-02-19 03:04:26 +00005372 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5373 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005374 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005375 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005376 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005377 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005378
Chris Lattner0a788432008-01-03 22:56:36 +00005379 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005380 assert(rhptee->isFunctionType());
5381 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005382 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005383
Chris Lattner0a788432008-01-03 22:56:36 +00005384 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005385 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005386 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005387
5388 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005389 assert(lhptee->isFunctionType());
5390 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005391 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005392 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005393 // unqualified versions of compatible types, ...
Eli Friedman80160bd2009-03-22 23:59:44 +00005394 lhptee = lhptee.getUnqualifiedType();
5395 rhptee = rhptee.getUnqualifiedType();
5396 if (!Context.typesAreCompatible(lhptee, rhptee)) {
5397 // Check if the pointee types are compatible ignoring the sign.
5398 // We explicitly check for char so that we catch "char" vs
5399 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005400 if (lhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00005401 lhptee = Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005402 else if (lhptee->hasSignedIntegerRepresentation())
Eli Friedman80160bd2009-03-22 23:59:44 +00005403 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005404
Chris Lattnerec3a1562009-10-17 20:33:28 +00005405 if (rhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00005406 rhptee = Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005407 else if (rhptee->hasSignedIntegerRepresentation())
Eli Friedman80160bd2009-03-22 23:59:44 +00005408 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005409
Eli Friedman80160bd2009-03-22 23:59:44 +00005410 if (lhptee == rhptee) {
5411 // Types are compatible ignoring the sign. Qualifier incompatibility
5412 // takes priority over sign incompatibility because the sign
5413 // warning can be disabled.
5414 if (ConvTy != Compatible)
5415 return ConvTy;
5416 return IncompatiblePointerSign;
5417 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005418
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005419 // If we are a multi-level pointer, it's possible that our issue is simply
5420 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5421 // the eventual target type is the same and the pointers have the same
5422 // level of indirection, this must be the issue.
5423 if (lhptee->isPointerType() && rhptee->isPointerType()) {
5424 do {
5425 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
5426 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005427
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005428 lhptee = Context.getCanonicalType(lhptee);
5429 rhptee = Context.getCanonicalType(rhptee);
5430 } while (lhptee->isPointerType() && rhptee->isPointerType());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005431
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005432 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Alexis Hunt6f3de502009-11-08 07:46:34 +00005433 return IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005434 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005435
Eli Friedman80160bd2009-03-22 23:59:44 +00005436 // General pointer incompatibility takes priority over qualifiers.
Mike Stump11289f42009-09-09 15:08:12 +00005437 return IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005438 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005439 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005440}
5441
Steve Naroff081c7422008-09-04 15:10:53 +00005442/// CheckBlockPointerTypesForAssignment - This routine determines whether two
5443/// block pointer types are compatible or whether a block and normal pointer
5444/// are compatible. It is more restrict than comparing two function pointer
5445// types.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005446Sema::AssignConvertType
5447Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff081c7422008-09-04 15:10:53 +00005448 QualType rhsType) {
5449 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005450
Steve Naroff081c7422008-09-04 15:10:53 +00005451 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005452 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
5453 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005454
Steve Naroff081c7422008-09-04 15:10:53 +00005455 // make sure we operate on the canonical type
5456 lhptee = Context.getCanonicalType(lhptee);
5457 rhptee = Context.getCanonicalType(rhptee);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005458
Steve Naroff081c7422008-09-04 15:10:53 +00005459 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005460
Steve Naroff081c7422008-09-04 15:10:53 +00005461 // For blocks we enforce that qualifiers are identical.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005462 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff081c7422008-09-04 15:10:53 +00005463 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005464
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005465 if (!getLangOptions().CPlusPlus) {
5466 if (!Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5467 return IncompatibleBlockPointer;
5468 }
5469 else if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump4e1f26a2009-02-19 03:04:26 +00005470 return IncompatibleBlockPointer;
Steve Naroff081c7422008-09-04 15:10:53 +00005471 return ConvTy;
5472}
5473
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005474/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
5475/// for assignment compatibility.
5476Sema::AssignConvertType
5477Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005478 if (lhsType->isObjCBuiltinType()) {
5479 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005480 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5481 !rhsType->isObjCQualifiedClassType())
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005482 return IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005483 return Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005484 }
5485 if (rhsType->isObjCBuiltinType()) {
5486 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005487 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5488 !lhsType->isObjCQualifiedClassType())
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005489 return IncompatiblePointer;
5490 return Compatible;
5491 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005492 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005493 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005494 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005495 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
5496 // make sure we operate on the canonical type
5497 lhptee = Context.getCanonicalType(lhptee);
5498 rhptee = Context.getCanonicalType(rhptee);
5499 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5500 return CompatiblePointerDiscardsQualifiers;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005501
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005502 if (Context.typesAreCompatible(lhsType, rhsType))
5503 return Compatible;
5504 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
5505 return IncompatibleObjCQualifiedId;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005506 return IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005507}
5508
John McCall29600e12010-11-16 02:32:08 +00005509Sema::AssignConvertType
5510Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
5511 // Fake up an opaque expression. We don't actually care about what
5512 // cast operations are required, so if CheckAssignmentConstraints
5513 // adds casts to this they'll be wasted, but fortunately that doesn't
5514 // usually happen on valid code.
5515 OpaqueValueExpr rhs(rhsType, VK_RValue);
5516 Expr *rhsPtr = &rhs;
5517 CastKind K = CK_Invalid;
5518
5519 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5520}
5521
Mike Stump4e1f26a2009-02-19 03:04:26 +00005522/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5523/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005524/// pointers. Here are some objectionable examples that GCC considers warnings:
5525///
5526/// int a, *pint;
5527/// short *pshort;
5528/// struct foo *pfoo;
5529///
5530/// pint = pshort; // warning: assignment from incompatible pointer type
5531/// a = pint; // warning: assignment makes integer from pointer without a cast
5532/// pint = a; // warning: assignment makes pointer from integer without a cast
5533/// pint = pfoo; // warning: assignment from incompatible pointer type
5534///
5535/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005536/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005537///
John McCall8cb679e2010-11-15 09:13:47 +00005538/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005539Sema::AssignConvertType
John McCall29600e12010-11-16 02:32:08 +00005540Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs,
John McCall8cb679e2010-11-15 09:13:47 +00005541 CastKind &Kind) {
John McCall29600e12010-11-16 02:32:08 +00005542 QualType rhsType = rhs->getType();
5543
Chris Lattnera52c2f22008-01-04 23:18:45 +00005544 // Get canonical types. We're not formatting these types, just comparing
5545 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00005546 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5547 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005548
John McCall8cb679e2010-11-15 09:13:47 +00005549 if (lhsType == rhsType) {
5550 Kind = CK_NoOp;
Chris Lattnerf5c973d2008-01-07 17:51:46 +00005551 return Compatible; // Common case: fast path an exact match.
John McCall8cb679e2010-11-15 09:13:47 +00005552 }
Steve Naroff44fd8ff2007-07-24 21:46:40 +00005553
David Chisnall9f57c292009-08-17 16:35:33 +00005554 if ((lhsType->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005555 (Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType))) ||
David Chisnall9f57c292009-08-17 16:35:33 +00005556 (rhsType->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005557 (Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)))) {
John McCall8cb679e2010-11-15 09:13:47 +00005558 Kind = CK_BitCast;
5559 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005560 }
5561
Douglas Gregor6b754842008-10-28 00:22:11 +00005562 // If the left-hand side is a reference type, then we are in a
5563 // (rare!) case where we've allowed the use of references in C,
5564 // e.g., as a parameter type in a built-in function. In this case,
5565 // just make sure that the type referenced is compatible with the
5566 // right-hand side type. The caller is responsible for adjusting
5567 // lhsType so that the resulting expression does not have reference
5568 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005569 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005570 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5571 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005572 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005573 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005574 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005575 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005576 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5577 // to the same ExtVector type.
5578 if (lhsType->isExtVectorType()) {
5579 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005580 return Incompatible;
5581 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005582 // CK_VectorSplat does T -> vector T, so first cast to the
5583 // element type.
5584 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5585 if (elType != rhsType) {
5586 Kind = PrepareScalarCast(*this, rhs, elType);
5587 ImpCastExprToType(rhs, elType, Kind);
5588 }
5589 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005590 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005591 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005592 }
Mike Stump11289f42009-09-09 15:08:12 +00005593
Nate Begeman191a6b12008-07-14 18:02:46 +00005594 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005595 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005596 // Allow assignments of an AltiVec vector type to an equivalent GCC
5597 // vector type and vice versa
5598 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5599 Kind = CK_BitCast;
5600 return Compatible;
5601 }
5602
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005603 // If we are allowing lax vector conversions, and LHS and RHS are both
5604 // vectors, the total size only needs to be the same. This is a bitcast;
5605 // no bits are changed but the result type is different.
5606 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00005607 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00005608 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005609 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005610 }
Chris Lattner881a2122008-01-04 23:32:24 +00005611 }
5612 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005613 }
Eli Friedman3360d892008-05-30 18:07:22 +00005614
Douglas Gregorbea453a2010-05-23 21:53:47 +00005615 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00005616 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00005617 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005618 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005619 }
Eli Friedman3360d892008-05-30 18:07:22 +00005620
Chris Lattnerec646832008-04-07 06:49:41 +00005621 if (isa<PointerType>(lhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005622 if (rhsType->isIntegerType()) {
5623 Kind = CK_IntegralToPointer; // FIXME: null?
Chris Lattner940cfeb2008-01-04 18:22:42 +00005624 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005625 }
Eli Friedman3360d892008-05-30 18:07:22 +00005626
John McCall8cb679e2010-11-15 09:13:47 +00005627 if (isa<PointerType>(rhsType)) {
5628 Kind = CK_BitCast;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005629 return CheckPointerTypesForAssignment(lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00005630 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005631
Steve Naroffaccc4882009-07-20 17:56:53 +00005632 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005633 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005634 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005635 if (lhsType->isVoidPointerType()) // an exception to the rule.
5636 return Compatible;
5637 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005638 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005639 if (rhsType->getAs<BlockPointerType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005640 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
5641 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005642 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005643 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005644
5645 // Treat block pointers as objects.
John McCall8cb679e2010-11-15 09:13:47 +00005646 if (getLangOptions().ObjC1 && lhsType->isObjCIdType()) {
5647 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005648 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005649 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005650 }
Steve Naroff081c7422008-09-04 15:10:53 +00005651 return Incompatible;
5652 }
5653
5654 if (isa<BlockPointerType>(lhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005655 if (rhsType->isIntegerType()) {
5656 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005657 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005658 }
5659
5660 Kind = CK_AnyPointerToObjCPointerCast;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005661
Steve Naroff32d072c2008-09-29 18:10:17 +00005662 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005663 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00005664 return Compatible;
5665
Steve Naroff081c7422008-09-04 15:10:53 +00005666 if (rhsType->isBlockPointerType())
5667 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005668
John McCall8cb679e2010-11-15 09:13:47 +00005669 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
Steve Naroff081c7422008-09-04 15:10:53 +00005670 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00005671 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005672
Chris Lattnera52c2f22008-01-04 23:18:45 +00005673 return Incompatible;
5674 }
5675
Steve Naroff7cae42b2009-07-10 23:34:53 +00005676 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005677 if (rhsType->isIntegerType()) {
5678 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005679 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005680 }
5681
5682 Kind = CK_BitCast;
Mike Stump11289f42009-09-09 15:08:12 +00005683
Steve Naroffaccc4882009-07-20 17:56:53 +00005684 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005685 if (isa<PointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005686 if (rhsType->isVoidPointerType()) // an exception to the rule.
5687 return Compatible;
5688 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005689 }
5690 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005691 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005692 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005693 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005694 if (RHSPT->getPointeeType()->isVoidType())
5695 return Compatible;
5696 }
5697 // Treat block pointers as objects.
5698 if (rhsType->isBlockPointerType())
5699 return Compatible;
5700 return Incompatible;
5701 }
Chris Lattnerec646832008-04-07 06:49:41 +00005702 if (isa<PointerType>(rhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00005703 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
John McCall8cb679e2010-11-15 09:13:47 +00005704 if (lhsType == Context.BoolTy) {
5705 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005706 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005707 }
Eli Friedman3360d892008-05-30 18:07:22 +00005708
John McCall8cb679e2010-11-15 09:13:47 +00005709 if (lhsType->isIntegerType()) {
5710 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005711 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005712 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005713
5714 if (isa<BlockPointerType>(lhsType) &&
John McCall8cb679e2010-11-15 09:13:47 +00005715 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
5716 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005717 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005718 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005719 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005720 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005721 if (isa<ObjCObjectPointerType>(rhsType)) {
5722 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
John McCall8cb679e2010-11-15 09:13:47 +00005723 if (lhsType == Context.BoolTy) {
5724 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005725 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005726 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005727
John McCall8cb679e2010-11-15 09:13:47 +00005728 if (lhsType->isIntegerType()) {
5729 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005730 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005731 }
5732
5733 Kind = CK_BitCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005734
Steve Naroffaccc4882009-07-20 17:56:53 +00005735 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005736 if (isa<PointerType>(lhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005737 if (lhsType->isVoidPointerType()) // an exception to the rule.
5738 return Compatible;
5739 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005740 }
5741 if (isa<BlockPointerType>(lhsType) &&
John McCall8cb679e2010-11-15 09:13:47 +00005742 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
5743 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005744 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005745 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005746 return Incompatible;
5747 }
Eli Friedman3360d892008-05-30 18:07:22 +00005748
Chris Lattnera52c2f22008-01-04 23:18:45 +00005749 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005750 if (Context.typesAreCompatible(lhsType, rhsType)) {
5751 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005752 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005753 }
Bill Wendling216423b2007-05-30 06:30:29 +00005754 }
Steve Naroff98cf3e92007-06-06 18:38:38 +00005755 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005756}
5757
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005758/// \brief Constructs a transparent union from an expression that is
5759/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00005760static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005761 QualType UnionType, FieldDecl *Field) {
5762 // Build an initializer list that designates the appropriate member
5763 // of the transparent union.
Ted Kremenekac034612010-04-13 23:39:13 +00005764 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005765 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005766 SourceLocation());
5767 Initializer->setType(UnionType);
5768 Initializer->setInitializedFieldInUnion(Field);
5769
5770 // Build a compound literal constructing a value of the transparent
5771 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005772 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall5d7aa7f2010-01-19 22:33:45 +00005773 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCall7decc9e2010-11-18 06:31:45 +00005774 VK_RValue, Initializer, false);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005775}
5776
5777Sema::AssignConvertType
5778Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
5779 QualType FromType = rExpr->getType();
5780
Mike Stump11289f42009-09-09 15:08:12 +00005781 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005782 // transparent_union GCC extension.
5783 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005784 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005785 return Incompatible;
5786
5787 // The field to initialize within the transparent union.
5788 RecordDecl *UD = UT->getDecl();
5789 FieldDecl *InitField = 0;
5790 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005791 for (RecordDecl::field_iterator it = UD->field_begin(),
5792 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005793 it != itend; ++it) {
5794 if (it->getType()->isPointerType()) {
5795 // If the transparent union contains a pointer type, we allow:
5796 // 1) void pointer
5797 // 2) null pointer constant
5798 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005799 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John McCalle3027922010-08-25 11:45:40 +00005800 ImpCastExprToType(rExpr, it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005801 InitField = *it;
5802 break;
5803 }
Mike Stump11289f42009-09-09 15:08:12 +00005804
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005805 if (rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005806 Expr::NPC_ValueDependentIsNull)) {
John McCalle84af4e2010-11-13 01:35:44 +00005807 ImpCastExprToType(rExpr, it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005808 InitField = *it;
5809 break;
5810 }
5811 }
5812
John McCall29600e12010-11-16 02:32:08 +00005813 Expr *rhs = rExpr;
John McCall8cb679e2010-11-15 09:13:47 +00005814 CastKind Kind = CK_Invalid;
John McCall29600e12010-11-16 02:32:08 +00005815 if (CheckAssignmentConstraints(it->getType(), rhs, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005816 == Compatible) {
John McCall29600e12010-11-16 02:32:08 +00005817 ImpCastExprToType(rhs, it->getType(), Kind);
5818 rExpr = rhs;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005819 InitField = *it;
5820 break;
5821 }
5822 }
5823
5824 if (!InitField)
5825 return Incompatible;
5826
5827 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
5828 return Compatible;
5829}
5830
Chris Lattner9bad62c2008-01-04 18:04:52 +00005831Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005832Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005833 if (getLangOptions().CPlusPlus) {
5834 if (!lhsType->isRecordType()) {
5835 // C++ 5.17p3: If the left operand is not of class type, the
5836 // expression is implicitly converted (C++ 4) to the
5837 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00005838 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005839 AA_Assigning))
Douglas Gregor9a657932008-10-21 23:43:52 +00005840 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00005841 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00005842 }
5843
5844 // FIXME: Currently, we fall through and treat C++ classes like C
5845 // structures.
John McCall34376a62010-12-04 03:47:34 +00005846 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005847
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005848 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5849 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00005850 if ((lhsType->isPointerType() ||
5851 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00005852 lhsType->isBlockPointerType())
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005853 && rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005854 Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00005855 ImpCastExprToType(rExpr, lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005856 return Compatible;
5857 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005858
Chris Lattnere6dcd502007-10-16 02:55:40 +00005859 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005860 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005861 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005862 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005863 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005864 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00005865 if (!lhsType->isReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00005866 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005867
John McCall8cb679e2010-11-15 09:13:47 +00005868 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005869 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00005870 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005871
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005872 // C99 6.5.16.1p2: The value of the right operand is converted to the
5873 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005874 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5875 // so that we can use references in built-in functions even in C.
5876 // The getNonReferenceType() call makes sure that the resulting expression
5877 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005878 if (result != Incompatible && rExpr->getType() != lhsType)
John McCall8cb679e2010-11-15 09:13:47 +00005879 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005880 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005881}
5882
Chris Lattner326f7572008-11-18 01:30:42 +00005883QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005884 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005885 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00005886 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005887 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005888}
5889
Chris Lattnerfaa54172010-01-12 21:23:57 +00005890QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00005891 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005892 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00005893 QualType lhsType =
5894 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
5895 QualType rhsType =
5896 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005897
Nate Begeman191a6b12008-07-14 18:02:46 +00005898 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005899 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00005900 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005901
Nate Begeman191a6b12008-07-14 18:02:46 +00005902 // Handle the case of a vector & extvector type of the same size and element
5903 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005904 if (getLangOptions().LaxVectorConversions) {
John McCall9dd450b2009-09-21 23:43:11 +00005905 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00005906 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00005907 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005908 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005909 if (lhsType->isExtVectorType()) {
John McCalle3027922010-08-25 11:45:40 +00005910 ImpCastExprToType(rex, lhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005911 return lhsType;
5912 }
5913
John McCalle3027922010-08-25 11:45:40 +00005914 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005915 return rhsType;
Eric Christophera613f562010-08-26 00:42:16 +00005916 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
5917 // If we are allowing lax vector conversions, and LHS and RHS are both
5918 // vectors, the total size only needs to be the same. This is a
5919 // bitcast; no bits are changed but the result type is different.
5920 ImpCastExprToType(rex, lhsType, CK_BitCast);
5921 return lhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005922 }
Eric Christophera613f562010-08-26 00:42:16 +00005923 }
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00005924 }
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005925 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005926
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005927 // Handle the case of equivalent AltiVec and GCC vector types
5928 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5929 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John McCalle3027922010-08-25 11:45:40 +00005930 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005931 return rhsType;
5932 }
5933
Nate Begemanbd956c42009-06-28 02:36:38 +00005934 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5935 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5936 bool swapped = false;
5937 if (rhsType->isExtVectorType()) {
5938 swapped = true;
5939 std::swap(rex, lex);
5940 std::swap(rhsType, lhsType);
5941 }
Mike Stump11289f42009-09-09 15:08:12 +00005942
Nate Begeman886448d2009-06-28 19:12:57 +00005943 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00005944 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005945 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005946 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00005947 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
5948 if (order > 0)
5949 ImpCastExprToType(rex, EltTy, CK_IntegralCast);
5950 if (order >= 0) {
5951 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005952 if (swapped) std::swap(rex, lex);
5953 return lhsType;
5954 }
5955 }
5956 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5957 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005958 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
5959 if (order > 0)
5960 ImpCastExprToType(rex, EltTy, CK_FloatingCast);
5961 if (order >= 0) {
5962 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005963 if (swapped) std::swap(rex, lex);
5964 return lhsType;
5965 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005966 }
5967 }
Mike Stump11289f42009-09-09 15:08:12 +00005968
Nate Begeman886448d2009-06-28 19:12:57 +00005969 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00005970 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005971 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00005972 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005973 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005974}
5975
Chris Lattnerfaa54172010-01-12 21:23:57 +00005976QualType Sema::CheckMultiplyDivideOperands(
5977 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00005978 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005979 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005980
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005981 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005982
Chris Lattnerfaa54172010-01-12 21:23:57 +00005983 if (!lex->getType()->isArithmeticType() ||
5984 !rex->getType()->isArithmeticType())
5985 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005986
Chris Lattnerfaa54172010-01-12 21:23:57 +00005987 // Check for division by zero.
5988 if (isDiv &&
5989 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005990 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
Chris Lattner70117952010-01-12 21:30:55 +00005991 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005992
Chris Lattnerfaa54172010-01-12 21:23:57 +00005993 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005994}
5995
Chris Lattnerfaa54172010-01-12 21:23:57 +00005996QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00005997 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005998 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005999 if (lex->getType()->hasIntegerRepresentation() &&
6000 rex->getType()->hasIntegerRepresentation())
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006001 return CheckVectorOperands(Loc, lex, rex);
6002 return InvalidOperands(Loc, lex, rex);
6003 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006004
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006005 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006006
Chris Lattnerfaa54172010-01-12 21:23:57 +00006007 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
6008 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006009
Chris Lattnerfaa54172010-01-12 21:23:57 +00006010 // Check for remainder by zero.
6011 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattner70117952010-01-12 21:30:55 +00006012 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
6013 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006014
Chris Lattnerfaa54172010-01-12 21:23:57 +00006015 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006016}
6017
Chris Lattnerfaa54172010-01-12 21:23:57 +00006018QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00006019 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006020 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6021 QualType compType = CheckVectorOperands(Loc, lex, rex);
6022 if (CompLHSTy) *CompLHSTy = compType;
6023 return compType;
6024 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006025
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006026 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006027
Steve Naroffe4718892007-04-27 18:30:00 +00006028 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006029 if (lex->getType()->isArithmeticType() &&
6030 rex->getType()->isArithmeticType()) {
6031 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006032 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006033 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006034
Eli Friedman8e122982008-05-18 18:08:51 +00006035 // Put any potential pointer into PExp
6036 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00006037 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006038 std::swap(PExp, IExp);
6039
Steve Naroff6b712a72009-07-14 18:25:06 +00006040 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006041
Eli Friedman8e122982008-05-18 18:08:51 +00006042 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006043 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006044
Chris Lattner12bdebb2009-04-24 23:50:08 +00006045 // Check for arithmetic on pointers to incomplete types.
6046 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006047 if (getLangOptions().CPlusPlus) {
6048 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00006049 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00006050 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006051 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006052
6053 // GNU extension: arithmetic on pointer to void
6054 Diag(Loc, diag::ext_gnu_void_ptr)
6055 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00006056 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006057 if (getLangOptions().CPlusPlus) {
6058 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6059 << lex->getType() << lex->getSourceRange();
6060 return QualType();
6061 }
6062
6063 // GNU extension: arithmetic on pointer to function
6064 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6065 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00006066 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006067 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00006068 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00006069 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006070 PExp->getType()->isObjCObjectPointerType()) &&
6071 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00006072 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6073 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006074 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006075 return QualType();
6076 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00006077 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006078 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006079 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6080 << PointeeTy << PExp->getSourceRange();
6081 return QualType();
6082 }
Mike Stump11289f42009-09-09 15:08:12 +00006083
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006084 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00006085 QualType LHSTy = Context.isPromotableBitField(lex);
6086 if (LHSTy.isNull()) {
6087 LHSTy = lex->getType();
6088 if (LHSTy->isPromotableIntegerType())
6089 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00006090 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006091 *CompLHSTy = LHSTy;
6092 }
Eli Friedman8e122982008-05-18 18:08:51 +00006093 return PExp->getType();
6094 }
6095 }
6096
Chris Lattner326f7572008-11-18 01:30:42 +00006097 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006098}
6099
Chris Lattner2a3569b2008-04-07 05:30:13 +00006100// C99 6.5.6
6101QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006102 SourceLocation Loc, QualType* CompLHSTy) {
6103 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6104 QualType compType = CheckVectorOperands(Loc, lex, rex);
6105 if (CompLHSTy) *CompLHSTy = compType;
6106 return compType;
6107 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006108
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006109 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006110
Chris Lattner4d62f422007-12-09 21:53:25 +00006111 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006112
Chris Lattner4d62f422007-12-09 21:53:25 +00006113 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00006114 if (lex->getType()->isArithmeticType()
6115 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006116 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006117 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006118 }
Mike Stump11289f42009-09-09 15:08:12 +00006119
Chris Lattner4d62f422007-12-09 21:53:25 +00006120 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00006121 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00006122 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006123
Douglas Gregorac1fb652009-03-24 19:52:54 +00006124 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006125
Douglas Gregorac1fb652009-03-24 19:52:54 +00006126 bool ComplainAboutVoid = false;
6127 Expr *ComplainAboutFunc = 0;
6128 if (lpointee->isVoidType()) {
6129 if (getLangOptions().CPlusPlus) {
6130 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6131 << lex->getSourceRange() << rex->getSourceRange();
6132 return QualType();
6133 }
6134
6135 // GNU C extension: arithmetic on pointer to void
6136 ComplainAboutVoid = true;
6137 } else if (lpointee->isFunctionType()) {
6138 if (getLangOptions().CPlusPlus) {
6139 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006140 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006141 return QualType();
6142 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006143
6144 // GNU C extension: arithmetic on pointer to function
6145 ComplainAboutFunc = lex;
6146 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00006147 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006148 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00006149 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006150 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006151 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006152
Chris Lattner12bdebb2009-04-24 23:50:08 +00006153 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006154 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006155 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6156 << lpointee << lex->getSourceRange();
6157 return QualType();
6158 }
Mike Stump11289f42009-09-09 15:08:12 +00006159
Chris Lattner4d62f422007-12-09 21:53:25 +00006160 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00006161 if (rex->getType()->isIntegerType()) {
6162 if (ComplainAboutVoid)
6163 Diag(Loc, diag::ext_gnu_void_ptr)
6164 << lex->getSourceRange() << rex->getSourceRange();
6165 if (ComplainAboutFunc)
6166 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006167 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006168 << ComplainAboutFunc->getSourceRange();
6169
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006170 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006171 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006172 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006173
Chris Lattner4d62f422007-12-09 21:53:25 +00006174 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006175 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006176 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006177
Douglas Gregorac1fb652009-03-24 19:52:54 +00006178 // RHS must be a completely-type object type.
6179 // Handle the GNU void* extension.
6180 if (rpointee->isVoidType()) {
6181 if (getLangOptions().CPlusPlus) {
6182 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6183 << lex->getSourceRange() << rex->getSourceRange();
6184 return QualType();
6185 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006186
Douglas Gregorac1fb652009-03-24 19:52:54 +00006187 ComplainAboutVoid = true;
6188 } else if (rpointee->isFunctionType()) {
6189 if (getLangOptions().CPlusPlus) {
6190 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006191 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006192 return QualType();
6193 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006194
6195 // GNU extension: arithmetic on pointer to function
6196 if (!ComplainAboutFunc)
6197 ComplainAboutFunc = rex;
6198 } else if (!rpointee->isDependentType() &&
6199 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006200 PDiag(diag::err_typecheck_sub_ptr_object)
6201 << rex->getSourceRange()
6202 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006203 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006204
Eli Friedman168fe152009-05-16 13:54:38 +00006205 if (getLangOptions().CPlusPlus) {
6206 // Pointee types must be the same: C++ [expr.add]
6207 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6208 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6209 << lex->getType() << rex->getType()
6210 << lex->getSourceRange() << rex->getSourceRange();
6211 return QualType();
6212 }
6213 } else {
6214 // Pointee types must be compatible C99 6.5.6p3
6215 if (!Context.typesAreCompatible(
6216 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6217 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6218 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6219 << lex->getType() << rex->getType()
6220 << lex->getSourceRange() << rex->getSourceRange();
6221 return QualType();
6222 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006223 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006224
Douglas Gregorac1fb652009-03-24 19:52:54 +00006225 if (ComplainAboutVoid)
6226 Diag(Loc, diag::ext_gnu_void_ptr)
6227 << lex->getSourceRange() << rex->getSourceRange();
6228 if (ComplainAboutFunc)
6229 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006230 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006231 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006232
6233 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006234 return Context.getPointerDiffType();
6235 }
6236 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006237
Chris Lattner326f7572008-11-18 01:30:42 +00006238 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006239}
6240
Douglas Gregor0bf31402010-10-08 23:50:27 +00006241static bool isScopedEnumerationType(QualType T) {
6242 if (const EnumType *ET = dyn_cast<EnumType>(T))
6243 return ET->getDecl()->isScoped();
6244 return false;
6245}
6246
Chris Lattner2a3569b2008-04-07 05:30:13 +00006247// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00006248QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattner2a3569b2008-04-07 05:30:13 +00006249 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00006250 // C99 6.5.7p2: Each of the operands shall have integer type.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006251 if (!lex->getType()->hasIntegerRepresentation() ||
6252 !rex->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006253 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006254
Douglas Gregor0bf31402010-10-08 23:50:27 +00006255 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6256 // hasIntegerRepresentation() above instead of this.
6257 if (isScopedEnumerationType(lex->getType()) ||
6258 isScopedEnumerationType(rex->getType())) {
6259 return InvalidOperands(Loc, lex, rex);
6260 }
6261
Nate Begemane46ee9a2009-10-25 02:26:48 +00006262 // Vector shifts promote their scalar inputs to vector type.
6263 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6264 return CheckVectorOperands(Loc, lex, rex);
6265
Chris Lattner5c11c412007-12-12 05:47:28 +00006266 // Shifts don't perform usual arithmetic conversions, they just do integer
6267 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006268
John McCall57cdd882010-12-16 19:28:59 +00006269 // For the LHS, do usual unary conversions, but then reset them away
6270 // if this is a compound assignment.
6271 Expr *old_lex = lex;
6272 UsualUnaryConversions(lex);
6273 QualType LHSTy = lex->getType();
6274 if (isCompAssign) lex = old_lex;
6275
6276 // The RHS is simpler.
Chris Lattner5c11c412007-12-12 05:47:28 +00006277 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006278
Ryan Flynnf53fab82009-08-07 16:20:20 +00006279 // Sanity-check shift operands
6280 llvm::APSInt Right;
6281 // Check right/shifter operand
Daniel Dunbar687fa862009-09-17 06:31:27 +00006282 if (!rex->isValueDependent() &&
6283 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn2f085712009-08-08 19:18:23 +00006284 if (Right.isNegative())
Ryan Flynnf53fab82009-08-07 16:20:20 +00006285 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
6286 else {
6287 llvm::APInt LeftBits(Right.getBitWidth(),
6288 Context.getTypeSize(lex->getType()));
6289 if (Right.uge(LeftBits))
6290 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
6291 }
6292 }
6293
Chris Lattner5c11c412007-12-12 05:47:28 +00006294 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006295 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006296}
6297
Chandler Carruth17773fc2010-07-10 12:30:03 +00006298static bool IsWithinTemplateSpecialization(Decl *D) {
6299 if (DeclContext *DC = D->getDeclContext()) {
6300 if (isa<ClassTemplateSpecializationDecl>(DC))
6301 return true;
6302 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6303 return FD->isFunctionTemplateSpecialization();
6304 }
6305 return false;
6306}
6307
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006308// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00006309QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006310 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00006311 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006312
Chris Lattner9a152e22009-12-05 05:40:13 +00006313 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00006314 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006315 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006316
Steve Naroff31090012007-07-16 21:54:35 +00006317 QualType lType = lex->getType();
6318 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006319
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006320 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00006321 !(lType->isBlockPointerType() && isRelational) &&
6322 !lex->getLocStart().isMacroID() &&
6323 !rex->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006324 // For non-floating point types, check for self-comparisons of the form
6325 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6326 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006327 //
6328 // NOTE: Don't warn about comparison expressions resulting from macro
6329 // expansion. Also don't warn about comparisons which are only self
6330 // comparisons within a template specialization. The warnings should catch
6331 // obvious cases in the definition of the template anyways. The idea is to
6332 // warn when the typed comparison operator will always evaluate to the same
6333 // result.
John McCall34376a62010-12-04 03:47:34 +00006334 Expr *LHSStripped = lex->IgnoreParenImpCasts();
6335 Expr *RHSStripped = rex->IgnoreParenImpCasts();
Chandler Carruth17773fc2010-07-10 12:30:03 +00006336 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006337 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006338 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006339 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006340 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6341 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006342 << (Opc == BO_EQ
6343 || Opc == BO_LE
6344 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00006345 } else if (lType->isArrayType() && rType->isArrayType() &&
6346 !DRL->getDecl()->getType()->isReferenceType() &&
6347 !DRR->getDecl()->getType()->isReferenceType()) {
6348 // what is it always going to eval to?
6349 char always_evals_to;
6350 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006351 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006352 always_evals_to = 0; // false
6353 break;
John McCalle3027922010-08-25 11:45:40 +00006354 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006355 always_evals_to = 1; // true
6356 break;
6357 default:
6358 // best we can say is 'a constant'
6359 always_evals_to = 2; // e.g. array1 <= array2
6360 break;
6361 }
6362 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6363 << 1 // array
6364 << always_evals_to);
6365 }
6366 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006367 }
Mike Stump11289f42009-09-09 15:08:12 +00006368
Chris Lattner222b8bd2009-03-08 19:39:53 +00006369 if (isa<CastExpr>(LHSStripped))
6370 LHSStripped = LHSStripped->IgnoreParenCasts();
6371 if (isa<CastExpr>(RHSStripped))
6372 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006373
Chris Lattner222b8bd2009-03-08 19:39:53 +00006374 // Warn about comparisons against a string constant (unless the other
6375 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006376 Expr *literalString = 0;
6377 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006378 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006379 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006380 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006381 literalString = lex;
6382 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006383 } else if ((isa<StringLiteral>(RHSStripped) ||
6384 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006385 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006386 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006387 literalString = rex;
6388 literalStringStripped = RHSStripped;
6389 }
6390
6391 if (literalString) {
6392 std::string resultComparison;
6393 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006394 case BO_LT: resultComparison = ") < 0"; break;
6395 case BO_GT: resultComparison = ") > 0"; break;
6396 case BO_LE: resultComparison = ") <= 0"; break;
6397 case BO_GE: resultComparison = ") >= 0"; break;
6398 case BO_EQ: resultComparison = ") == 0"; break;
6399 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006400 default: assert(false && "Invalid comparison operator");
6401 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006402
Douglas Gregor49862b82010-01-12 23:18:54 +00006403 DiagRuntimeBehavior(Loc,
6404 PDiag(diag::warn_stringcompare)
6405 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006406 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006407 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006408 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006409
Douglas Gregorec170db2010-06-08 19:50:34 +00006410 // C99 6.5.8p3 / C99 6.5.9p4
6411 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
6412 UsualArithmeticConversions(lex, rex);
6413 else {
6414 UsualUnaryConversions(lex);
6415 UsualUnaryConversions(rex);
6416 }
6417
6418 lType = lex->getType();
6419 rType = rex->getType();
6420
Douglas Gregorca63811b2008-11-19 03:25:36 +00006421 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner9a152e22009-12-05 05:40:13 +00006422 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregorca63811b2008-11-19 03:25:36 +00006423
Chris Lattnerb620c342007-08-26 01:18:55 +00006424 if (isRelational) {
6425 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006426 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006427 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006428 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006429 if (lType->hasFloatingRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006430 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006431
Chris Lattnerb620c342007-08-26 01:18:55 +00006432 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006433 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006434 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006435
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006436 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006437 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006438 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006439 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006440
Douglas Gregorf267edd2010-06-15 21:38:40 +00006441 // All of the following pointer-related warnings are GCC extensions, except
6442 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00006443 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006444 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006445 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00006446 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006447 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006448
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006449 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006450 if (LCanPointeeTy == RCanPointeeTy)
6451 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006452 if (!isRelational &&
6453 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6454 // Valid unless comparison between non-null pointer and function pointer
6455 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006456 // In a SFINAE context, we treat this as a hard error to maintain
6457 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006458 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6459 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00006460 Diag(Loc,
6461 isSFINAEContext()?
6462 diag::err_typecheck_comparison_of_fptr_to_void
6463 : diag::ext_typecheck_comparison_of_fptr_to_void)
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006464 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006465
6466 if (isSFINAEContext())
6467 return QualType();
6468
John McCalle3027922010-08-25 11:45:40 +00006469 ImpCastExprToType(rex, lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006470 return ResultTy;
6471 }
6472 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006473
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006474 // C++ [expr.rel]p2:
6475 // [...] Pointer conversions (4.10) and qualification
6476 // conversions (4.4) are performed on pointer operands (or on
6477 // a pointer operand and a null pointer constant) to bring
6478 // them to their composite pointer type. [...]
6479 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006480 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006481 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006482 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006483 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006484 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006485 if (T.isNull()) {
6486 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6487 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6488 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006489 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006490 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006491 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006492 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006493 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006494 }
6495
John McCalle3027922010-08-25 11:45:40 +00006496 ImpCastExprToType(lex, T, CK_BitCast);
6497 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006498 return ResultTy;
6499 }
Eli Friedman16c209612009-08-23 00:27:47 +00006500 // C99 6.5.9p2 and C99 6.5.8p2
6501 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6502 RCanPointeeTy.getUnqualifiedType())) {
6503 // Valid unless a relational comparison of function pointers
6504 if (isRelational && LCanPointeeTy->isFunctionType()) {
6505 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
6506 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6507 }
6508 } else if (!isRelational &&
6509 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6510 // Valid unless comparison between non-null pointer and function pointer
6511 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6512 && !LHSIsNull && !RHSIsNull) {
6513 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
6514 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6515 }
6516 } else {
6517 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00006518 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006519 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00006520 }
Eli Friedman16c209612009-08-23 00:27:47 +00006521 if (LCanPointeeTy != RCanPointeeTy)
John McCalle3027922010-08-25 11:45:40 +00006522 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006523 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006524 }
Mike Stump11289f42009-09-09 15:08:12 +00006525
Sebastian Redl576fd422009-05-10 18:38:11 +00006526 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006527 // Comparison of nullptr_t with itself.
6528 if (lType->isNullPtrType() && rType->isNullPtrType())
6529 return ResultTy;
6530
Mike Stump11289f42009-09-09 15:08:12 +00006531 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006532 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006533 if (RHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00006534 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006535 (!isRelational && lType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00006536 ImpCastExprToType(rex, lType,
6537 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006538 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006539 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006540 return ResultTy;
6541 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006542 if (LHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00006543 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006544 (!isRelational && rType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00006545 ImpCastExprToType(lex, rType,
6546 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006547 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006548 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006549 return ResultTy;
6550 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006551
6552 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00006553 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006554 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6555 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006556 // In addition, pointers to members can be compared, or a pointer to
6557 // member and a null pointer constant. Pointer to member conversions
6558 // (4.11) and qualification conversions (4.4) are performed to bring
6559 // them to a common type. If one operand is a null pointer constant,
6560 // the common type is the type of the other operand. Otherwise, the
6561 // common type is a pointer to member type similar (4.4) to the type
6562 // of one of the operands, with a cv-qualification signature (4.4)
6563 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006564 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006565 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006566 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006567 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006568 if (T.isNull()) {
6569 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006570 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006571 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006572 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006573 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006574 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006575 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006576 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006577 }
Mike Stump11289f42009-09-09 15:08:12 +00006578
John McCalle3027922010-08-25 11:45:40 +00006579 ImpCastExprToType(lex, T, CK_BitCast);
6580 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006581 return ResultTy;
6582 }
Sebastian Redl576fd422009-05-10 18:38:11 +00006583 }
Mike Stump11289f42009-09-09 15:08:12 +00006584
Steve Naroff081c7422008-09-04 15:10:53 +00006585 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00006586 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006587 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6588 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006589
Steve Naroff081c7422008-09-04 15:10:53 +00006590 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006591 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006592 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006593 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006594 }
John McCalle3027922010-08-25 11:45:40 +00006595 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006596 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006597 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00006598 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00006599 if (!isRelational
6600 && ((lType->isBlockPointerType() && rType->isPointerType())
6601 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006602 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006603 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006604 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006605 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006606 ->getPointeeType()->isVoidType())))
6607 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
6608 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006609 }
John McCalle3027922010-08-25 11:45:40 +00006610 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006611 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006612 }
Steve Naroff081c7422008-09-04 15:10:53 +00006613
Steve Naroff7cae42b2009-07-10 23:34:53 +00006614 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006615 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006616 const PointerType *LPT = lType->getAs<PointerType>();
6617 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006618 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00006619 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006620 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00006621 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006622
Steve Naroff753567f2008-11-17 19:49:16 +00006623 if (!LPtrToVoid && !RPtrToVoid &&
6624 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006625 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006626 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006627 }
John McCalle3027922010-08-25 11:45:40 +00006628 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006629 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006630 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006631 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006632 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006633 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
6634 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006635 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006636 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006637 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006638 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006639 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6640 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006641 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006642 bool isError = false;
6643 if ((LHSIsNull && lType->isIntegerType()) ||
6644 (RHSIsNull && rType->isIntegerType())) {
6645 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006646 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006647 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006648 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006649 else if (getLangOptions().CPlusPlus) {
6650 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6651 isError = true;
6652 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006653 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006654
Chris Lattnerd99bd522009-08-23 00:03:44 +00006655 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006656 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00006657 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006658 if (isError)
6659 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006660 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006661
6662 if (lType->isIntegerType())
John McCalle84af4e2010-11-13 01:35:44 +00006663 ImpCastExprToType(lex, rType,
6664 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006665 else
John McCalle84af4e2010-11-13 01:35:44 +00006666 ImpCastExprToType(rex, lType,
6667 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006668 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006669 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006670
Steve Naroff4b191572008-09-04 16:56:14 +00006671 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00006672 if (!isRelational && RHSIsNull
6673 && lType->isBlockPointerType() && rType->isIntegerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00006674 ImpCastExprToType(rex, lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006675 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006676 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00006677 if (!isRelational && LHSIsNull
6678 && lType->isIntegerType() && rType->isBlockPointerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00006679 ImpCastExprToType(lex, rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006680 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006681 }
Chris Lattner326f7572008-11-18 01:30:42 +00006682 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006683}
6684
Nate Begeman191a6b12008-07-14 18:02:46 +00006685/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006686/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006687/// like a scalar comparison, a vector comparison produces a vector of integer
6688/// types.
6689QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00006690 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00006691 bool isRelational) {
6692 // Check to make sure we're operating on vectors of the same type and width,
6693 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00006694 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00006695 if (vType.isNull())
6696 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006697
Anton Yartsev3f8f2882010-11-18 03:19:30 +00006698 // If AltiVec, the comparison results in a numeric type, i.e.
6699 // bool for C++, int for C
6700 if (getLangOptions().AltiVec)
6701 return (getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy);
6702
Nate Begeman191a6b12008-07-14 18:02:46 +00006703 QualType lType = lex->getType();
6704 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006705
Nate Begeman191a6b12008-07-14 18:02:46 +00006706 // For non-floating point types, check for self-comparisons of the form
6707 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6708 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006709 if (!lType->hasFloatingRepresentation()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006710 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
6711 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
6712 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregorec170db2010-06-08 19:50:34 +00006713 DiagRuntimeBehavior(Loc,
6714 PDiag(diag::warn_comparison_always)
6715 << 0 // self-
6716 << 2 // "a constant"
6717 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006718 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006719
Nate Begeman191a6b12008-07-14 18:02:46 +00006720 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006721 if (!isRelational && lType->hasFloatingRepresentation()) {
6722 assert (rType->hasFloatingRepresentation());
Chris Lattner326f7572008-11-18 01:30:42 +00006723 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00006724 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006725
Nate Begeman191a6b12008-07-14 18:02:46 +00006726 // Return the type for the comparison, which is the same as vector type for
6727 // integer vectors, or an integer type of identical size and number of
6728 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006729 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00006730 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006731
John McCall9dd450b2009-09-21 23:43:11 +00006732 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00006733 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006734 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00006735 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00006736 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006737 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6738
Mike Stump4e1f26a2009-02-19 03:04:26 +00006739 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006740 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00006741 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6742}
6743
Steve Naroff218bc2b2007-05-04 21:54:46 +00006744inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00006745 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006746 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6747 if (lex->getType()->hasIntegerRepresentation() &&
6748 rex->getType()->hasIntegerRepresentation())
6749 return CheckVectorOperands(Loc, lex, rex);
6750
6751 return InvalidOperands(Loc, lex, rex);
6752 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006753
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006754 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006755
Douglas Gregor0bf31402010-10-08 23:50:27 +00006756 if (lex->getType()->isIntegralOrUnscopedEnumerationType() &&
6757 rex->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006758 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00006759 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006760}
6761
Steve Naroff218bc2b2007-05-04 21:54:46 +00006762inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner8406c512010-07-13 19:41:32 +00006763 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
6764
6765 // Diagnose cases where the user write a logical and/or but probably meant a
6766 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6767 // is a constant.
6768 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
Eli Friedman6b197e02010-07-27 19:14:53 +00006769 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
Chris Lattnerdeee7a32010-07-15 00:26:43 +00006770 // Don't warn in macros.
Chris Lattner938533d2010-07-24 01:10:11 +00006771 !Loc.isMacroID()) {
6772 // If the RHS can be constant folded, and if it constant folds to something
6773 // that isn't 0 or 1 (which indicate a potential logical operation that
6774 // happened to fold to true/false) then warn.
6775 Expr::EvalResult Result;
6776 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
6777 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
6778 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6779 << rex->getSourceRange()
John McCalle3027922010-08-25 11:45:40 +00006780 << (Opc == BO_LAnd ? "&&" : "||")
6781 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00006782 }
6783 }
Chris Lattner8406c512010-07-13 19:41:32 +00006784
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006785 if (!Context.getLangOptions().CPlusPlus) {
6786 UsualUnaryConversions(lex);
6787 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006788
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006789 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
6790 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006791
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006792 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00006793 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006794
John McCall4a2429a2010-06-04 00:29:51 +00006795 // The following is safe because we only use this method for
6796 // non-overloadable operands.
6797
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006798 // C++ [expr.log.and]p1
6799 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00006800 // The operands are both contextually converted to type bool.
6801 if (PerformContextuallyConvertToBool(lex) ||
6802 PerformContextuallyConvertToBool(rex))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006803 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006804
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006805 // C++ [expr.log.and]p2
6806 // C++ [expr.log.or]p2
6807 // The result is a bool.
6808 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00006809}
6810
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006811/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6812/// is a read-only property; return true if so. A readonly property expression
6813/// depends on various declarations and thus must be treated specially.
6814///
Mike Stump11289f42009-09-09 15:08:12 +00006815static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006816 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6817 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00006818 if (PropExpr->isImplicitProperty()) return false;
6819
6820 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6821 QualType BaseType = PropExpr->isSuperReceiver() ?
6822 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00006823 PropExpr->getBase()->getType();
6824
John McCallb7bd14f2010-12-02 01:19:52 +00006825 if (const ObjCObjectPointerType *OPT =
6826 BaseType->getAsObjCInterfacePointerType())
6827 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6828 if (S.isPropertyReadonly(PDecl, IFace))
6829 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006830 }
6831 return false;
6832}
6833
Chris Lattner30bd3272008-11-18 01:22:49 +00006834/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6835/// emit an error and return true. If so, return false.
6836static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006837 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00006838 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006839 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006840 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6841 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00006842 if (IsLV == Expr::MLV_Valid)
6843 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006844
Chris Lattner30bd3272008-11-18 01:22:49 +00006845 unsigned Diag = 0;
6846 bool NeedType = false;
6847 switch (IsLV) { // C99 6.5.16p2
Chris Lattner30bd3272008-11-18 01:22:49 +00006848 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006849 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006850 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6851 NeedType = true;
6852 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006853 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006854 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6855 NeedType = true;
6856 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00006857 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00006858 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6859 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006860 case Expr::MLV_Valid:
6861 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00006862 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006863 case Expr::MLV_MemberFunction:
6864 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00006865 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6866 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006867 case Expr::MLV_IncompleteType:
6868 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00006869 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006870 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00006871 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00006872 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00006873 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6874 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00006875 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00006876 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6877 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00006878 case Expr::MLV_ReadonlyProperty:
6879 Diag = diag::error_readonly_property_assignment;
6880 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00006881 case Expr::MLV_NoSetterProperty:
6882 Diag = diag::error_nosetter_property_assignment;
6883 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00006884 case Expr::MLV_SubObjCPropertySetting:
6885 Diag = diag::error_no_subobject_property_setting;
6886 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006887 }
Steve Naroffad373bd2007-07-31 12:34:36 +00006888
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006889 SourceRange Assign;
6890 if (Loc != OrigLoc)
6891 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00006892 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006893 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006894 else
Mike Stump11289f42009-09-09 15:08:12 +00006895 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006896 return true;
6897}
6898
6899
6900
6901// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00006902QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
6903 SourceLocation Loc,
6904 QualType CompoundType) {
6905 // Verify that LHS is a modifiable lvalue, and emit error if not.
6906 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00006907 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00006908
6909 QualType LHSType = LHS->getType();
6910 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006911 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00006912 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006913 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006914 // Simple assignment "x = y".
John McCall34376a62010-12-04 03:47:34 +00006915 if (LHS->getObjectKind() == OK_ObjCProperty)
6916 ConvertPropertyForLValue(LHS, RHS, LHSTy);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006917 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006918 // Special case of NSObject attributes on c-style pointer types.
6919 if (ConvTy == IncompatiblePointer &&
6920 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006921 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006922 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006923 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006924 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006925
John McCall7decc9e2010-11-18 06:31:45 +00006926 if (ConvTy == Compatible &&
6927 getLangOptions().ObjCNonFragileABI &&
6928 LHSType->isObjCObjectType())
6929 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
6930 << LHSType;
6931
Chris Lattnerea714382008-08-21 18:04:13 +00006932 // If the RHS is a unary plus or minus, check to see if they = and + are
6933 // right next to each other. If so, the user may have typo'd "x =+ 4"
6934 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00006935 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00006936 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
6937 RHSCheck = ICE->getSubExpr();
6938 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00006939 if ((UO->getOpcode() == UO_Plus ||
6940 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00006941 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00006942 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00006943 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
6944 // And there is a space or other character before the subexpr of the
6945 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00006946 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
6947 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00006948 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00006949 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00006950 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00006951 }
Chris Lattnerea714382008-08-21 18:04:13 +00006952 }
6953 } else {
6954 // Compound assignment "x += y"
John McCall29600e12010-11-16 02:32:08 +00006955 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006956 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00006957
Chris Lattner326f7572008-11-18 01:30:42 +00006958 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006959 RHS, AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00006960 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006961
Chris Lattner39561062010-07-07 06:14:23 +00006962
6963 // Check to see if the destination operand is a dereferenced null pointer. If
6964 // so, and if not volatile-qualified, this is undefined behavior that the
6965 // optimizer will delete, so warn about it. People sometimes try to use this
6966 // to get a deterministic trap and are surprised by clang's behavior. This
6967 // only handles the pattern "*null = whatever", which is a very syntactic
6968 // check.
6969 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
John McCalle3027922010-08-25 11:45:40 +00006970 if (UO->getOpcode() == UO_Deref &&
Chris Lattner39561062010-07-07 06:14:23 +00006971 UO->getSubExpr()->IgnoreParenCasts()->
6972 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
6973 !UO->getType().isVolatileQualified()) {
6974 Diag(UO->getOperatorLoc(), diag::warn_indirection_through_null)
6975 << UO->getSubExpr()->getSourceRange();
6976 Diag(UO->getOperatorLoc(), diag::note_indirection_through_null);
6977 }
6978
Steve Naroff98cf3e92007-06-06 18:38:38 +00006979 // C99 6.5.16p3: The type of an assignment expression is the type of the
6980 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00006981 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00006982 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
6983 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00006984 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00006985 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00006986 return (getLangOptions().CPlusPlus
6987 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00006988}
6989
Chris Lattner326f7572008-11-18 01:30:42 +00006990// C99 6.5.17
John McCall34376a62010-12-04 03:47:34 +00006991static QualType CheckCommaOperands(Sema &S, Expr *&LHS, Expr *&RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00006992 SourceLocation Loc) {
6993 S.DiagnoseUnusedExprResult(LHS);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00006994
John McCall4bc41ae2010-11-18 19:01:18 +00006995 ExprResult LHSResult = S.CheckPlaceholderExpr(LHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00006996 if (LHSResult.isInvalid())
6997 return QualType();
6998
John McCall4bc41ae2010-11-18 19:01:18 +00006999 ExprResult RHSResult = S.CheckPlaceholderExpr(RHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007000 if (RHSResult.isInvalid())
7001 return QualType();
7002 RHS = RHSResult.take();
7003
John McCall73d36182010-10-12 07:14:40 +00007004 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7005 // operands, but not unary promotions.
7006 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007007
John McCall34376a62010-12-04 03:47:34 +00007008 // So we treat the LHS as a ignored value, and in C++ we allow the
7009 // containing site to determine what should be done with the RHS.
7010 S.IgnoredValueConversions(LHS);
7011
7012 if (!S.getLangOptions().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007013 S.DefaultFunctionArrayLvalueConversion(RHS);
John McCall73d36182010-10-12 07:14:40 +00007014 if (!RHS->getType()->isVoidType())
John McCall4bc41ae2010-11-18 19:01:18 +00007015 S.RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007016 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007017
Chris Lattner326f7572008-11-18 01:30:42 +00007018 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007019}
7020
Steve Naroff7a5af782007-07-13 16:58:59 +00007021/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7022/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007023static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7024 ExprValueKind &VK,
7025 SourceLocation OpLoc,
7026 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007027 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007028 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007029
Chris Lattner6b0cf142008-11-21 07:05:48 +00007030 QualType ResType = Op->getType();
7031 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007032
John McCall4bc41ae2010-11-18 19:01:18 +00007033 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007034 // Decrement of bool is not allowed.
7035 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007036 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007037 return QualType();
7038 }
7039 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007040 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007041 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007042 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007043 } else if (ResType->isAnyPointerType()) {
7044 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00007045
Chris Lattner6b0cf142008-11-21 07:05:48 +00007046 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00007047 if (PointeeTy->isVoidType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007048 if (S.getLangOptions().CPlusPlus) {
7049 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007050 << Op->getSourceRange();
7051 return QualType();
7052 }
7053
7054 // Pointer to void is a GNU extension in C.
John McCall4bc41ae2010-11-18 19:01:18 +00007055 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00007056 } else if (PointeeTy->isFunctionType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007057 if (S.getLangOptions().CPlusPlus) {
7058 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007059 << Op->getType() << Op->getSourceRange();
7060 return QualType();
7061 }
7062
John McCall4bc41ae2010-11-18 19:01:18 +00007063 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007064 << ResType << Op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007065 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
7066 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00007067 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00007068 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00007069 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007070 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00007071 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7072 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007073 << PointeeTy << Op->getSourceRange();
7074 return QualType();
7075 }
Eli Friedman090addd2010-01-03 00:20:48 +00007076 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007077 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007078 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007079 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007080 } else if (ResType->isPlaceholderType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007081 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007082 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007083 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7084 isInc, isPrefix);
Chris Lattner6b0cf142008-11-21 07:05:48 +00007085 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007086 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00007087 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007088 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007089 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007090 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007091 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007092 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007093 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007094 // In C++, a prefix increment is the same type as the operand. Otherwise
7095 // (in C or with postfix), the increment is the unqualified type of the
7096 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00007097 if (isPrefix && S.getLangOptions().CPlusPlus) {
7098 VK = VK_LValue;
7099 return ResType;
7100 } else {
7101 VK = VK_RValue;
7102 return ResType.getUnqualifiedType();
7103 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007104}
7105
John McCall34376a62010-12-04 03:47:34 +00007106void Sema::ConvertPropertyForRValue(Expr *&E) {
7107 assert(E->getValueKind() == VK_LValue &&
7108 E->getObjectKind() == OK_ObjCProperty);
7109 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7110
7111 ExprValueKind VK = VK_RValue;
7112 if (PRE->isImplicitProperty()) {
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007113 if (const ObjCMethodDecl *GetterMethod =
7114 PRE->getImplicitPropertyGetter()) {
7115 QualType Result = GetterMethod->getResultType();
7116 VK = Expr::getValueKindForType(Result);
7117 }
7118 else {
7119 Diag(PRE->getLocation(), diag::err_getter_not_found)
7120 << PRE->getBase()->getType();
7121 }
John McCall34376a62010-12-04 03:47:34 +00007122 }
7123
7124 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
7125 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007126
7127 ExprResult Result = MaybeBindToTemporary(E);
7128 if (!Result.isInvalid())
7129 E = Result.take();
John McCall34376a62010-12-04 03:47:34 +00007130}
7131
7132void Sema::ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType &LHSTy) {
7133 assert(LHS->getValueKind() == VK_LValue &&
7134 LHS->getObjectKind() == OK_ObjCProperty);
7135 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7136
7137 if (PRE->isImplicitProperty()) {
7138 // If using property-dot syntax notation for assignment, and there is a
7139 // setter, RHS expression is being passed to the setter argument. So,
7140 // type conversion (and comparison) is RHS to setter's argument type.
7141 if (const ObjCMethodDecl *SetterMD = PRE->getImplicitPropertySetter()) {
7142 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7143 LHSTy = (*P)->getType();
7144
7145 // Otherwise, if the getter returns an l-value, just call that.
7146 } else {
7147 QualType Result = PRE->getImplicitPropertyGetter()->getResultType();
7148 ExprValueKind VK = Expr::getValueKindForType(Result);
7149 if (VK == VK_LValue) {
7150 LHS = ImplicitCastExpr::Create(Context, LHS->getType(),
7151 CK_GetObjCProperty, LHS, 0, VK);
7152 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007153 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007154 }
John McCall34376a62010-12-04 03:47:34 +00007155 }
7156
7157 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007158 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007159 InitializedEntity::InitializeParameter(Context, LHSTy);
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007160 Expr *Arg = RHS;
7161 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(),
7162 Owned(Arg));
7163 if (!ArgE.isInvalid())
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007164 RHS = ArgE.takeAs<Expr>();
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007165 }
7166}
7167
7168
Anders Carlsson806700f2008-02-01 07:15:58 +00007169/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007170/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007171/// where the declaration is needed for type checking. We only need to
7172/// handle cases when the expression references a function designator
7173/// or is an lvalue. Here are some examples:
7174/// - &(x) => x
7175/// - &*****f => f for f a function designator.
7176/// - &s.xx => s
7177/// - &s.zz[1].yy -> s, if zz is an array
7178/// - *(x + 1) -> x, if x is an array
7179/// - &"123"[2] -> 0
7180/// - & __real__ x -> x
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007181static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007182 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007183 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007184 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007185 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007186 // If this is an arrow operator, the address is an offset from
7187 // the base's value, so the object the base refers to is
7188 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007189 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007190 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007191 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007192 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007193 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007194 // FIXME: This code shouldn't be necessary! We should catch the implicit
7195 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007196 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7197 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7198 if (ICE->getSubExpr()->getType()->isArrayType())
7199 return getPrimaryDecl(ICE->getSubExpr());
7200 }
7201 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007202 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007203 case Stmt::UnaryOperatorClass: {
7204 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007205
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007206 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007207 case UO_Real:
7208 case UO_Imag:
7209 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007210 return getPrimaryDecl(UO->getSubExpr());
7211 default:
7212 return 0;
7213 }
7214 }
Steve Naroff47500512007-04-19 23:00:49 +00007215 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007216 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007217 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007218 // If the result of an implicit cast is an l-value, we care about
7219 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007220 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007221 default:
7222 return 0;
7223 }
7224}
7225
7226/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007227/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007228/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007229/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007230/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007231/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007232/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007233static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7234 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007235 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007236 return S.Context.DependentTy;
7237 if (OrigOp->getType() == S.Context.OverloadTy)
7238 return S.Context.OverloadTy;
John McCall8d08b9b2010-08-27 09:08:28 +00007239
John McCall4bc41ae2010-11-18 19:01:18 +00007240 ExprResult PR = S.CheckPlaceholderExpr(OrigOp, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007241 if (PR.isInvalid()) return QualType();
7242 OrigOp = PR.take();
7243
John McCall8d08b9b2010-08-27 09:08:28 +00007244 // Make sure to ignore parentheses in subsequent checks
7245 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007246
John McCall4bc41ae2010-11-18 19:01:18 +00007247 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007248 // Implement C99-only parts of addressof rules.
7249 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007250 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007251 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7252 // (assuming the deref expression is valid).
7253 return uOp->getSubExpr()->getType();
7254 }
7255 // Technically, there should be a check for array subscript
7256 // expressions here, but the result of one is always an lvalue anyway.
7257 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007258 NamedDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007259 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00007260
Chris Lattner9156f1b2010-07-05 19:17:26 +00007261 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007262 bool sfinae = S.isSFINAEContext();
7263 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7264 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007265 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007266 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007267 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007268 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007269 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007270 } else if (lval == Expr::LV_MemberFunction) {
7271 // If it's an instance method, make a member pointer.
7272 // The expression must have exactly the form &A::foo.
7273
7274 // If the underlying expression isn't a decl ref, give up.
7275 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007276 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007277 << OrigOp->getSourceRange();
7278 return QualType();
7279 }
7280 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7281 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7282
7283 // The id-expression was parenthesized.
7284 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007285 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007286 << OrigOp->getSourceRange();
7287
7288 // The method was named without a qualifier.
7289 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007290 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007291 << op->getSourceRange();
7292 }
7293
John McCall4bc41ae2010-11-18 19:01:18 +00007294 return S.Context.getMemberPointerType(op->getType(),
7295 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007296 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007297 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007298 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007299 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007300 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007301 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007302 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007303 return QualType();
7304 }
John McCall086a4642010-11-24 05:12:34 +00007305 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007306 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00007307 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00007308 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00007309 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007310 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007311 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00007312 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00007313 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007314 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007315 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007316 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00007317 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00007318 << "property expression" << op->getSourceRange();
7319 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007320 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007321 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007322 // with the register storage-class specifier.
7323 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007324 // in C++ it is not error to take address of a register
7325 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007326 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007327 !S.getLangOptions().CPlusPlus) {
7328 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00007329 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007330 return QualType();
7331 }
John McCalld14a8642009-11-21 08:51:07 +00007332 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007333 return S.Context.OverloadTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +00007334 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007335 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007336 // Could be a pointer to member, though, if there is an explicit
7337 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007338 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007339 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007340 if (Ctx && Ctx->isRecord()) {
7341 if (FD->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007342 S.Diag(OpLoc,
7343 diag::err_cannot_form_pointer_to_member_of_reference_type)
Anders Carlsson0b675f52009-07-08 21:45:58 +00007344 << FD->getDeclName() << FD->getType();
7345 return QualType();
7346 }
Mike Stump11289f42009-09-09 15:08:12 +00007347
John McCall4bc41ae2010-11-18 19:01:18 +00007348 return S.Context.getMemberPointerType(op->getType(),
7349 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007350 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007351 }
Anders Carlsson5b535762009-05-16 21:43:42 +00007352 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00007353 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007354 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007355
Eli Friedmance7f9002009-05-16 23:27:50 +00007356 if (lval == Expr::LV_IncompleteVoidType) {
7357 // Taking the address of a void variable is technically illegal, but we
7358 // allow it in cases which are otherwise valid.
7359 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007360 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007361 }
7362
Steve Naroff47500512007-04-19 23:00:49 +00007363 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007364 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007365 return S.Context.getObjCObjectPointerType(op->getType());
7366 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007367}
7368
Chris Lattner9156f1b2010-07-05 19:17:26 +00007369/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007370static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7371 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007372 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007373 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007374
John McCall4bc41ae2010-11-18 19:01:18 +00007375 S.UsualUnaryConversions(Op);
Chris Lattner9156f1b2010-07-05 19:17:26 +00007376 QualType OpTy = Op->getType();
7377 QualType Result;
7378
7379 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7380 // is an incomplete type or void. It would be possible to warn about
7381 // dereferencing a void pointer, but it's completely well-defined, and such a
7382 // warning is unlikely to catch any mistakes.
7383 if (const PointerType *PT = OpTy->getAs<PointerType>())
7384 Result = PT->getPointeeType();
7385 else if (const ObjCObjectPointerType *OPT =
7386 OpTy->getAs<ObjCObjectPointerType>())
7387 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007388 else {
John McCall4bc41ae2010-11-18 19:01:18 +00007389 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007390 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007391 if (PR.take() != Op)
7392 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007393 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007394
Chris Lattner9156f1b2010-07-05 19:17:26 +00007395 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007396 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007397 << OpTy << Op->getSourceRange();
7398 return QualType();
7399 }
John McCall4bc41ae2010-11-18 19:01:18 +00007400
7401 // Dereferences are usually l-values...
7402 VK = VK_LValue;
7403
7404 // ...except that certain expressions are never l-values in C.
7405 if (!S.getLangOptions().CPlusPlus &&
7406 IsCForbiddenLValueType(S.Context, Result))
7407 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007408
7409 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007410}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007411
John McCalle3027922010-08-25 11:45:40 +00007412static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007413 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007414 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007415 switch (Kind) {
7416 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007417 case tok::periodstar: Opc = BO_PtrMemD; break;
7418 case tok::arrowstar: Opc = BO_PtrMemI; break;
7419 case tok::star: Opc = BO_Mul; break;
7420 case tok::slash: Opc = BO_Div; break;
7421 case tok::percent: Opc = BO_Rem; break;
7422 case tok::plus: Opc = BO_Add; break;
7423 case tok::minus: Opc = BO_Sub; break;
7424 case tok::lessless: Opc = BO_Shl; break;
7425 case tok::greatergreater: Opc = BO_Shr; break;
7426 case tok::lessequal: Opc = BO_LE; break;
7427 case tok::less: Opc = BO_LT; break;
7428 case tok::greaterequal: Opc = BO_GE; break;
7429 case tok::greater: Opc = BO_GT; break;
7430 case tok::exclaimequal: Opc = BO_NE; break;
7431 case tok::equalequal: Opc = BO_EQ; break;
7432 case tok::amp: Opc = BO_And; break;
7433 case tok::caret: Opc = BO_Xor; break;
7434 case tok::pipe: Opc = BO_Or; break;
7435 case tok::ampamp: Opc = BO_LAnd; break;
7436 case tok::pipepipe: Opc = BO_LOr; break;
7437 case tok::equal: Opc = BO_Assign; break;
7438 case tok::starequal: Opc = BO_MulAssign; break;
7439 case tok::slashequal: Opc = BO_DivAssign; break;
7440 case tok::percentequal: Opc = BO_RemAssign; break;
7441 case tok::plusequal: Opc = BO_AddAssign; break;
7442 case tok::minusequal: Opc = BO_SubAssign; break;
7443 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7444 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7445 case tok::ampequal: Opc = BO_AndAssign; break;
7446 case tok::caretequal: Opc = BO_XorAssign; break;
7447 case tok::pipeequal: Opc = BO_OrAssign; break;
7448 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007449 }
7450 return Opc;
7451}
7452
John McCalle3027922010-08-25 11:45:40 +00007453static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007454 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007455 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007456 switch (Kind) {
7457 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007458 case tok::plusplus: Opc = UO_PreInc; break;
7459 case tok::minusminus: Opc = UO_PreDec; break;
7460 case tok::amp: Opc = UO_AddrOf; break;
7461 case tok::star: Opc = UO_Deref; break;
7462 case tok::plus: Opc = UO_Plus; break;
7463 case tok::minus: Opc = UO_Minus; break;
7464 case tok::tilde: Opc = UO_Not; break;
7465 case tok::exclaim: Opc = UO_LNot; break;
7466 case tok::kw___real: Opc = UO_Real; break;
7467 case tok::kw___imag: Opc = UO_Imag; break;
7468 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007469 }
7470 return Opc;
7471}
7472
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007473/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7474/// This warning is only emitted for builtin assignment operations. It is also
7475/// suppressed in the event of macro expansions.
7476static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7477 SourceLocation OpLoc) {
7478 if (!S.ActiveTemplateInstantiations.empty())
7479 return;
7480 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7481 return;
7482 lhs = lhs->IgnoreParenImpCasts();
7483 rhs = rhs->IgnoreParenImpCasts();
7484 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7485 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7486 if (!LeftDeclRef || !RightDeclRef ||
7487 LeftDeclRef->getLocation().isMacroID() ||
7488 RightDeclRef->getLocation().isMacroID())
7489 return;
7490 const ValueDecl *LeftDecl =
7491 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7492 const ValueDecl *RightDecl =
7493 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7494 if (LeftDecl != RightDecl)
7495 return;
7496 if (LeftDecl->getType().isVolatileQualified())
7497 return;
7498 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7499 if (RefTy->getPointeeType().isVolatileQualified())
7500 return;
7501
7502 S.Diag(OpLoc, diag::warn_self_assignment)
7503 << LeftDeclRef->getType()
7504 << lhs->getSourceRange() << rhs->getSourceRange();
7505}
7506
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007507/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7508/// operator @p Opc at location @c TokLoc. This routine only supports
7509/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007510ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007511 BinaryOperatorKind Opc,
John McCalle3027922010-08-25 11:45:40 +00007512 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007513 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007514 // The following two variables are used for compound assignment operators
7515 QualType CompLHSTy; // Type of LHS after promotions for computation
7516 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007517 ExprValueKind VK = VK_RValue;
7518 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007519
7520 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007521 case BO_Assign:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007522 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007523 if (getLangOptions().CPlusPlus &&
7524 lhs->getObjectKind() != OK_ObjCProperty) {
John McCall4bc41ae2010-11-18 19:01:18 +00007525 VK = lhs->getValueKind();
7526 OK = lhs->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007527 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007528 if (!ResultTy.isNull())
7529 DiagnoseSelfAssignment(*this, lhs, rhs, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007530 break;
John McCalle3027922010-08-25 11:45:40 +00007531 case BO_PtrMemD:
7532 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00007533 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007534 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007535 break;
John McCalle3027922010-08-25 11:45:40 +00007536 case BO_Mul:
7537 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007538 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007539 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007540 break;
John McCalle3027922010-08-25 11:45:40 +00007541 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007542 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7543 break;
John McCalle3027922010-08-25 11:45:40 +00007544 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007545 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7546 break;
John McCalle3027922010-08-25 11:45:40 +00007547 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007548 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7549 break;
John McCalle3027922010-08-25 11:45:40 +00007550 case BO_Shl:
7551 case BO_Shr:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007552 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
7553 break;
John McCalle3027922010-08-25 11:45:40 +00007554 case BO_LE:
7555 case BO_LT:
7556 case BO_GE:
7557 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007558 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007559 break;
John McCalle3027922010-08-25 11:45:40 +00007560 case BO_EQ:
7561 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007562 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007563 break;
John McCalle3027922010-08-25 11:45:40 +00007564 case BO_And:
7565 case BO_Xor:
7566 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007567 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7568 break;
John McCalle3027922010-08-25 11:45:40 +00007569 case BO_LAnd:
7570 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00007571 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007572 break;
John McCalle3027922010-08-25 11:45:40 +00007573 case BO_MulAssign:
7574 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007575 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007576 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007577 CompLHSTy = CompResultTy;
7578 if (!CompResultTy.isNull())
7579 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007580 break;
John McCalle3027922010-08-25 11:45:40 +00007581 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007582 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7583 CompLHSTy = CompResultTy;
7584 if (!CompResultTy.isNull())
7585 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007586 break;
John McCalle3027922010-08-25 11:45:40 +00007587 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007588 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7589 if (!CompResultTy.isNull())
7590 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007591 break;
John McCalle3027922010-08-25 11:45:40 +00007592 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007593 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7594 if (!CompResultTy.isNull())
7595 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007596 break;
John McCalle3027922010-08-25 11:45:40 +00007597 case BO_ShlAssign:
7598 case BO_ShrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007599 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
7600 CompLHSTy = CompResultTy;
7601 if (!CompResultTy.isNull())
7602 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007603 break;
John McCalle3027922010-08-25 11:45:40 +00007604 case BO_AndAssign:
7605 case BO_XorAssign:
7606 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007607 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7608 CompLHSTy = CompResultTy;
7609 if (!CompResultTy.isNull())
7610 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007611 break;
John McCalle3027922010-08-25 11:45:40 +00007612 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00007613 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John McCall7decc9e2010-11-18 06:31:45 +00007614 if (getLangOptions().CPlusPlus) {
7615 VK = rhs->getValueKind();
7616 OK = rhs->getObjectKind();
7617 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007618 break;
7619 }
7620 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007621 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007622 if (CompResultTy.isNull())
John McCall7decc9e2010-11-18 06:31:45 +00007623 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy,
7624 VK, OK, OpLoc));
7625
John McCall34376a62010-12-04 03:47:34 +00007626 if (getLangOptions().CPlusPlus && lhs->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007627 VK = VK_LValue;
7628 OK = lhs->getObjectKind();
7629 }
7630 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
7631 VK, OK, CompLHSTy,
7632 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007633}
7634
Sebastian Redl44615072009-10-27 12:10:02 +00007635/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
7636/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007637static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7638 const PartialDiagnostic &PD,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007639 const PartialDiagnostic &FirstNote,
7640 SourceRange FirstParenRange,
7641 const PartialDiagnostic &SecondNote,
Douglas Gregor89336232010-03-29 23:34:08 +00007642 SourceRange SecondParenRange) {
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007643 Self.Diag(Loc, PD);
7644
7645 if (!FirstNote.getDiagID())
7646 return;
7647
7648 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
7649 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
7650 // We can't display the parentheses, so just return.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007651 return;
7652 }
7653
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007654 Self.Diag(Loc, FirstNote)
7655 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregora771f462010-03-31 17:46:05 +00007656 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007657
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007658 if (!SecondNote.getDiagID())
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007659 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007660
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007661 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
7662 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
7663 // We can't display the parentheses, so just dig the
7664 // warning/error and return.
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007665 Self.Diag(Loc, SecondNote);
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007666 return;
7667 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007668
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007669 Self.Diag(Loc, SecondNote)
Douglas Gregora771f462010-03-31 17:46:05 +00007670 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
7671 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007672}
7673
Sebastian Redl44615072009-10-27 12:10:02 +00007674/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7675/// operators are mixed in a way that suggests that the programmer forgot that
7676/// comparison operators have higher precedence. The most typical example of
7677/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007678static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007679 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00007680 typedef BinaryOperator BinOp;
7681 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7682 rhsopc = static_cast<BinOp::Opcode>(-1);
7683 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007684 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00007685 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007686 rhsopc = BO->getOpcode();
7687
7688 // Subs are not binary operators.
7689 if (lhsopc == -1 && rhsopc == -1)
7690 return;
7691
7692 // Bitwise operations are sometimes used as eager logical ops.
7693 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00007694 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7695 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007696 return;
7697
Sebastian Redl44615072009-10-27 12:10:02 +00007698 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007699 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007700 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00007701 << SourceRange(lhs->getLocStart(), OpLoc)
7702 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00007703 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007704 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007705 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
7706 Self.PDiag(diag::note_precedence_bitwise_silence)
7707 << BinOp::getOpcodeStr(lhsopc),
7708 lhs->getSourceRange());
Sebastian Redl44615072009-10-27 12:10:02 +00007709 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007710 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007711 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00007712 << SourceRange(OpLoc, rhs->getLocEnd())
7713 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00007714 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007715 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007716 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
7717 Self.PDiag(diag::note_precedence_bitwise_silence)
7718 << BinOp::getOpcodeStr(rhsopc),
7719 rhs->getSourceRange());
Sebastian Redl43028242009-10-26 15:24:15 +00007720}
7721
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007722/// \brief It accepts a '&&' expr that is inside a '||' one.
7723/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7724/// in parentheses.
7725static void
7726EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
7727 Expr *E) {
7728 assert(isa<BinaryOperator>(E) &&
7729 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
7730 SuggestParentheses(Self, OpLoc,
7731 Self.PDiag(diag::warn_logical_and_in_logical_or)
7732 << E->getSourceRange(),
7733 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
7734 E->getSourceRange(),
7735 Self.PDiag(0), SourceRange());
7736}
7737
7738/// \brief Returns true if the given expression can be evaluated as a constant
7739/// 'true'.
7740static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7741 bool Res;
7742 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7743}
7744
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007745/// \brief Returns true if the given expression can be evaluated as a constant
7746/// 'false'.
7747static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7748 bool Res;
7749 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7750}
7751
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007752/// \brief Look for '&&' in the left hand of a '||' expr.
7753static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007754 Expr *OrLHS, Expr *OrRHS) {
7755 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007756 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007757 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7758 if (EvaluatesAsFalse(S, OrRHS))
7759 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007760 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7761 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7762 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7763 } else if (Bop->getOpcode() == BO_LOr) {
7764 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7765 // If it's "a || b && 1 || c" we didn't warn earlier for
7766 // "a || b && 1", but warn now.
7767 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7768 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7769 }
7770 }
7771 }
7772}
7773
7774/// \brief Look for '&&' in the right hand of a '||' expr.
7775static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007776 Expr *OrLHS, Expr *OrRHS) {
7777 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007778 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007779 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7780 if (EvaluatesAsFalse(S, OrLHS))
7781 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007782 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7783 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7784 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007785 }
7786 }
7787}
7788
Sebastian Redl43028242009-10-26 15:24:15 +00007789/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007790/// precedence.
John McCalle3027922010-08-25 11:45:40 +00007791static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007792 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007793 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00007794 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007795 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7796
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007797 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7798 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00007799 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007800 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7801 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007802 }
Sebastian Redl43028242009-10-26 15:24:15 +00007803}
7804
Steve Naroff218bc2b2007-05-04 21:54:46 +00007805// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007806ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00007807 tok::TokenKind Kind,
7808 Expr *lhs, Expr *rhs) {
7809 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00007810 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
7811 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00007812
Sebastian Redl43028242009-10-26 15:24:15 +00007813 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7814 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
7815
Douglas Gregor5287f092009-11-05 00:51:44 +00007816 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
7817}
7818
John McCalldadc5752010-08-24 06:29:42 +00007819ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007820 BinaryOperatorKind Opc,
7821 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00007822 if (getLangOptions().CPlusPlus) {
7823 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007824
John McCall622114c2010-12-06 05:26:58 +00007825 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
7826 UseBuiltinOperator = false;
7827 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
7828 UseBuiltinOperator = true;
7829 } else {
7830 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
7831 !rhs->getType()->isOverloadableType();
7832 }
7833
7834 if (!UseBuiltinOperator) {
7835 // Find all of the overloaded operators visible from this
7836 // point. We perform both an operator-name lookup from the local
7837 // scope and an argument-dependent lookup based on the types of
7838 // the arguments.
7839 UnresolvedSet<16> Functions;
7840 OverloadedOperatorKind OverOp
7841 = BinaryOperator::getOverloadedOperator(Opc);
7842 if (S && OverOp != OO_None)
7843 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
7844 Functions);
7845
7846 // Build the (potentially-overloaded, potentially-dependent)
7847 // binary operation.
7848 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
7849 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00007850 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007851
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007852 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00007853 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00007854}
7855
John McCalldadc5752010-08-24 06:29:42 +00007856ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007857 UnaryOperatorKind Opc,
John McCall36226622010-10-12 02:09:17 +00007858 Expr *Input) {
John McCall7decc9e2010-11-18 06:31:45 +00007859 ExprValueKind VK = VK_RValue;
7860 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00007861 QualType resultType;
7862 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007863 case UO_PreInc:
7864 case UO_PreDec:
7865 case UO_PostInc:
7866 case UO_PostDec:
John McCall4bc41ae2010-11-18 19:01:18 +00007867 resultType = CheckIncrementDecrementOperand(*this, Input, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007868 Opc == UO_PreInc ||
7869 Opc == UO_PostInc,
7870 Opc == UO_PreInc ||
7871 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00007872 break;
John McCalle3027922010-08-25 11:45:40 +00007873 case UO_AddrOf:
John McCall4bc41ae2010-11-18 19:01:18 +00007874 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007875 break;
John McCalle3027922010-08-25 11:45:40 +00007876 case UO_Deref:
Douglas Gregorb92a1562010-02-03 00:27:59 +00007877 DefaultFunctionArrayLvalueConversion(Input);
John McCall4bc41ae2010-11-18 19:01:18 +00007878 resultType = CheckIndirectionOperand(*this, Input, VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007879 break;
John McCalle3027922010-08-25 11:45:40 +00007880 case UO_Plus:
7881 case UO_Minus:
Steve Naroff31090012007-07-16 21:54:35 +00007882 UsualUnaryConversions(Input);
7883 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007884 if (resultType->isDependentType())
7885 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00007886 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
7887 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00007888 break;
7889 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
7890 resultType->isEnumeralType())
7891 break;
7892 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00007893 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00007894 resultType->isPointerType())
7895 break;
John McCall36226622010-10-12 02:09:17 +00007896 else if (resultType->isPlaceholderType()) {
7897 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
7898 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007899 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00007900 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007901
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007902 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7903 << resultType << Input->getSourceRange());
John McCalle3027922010-08-25 11:45:40 +00007904 case UO_Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00007905 UsualUnaryConversions(Input);
7906 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007907 if (resultType->isDependentType())
7908 break;
Chris Lattner0d707612008-07-25 23:52:49 +00007909 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
7910 if (resultType->isComplexType() || resultType->isComplexIntegerType())
7911 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00007912 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007913 << resultType << Input->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007914 else if (resultType->hasIntegerRepresentation())
7915 break;
7916 else if (resultType->isPlaceholderType()) {
7917 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
7918 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007919 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00007920 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007921 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7922 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00007923 }
Steve Naroff35d85152007-05-07 00:24:15 +00007924 break;
John McCalle3027922010-08-25 11:45:40 +00007925 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00007926 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregorb92a1562010-02-03 00:27:59 +00007927 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroff31090012007-07-16 21:54:35 +00007928 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007929 if (resultType->isDependentType())
7930 break;
John McCall36226622010-10-12 02:09:17 +00007931 if (resultType->isScalarType()) { // C99 6.5.3.3p1
7932 // ok, fallthrough
7933 } else if (resultType->isPlaceholderType()) {
7934 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
7935 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007936 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00007937 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007938 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7939 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00007940 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00007941
Chris Lattnerbe31ed82007-06-02 19:11:33 +00007942 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007943 // In C++, it's bool. C++ 5.3.1p8
7944 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Steve Naroff35d85152007-05-07 00:24:15 +00007945 break;
John McCalle3027922010-08-25 11:45:40 +00007946 case UO_Real:
7947 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00007948 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00007949 // _Real and _Imag map ordinary l-values into ordinary l-values.
7950 if (Input->getValueKind() != VK_RValue &&
7951 Input->getObjectKind() == OK_Ordinary)
7952 VK = Input->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00007953 break;
John McCalle3027922010-08-25 11:45:40 +00007954 case UO_Extension:
Chris Lattner86554282007-06-08 22:32:33 +00007955 resultType = Input->getType();
John McCall7decc9e2010-11-18 06:31:45 +00007956 VK = Input->getValueKind();
7957 OK = Input->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00007958 break;
Steve Naroff35d85152007-05-07 00:24:15 +00007959 }
7960 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007961 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00007962
John McCall7decc9e2010-11-18 06:31:45 +00007963 return Owned(new (Context) UnaryOperator(Input, Opc, resultType,
7964 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00007965}
Chris Lattnereefa10e2007-05-28 06:56:27 +00007966
John McCalldadc5752010-08-24 06:29:42 +00007967ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007968 UnaryOperatorKind Opc,
7969 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00007970 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00007971 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007972 // Find all of the overloaded operators visible from this
7973 // point. We perform both an operator-name lookup from the local
7974 // scope and an argument-dependent lookup based on the types of
7975 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00007976 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00007977 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00007978 if (S && OverOp != OO_None)
7979 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
7980 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007981
John McCallb268a282010-08-23 23:25:46 +00007982 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007983 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007984
John McCallb268a282010-08-23 23:25:46 +00007985 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007986}
7987
Douglas Gregor5287f092009-11-05 00:51:44 +00007988// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007989ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00007990 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00007991 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00007992}
7993
Steve Naroff66356bd2007-09-16 14:56:35 +00007994/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
John McCalldadc5752010-08-24 06:29:42 +00007995ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007996 SourceLocation LabLoc,
7997 IdentifierInfo *LabelII) {
Chris Lattnereefa10e2007-05-28 06:56:27 +00007998 // Look up the record for this label identifier.
John McCallaab3e412010-08-25 08:40:02 +00007999 LabelStmt *&LabelDecl = getCurFunction()->LabelMap[LabelII];
Mike Stump4e1f26a2009-02-19 03:04:26 +00008000
Daniel Dunbar88402ce2008-08-04 16:51:22 +00008001 // If we haven't seen this label yet, create a forward reference. It
8002 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff846b1ec2009-03-13 15:38:40 +00008003 if (LabelDecl == 0)
Steve Narofff6009ed2009-01-21 00:14:39 +00008004 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008005
Argyrios Kyrtzidis72664df2010-09-19 21:21:25 +00008006 LabelDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008007 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008008 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
8009 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008010}
8011
John McCalldadc5752010-08-24 06:29:42 +00008012ExprResult
John McCallb268a282010-08-23 23:25:46 +00008013Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008014 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008015 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8016 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8017
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008018 bool isFileScope
8019 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008020 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008021 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008022
Chris Lattner366727f2007-07-24 16:58:17 +00008023 // FIXME: there are a variety of strange constraints to enforce here, for
8024 // example, it is not possible to goto into a stmt expression apparently.
8025 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008026
Chris Lattner366727f2007-07-24 16:58:17 +00008027 // If there are sub stmts in the compound stmt, take the type of the last one
8028 // as the type of the stmtexpr.
8029 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008030 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008031 if (!Compound->body_empty()) {
8032 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008033 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008034 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008035 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8036 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008037 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008038 }
8039 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008040 // Do function/array conversion on the last expression, but not
8041 // lvalue-to-rvalue. However, initialize an unqualified type.
8042 DefaultFunctionArrayConversion(LastExpr);
8043 Ty = LastExpr->getType().getUnqualifiedType();
8044
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008045 if (!Ty->isDependentType() && !LastExpr->isTypeDependent()) {
8046 ExprResult Res = PerformCopyInitialization(
8047 InitializedEntity::InitializeResult(LPLoc,
8048 Ty,
8049 false),
8050 SourceLocation(),
8051 Owned(LastExpr));
8052 if (Res.isInvalid())
8053 return ExprError();
8054 if ((LastExpr = Res.takeAs<Expr>())) {
8055 if (!LastLabelStmt)
8056 Compound->setLastStmt(LastExpr);
8057 else
8058 LastLabelStmt->setSubStmt(LastExpr);
8059 StmtExprMayBindToTemp = true;
8060 }
8061 }
8062 }
Chris Lattner944d3062008-07-26 19:51:01 +00008063 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008064
Eli Friedmanba961a92009-03-23 00:24:07 +00008065 // FIXME: Check that expression type is complete/non-abstract; statement
8066 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008067 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8068 if (StmtExprMayBindToTemp)
8069 return MaybeBindToTemporary(ResStmtExpr);
8070 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008071}
Steve Naroff78864672007-08-01 22:05:33 +00008072
John McCalldadc5752010-08-24 06:29:42 +00008073ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008074 TypeSourceInfo *TInfo,
8075 OffsetOfComponent *CompPtr,
8076 unsigned NumComponents,
8077 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008078 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008079 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008080 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008081
Chris Lattnerf17bd422007-08-30 17:45:32 +00008082 // We must have at least one component that refers to the type, and the first
8083 // one is known to be a field designator. Verify that the ArgTy represents
8084 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008085 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008086 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8087 << ArgTy << TypeRange);
8088
8089 // Type must be complete per C99 7.17p3 because a declaring a variable
8090 // with an incomplete type would be ill-formed.
8091 if (!Dependent
8092 && RequireCompleteType(BuiltinLoc, ArgTy,
8093 PDiag(diag::err_offsetof_incomplete_type)
8094 << TypeRange))
8095 return ExprError();
8096
Chris Lattner78502cf2007-08-31 21:49:13 +00008097 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8098 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008099 // FIXME: This diagnostic isn't actually visible because the location is in
8100 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008101 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008102 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8103 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008104
8105 bool DidWarnAboutNonPOD = false;
8106 QualType CurrentType = ArgTy;
8107 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8108 llvm::SmallVector<OffsetOfNode, 4> Comps;
8109 llvm::SmallVector<Expr*, 4> Exprs;
8110 for (unsigned i = 0; i != NumComponents; ++i) {
8111 const OffsetOfComponent &OC = CompPtr[i];
8112 if (OC.isBrackets) {
8113 // Offset of an array sub-field. TODO: Should we allow vector elements?
8114 if (!CurrentType->isDependentType()) {
8115 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8116 if(!AT)
8117 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8118 << CurrentType);
8119 CurrentType = AT->getElementType();
8120 } else
8121 CurrentType = Context.DependentTy;
8122
8123 // The expression must be an integral expression.
8124 // FIXME: An integral constant expression?
8125 Expr *Idx = static_cast<Expr*>(OC.U.E);
8126 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8127 !Idx->getType()->isIntegerType())
8128 return ExprError(Diag(Idx->getLocStart(),
8129 diag::err_typecheck_subscript_not_integer)
8130 << Idx->getSourceRange());
8131
8132 // Record this array index.
8133 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8134 Exprs.push_back(Idx);
8135 continue;
8136 }
8137
8138 // Offset of a field.
8139 if (CurrentType->isDependentType()) {
8140 // We have the offset of a field, but we can't look into the dependent
8141 // type. Just record the identifier of the field.
8142 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8143 CurrentType = Context.DependentTy;
8144 continue;
8145 }
8146
8147 // We need to have a complete type to look into.
8148 if (RequireCompleteType(OC.LocStart, CurrentType,
8149 diag::err_offsetof_incomplete_type))
8150 return ExprError();
8151
8152 // Look for the designated field.
8153 const RecordType *RC = CurrentType->getAs<RecordType>();
8154 if (!RC)
8155 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8156 << CurrentType);
8157 RecordDecl *RD = RC->getDecl();
8158
8159 // C++ [lib.support.types]p5:
8160 // The macro offsetof accepts a restricted set of type arguments in this
8161 // International Standard. type shall be a POD structure or a POD union
8162 // (clause 9).
8163 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8164 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
8165 DiagRuntimeBehavior(BuiltinLoc,
8166 PDiag(diag::warn_offsetof_non_pod_type)
8167 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8168 << CurrentType))
8169 DidWarnAboutNonPOD = true;
8170 }
8171
8172 // Look for the field.
8173 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8174 LookupQualifiedName(R, RD);
8175 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008176 IndirectFieldDecl *IndirectMemberDecl = 0;
8177 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008178 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008179 MemberDecl = IndirectMemberDecl->getAnonField();
8180 }
8181
Douglas Gregor882211c2010-04-28 22:16:22 +00008182 if (!MemberDecl)
8183 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8184 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8185 OC.LocEnd));
8186
Douglas Gregor10982ea2010-04-28 22:36:06 +00008187 // C99 7.17p3:
8188 // (If the specified member is a bit-field, the behavior is undefined.)
8189 //
8190 // We diagnose this as an error.
8191 if (MemberDecl->getBitWidth()) {
8192 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8193 << MemberDecl->getDeclName()
8194 << SourceRange(BuiltinLoc, RParenLoc);
8195 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8196 return ExprError();
8197 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008198
8199 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008200 if (IndirectMemberDecl)
8201 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008202
Douglas Gregord1702062010-04-29 00:18:15 +00008203 // If the member was found in a base class, introduce OffsetOfNodes for
8204 // the base class indirections.
8205 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8206 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008207 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008208 CXXBasePath &Path = Paths.front();
8209 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8210 B != BEnd; ++B)
8211 Comps.push_back(OffsetOfNode(B->Base));
8212 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008213
Francois Pichet783dd6e2010-11-21 06:08:52 +00008214 if (IndirectMemberDecl) {
8215 for (IndirectFieldDecl::chain_iterator FI =
8216 IndirectMemberDecl->chain_begin(),
8217 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8218 assert(isa<FieldDecl>(*FI));
8219 Comps.push_back(OffsetOfNode(OC.LocStart,
8220 cast<FieldDecl>(*FI), OC.LocEnd));
8221 }
8222 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008223 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008224
Douglas Gregor882211c2010-04-28 22:16:22 +00008225 CurrentType = MemberDecl->getType().getNonReferenceType();
8226 }
8227
8228 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8229 TInfo, Comps.data(), Comps.size(),
8230 Exprs.data(), Exprs.size(), RParenLoc));
8231}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008232
John McCalldadc5752010-08-24 06:29:42 +00008233ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008234 SourceLocation BuiltinLoc,
8235 SourceLocation TypeLoc,
8236 ParsedType argty,
8237 OffsetOfComponent *CompPtr,
8238 unsigned NumComponents,
8239 SourceLocation RPLoc) {
8240
Douglas Gregor882211c2010-04-28 22:16:22 +00008241 TypeSourceInfo *ArgTInfo;
8242 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8243 if (ArgTy.isNull())
8244 return ExprError();
8245
Eli Friedman06dcfd92010-08-05 10:15:45 +00008246 if (!ArgTInfo)
8247 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8248
8249 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8250 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008251}
8252
8253
John McCalldadc5752010-08-24 06:29:42 +00008254ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008255 Expr *CondExpr,
8256 Expr *LHSExpr, Expr *RHSExpr,
8257 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008258 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8259
John McCall7decc9e2010-11-18 06:31:45 +00008260 ExprValueKind VK = VK_RValue;
8261 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008262 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008263 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008264 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008265 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008266 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008267 } else {
8268 // The conditional expression is required to be a constant expression.
8269 llvm::APSInt condEval(32);
8270 SourceLocation ExpLoc;
8271 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008272 return ExprError(Diag(ExpLoc,
8273 diag::err_typecheck_choose_expr_requires_constant)
8274 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008275
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008276 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008277 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8278
8279 resType = ActiveExpr->getType();
8280 ValueDependent = ActiveExpr->isValueDependent();
8281 VK = ActiveExpr->getValueKind();
8282 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008283 }
8284
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008285 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008286 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008287 resType->isDependentType(),
8288 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008289}
8290
Steve Naroffc540d662008-09-03 18:15:37 +00008291//===----------------------------------------------------------------------===//
8292// Clang Extensions.
8293//===----------------------------------------------------------------------===//
8294
8295/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008296void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008297 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8298 PushBlockScope(BlockScope, Block);
8299 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008300 if (BlockScope)
8301 PushDeclContext(BlockScope, Block);
8302 else
8303 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008304}
8305
Mike Stump82f071f2009-02-04 22:31:32 +00008306void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008307 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008308 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008309 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008310
John McCall8cb7bdf2010-06-04 23:28:52 +00008311 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008312 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008313
John McCall3882ace2011-01-05 12:14:39 +00008314 // GetTypeForDeclarator always produces a function type for a block
8315 // literal signature. Furthermore, it is always a FunctionProtoType
8316 // unless the function was written with a typedef.
8317 assert(T->isFunctionType() &&
8318 "GetTypeForDeclarator made a non-function block signature");
8319
8320 // Look for an explicit signature in that function type.
8321 FunctionProtoTypeLoc ExplicitSignature;
8322
8323 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8324 if (isa<FunctionProtoTypeLoc>(tmp)) {
8325 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8326
8327 // Check whether that explicit signature was synthesized by
8328 // GetTypeForDeclarator. If so, don't save that as part of the
8329 // written signature.
8330 if (ExplicitSignature.getLParenLoc() ==
8331 ExplicitSignature.getRParenLoc()) {
8332 // This would be much cheaper if we stored TypeLocs instead of
8333 // TypeSourceInfos.
8334 TypeLoc Result = ExplicitSignature.getResultLoc();
8335 unsigned Size = Result.getFullDataSize();
8336 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8337 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8338
8339 ExplicitSignature = FunctionProtoTypeLoc();
8340 }
John McCalla3ccba02010-06-04 11:21:44 +00008341 }
Mike Stump11289f42009-09-09 15:08:12 +00008342
John McCall3882ace2011-01-05 12:14:39 +00008343 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8344 CurBlock->FunctionType = T;
8345
8346 const FunctionType *Fn = T->getAs<FunctionType>();
8347 QualType RetTy = Fn->getResultType();
8348 bool isVariadic =
8349 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8350
John McCall8e346702010-06-04 19:02:56 +00008351 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008352
John McCalla3ccba02010-06-04 11:21:44 +00008353 // Don't allow returning a objc interface by value.
8354 if (RetTy->isObjCObjectType()) {
8355 Diag(ParamInfo.getSourceRange().getBegin(),
8356 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8357 return;
8358 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008359
John McCalla3ccba02010-06-04 11:21:44 +00008360 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008361 // return type. TODO: what should we do with declarators like:
8362 // ^ * { ... }
8363 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008364 if (RetTy != Context.DependentTy)
8365 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008366
John McCalla3ccba02010-06-04 11:21:44 +00008367 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00008368 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008369 if (ExplicitSignature) {
8370 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8371 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008372 if (Param->getIdentifier() == 0 &&
8373 !Param->isImplicit() &&
8374 !Param->isInvalidDecl() &&
8375 !getLangOptions().CPlusPlus)
8376 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008377 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008378 }
John McCalla3ccba02010-06-04 11:21:44 +00008379
8380 // Fake up parameter variables if we have a typedef, like
8381 // ^ fntype { ... }
8382 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8383 for (FunctionProtoType::arg_type_iterator
8384 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8385 ParmVarDecl *Param =
8386 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8387 ParamInfo.getSourceRange().getBegin(),
8388 *I);
John McCall8e346702010-06-04 19:02:56 +00008389 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008390 }
Steve Naroffc540d662008-09-03 18:15:37 +00008391 }
John McCalla3ccba02010-06-04 11:21:44 +00008392
John McCall8e346702010-06-04 19:02:56 +00008393 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008394 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00008395 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00008396 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8397 CurBlock->TheDecl->param_end(),
8398 /*CheckParameterNames=*/false);
8399 }
8400
John McCalla3ccba02010-06-04 11:21:44 +00008401 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008402 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008403
John McCall8e346702010-06-04 19:02:56 +00008404 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008405 Diag(ParamInfo.getAttributes()->getLoc(),
8406 diag::warn_attribute_sentinel_not_variadic) << 1;
8407 // FIXME: remove the attribute.
8408 }
8409
8410 // Put the parameter variables in scope. We can bail out immediately
8411 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008412 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008413 return;
8414
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008415 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008416 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8417 (*AI)->setOwningFunction(CurBlock->TheDecl);
8418
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008419 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008420 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008421 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008422
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008423 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008424 }
John McCallf7b2fb52010-01-22 00:28:27 +00008425 }
Steve Naroffc540d662008-09-03 18:15:37 +00008426}
8427
8428/// ActOnBlockError - If there is an error parsing a block, this callback
8429/// is invoked to pop the information about the block from the action impl.
8430void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008431 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008432 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008433 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008434}
8435
8436/// ActOnBlockStmtExpr - This is called when the body of a block statement
8437/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008438ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
John McCallb268a282010-08-23 23:25:46 +00008439 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008440 // If blocks are disabled, emit an error.
8441 if (!LangOpts.Blocks)
8442 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008443
Douglas Gregor9a28e842010-03-01 23:15:13 +00008444 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008445
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008446 PopDeclContext();
8447
Steve Naroffc540d662008-09-03 18:15:37 +00008448 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008449 if (!BSI->ReturnType.isNull())
8450 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008451
Mike Stump3bf1ab42009-07-28 22:04:01 +00008452 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008453 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008454
8455 // If the user wrote a function type in some form, try to use that.
8456 if (!BSI->FunctionType.isNull()) {
8457 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8458
8459 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8460 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8461
8462 // Turn protoless block types into nullary block types.
8463 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008464 FunctionProtoType::ExtProtoInfo EPI;
8465 EPI.ExtInfo = Ext;
8466 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008467
8468 // Otherwise, if we don't need to change anything about the function type,
8469 // preserve its sugar structure.
8470 } else if (FTy->getResultType() == RetTy &&
8471 (!NoReturn || FTy->getNoReturnAttr())) {
8472 BlockTy = BSI->FunctionType;
8473
8474 // Otherwise, make the minimal modifications to the function type.
8475 } else {
8476 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008477 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8478 EPI.TypeQuals = 0; // FIXME: silently?
8479 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008480 BlockTy = Context.getFunctionType(RetTy,
8481 FPT->arg_type_begin(),
8482 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008483 EPI);
John McCall8e346702010-06-04 19:02:56 +00008484 }
8485
8486 // If we don't have a function type, just build one from nothing.
8487 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008488 FunctionProtoType::ExtProtoInfo EPI;
8489 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, 0, CC_Default);
8490 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008491 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008492
John McCall8e346702010-06-04 19:02:56 +00008493 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8494 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008495 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008496
Chris Lattner45542ea2009-04-19 05:28:12 +00008497 // If needed, diagnose invalid gotos and switches in the block.
John McCallaab3e412010-08-25 08:40:02 +00008498 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008499 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008500
John McCallb268a282010-08-23 23:25:46 +00008501 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Mike Stump314825b2010-01-19 23:08:01 +00008502
8503 bool Good = true;
8504 // Check goto/label use.
8505 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
8506 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
8507 LabelStmt *L = I->second;
8508
8509 // Verify that we have no forward references left. If so, there was a goto
8510 // or address of a label taken, but no definition of it.
Argyrios Kyrtzidis72664df2010-09-19 21:21:25 +00008511 if (L->getSubStmt() != 0) {
8512 if (!L->isUsed())
8513 Diag(L->getIdentLoc(), diag::warn_unused_label) << L->getName();
Mike Stump314825b2010-01-19 23:08:01 +00008514 continue;
Argyrios Kyrtzidis72664df2010-09-19 21:21:25 +00008515 }
Mike Stump314825b2010-01-19 23:08:01 +00008516
8517 // Emit error.
8518 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
8519 Good = false;
8520 }
Douglas Gregor9a28e842010-03-01 23:15:13 +00008521 if (!Good) {
8522 PopFunctionOrBlockScope();
Mike Stump314825b2010-01-19 23:08:01 +00008523 return ExprError();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008524 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008525
John McCall1d570a72010-08-25 05:56:39 +00008526 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy,
8527 BSI->hasBlockDeclRefExprs);
8528
Ted Kremenek918fe842010-03-20 21:06:02 +00008529 // Issue any analysis-based warnings.
Ted Kremenek0b405322010-03-23 00:13:23 +00008530 const sema::AnalysisBasedWarnings::Policy &WP =
8531 AnalysisWarnings.getDefaultPolicy();
John McCall1d570a72010-08-25 05:56:39 +00008532 AnalysisWarnings.IssueWarnings(WP, Result);
Ted Kremenek918fe842010-03-20 21:06:02 +00008533
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008534 PopFunctionOrBlockScope();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008535 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008536}
8537
John McCalldadc5752010-08-24 06:29:42 +00008538ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00008539 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008540 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008541 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00008542 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00008543 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008544}
8545
John McCalldadc5752010-08-24 06:29:42 +00008546ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008547 Expr *E, TypeSourceInfo *TInfo,
8548 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008549 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008550
Eli Friedman121ba0c2008-08-09 23:32:40 +00008551 // Get the va_list type
8552 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008553 if (VaListType->isArrayType()) {
8554 // Deal with implicit array decay; for example, on x86-64,
8555 // va_list is an array, but it's supposed to decay to
8556 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008557 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008558 // Make sure the input expression also decays appropriately.
8559 UsualUnaryConversions(E);
8560 } else {
8561 // Otherwise, the va_list argument must be an l-value because
8562 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008563 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008564 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008565 return ExprError();
8566 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008567
Douglas Gregorad3150c2009-05-19 23:10:31 +00008568 if (!E->isTypeDependent() &&
8569 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008570 return ExprError(Diag(E->getLocStart(),
8571 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008572 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008573 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008574
Eli Friedmanba961a92009-03-23 00:24:07 +00008575 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008576 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008577
Abramo Bagnara27db2392010-08-10 10:06:15 +00008578 QualType T = TInfo->getType().getNonLValueExprType(Context);
8579 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008580}
8581
John McCalldadc5752010-08-24 06:29:42 +00008582ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00008583 // The type of __null will be int or long, depending on the size of
8584 // pointers on the target.
8585 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008586 unsigned pw = Context.Target.getPointerWidth(0);
8587 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008588 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008589 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008590 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008591 else if (pw == Context.Target.getLongLongWidth())
8592 Ty = Context.LongLongTy;
8593 else {
8594 assert(!"I don't know size of pointer!");
8595 Ty = Context.IntTy;
8596 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00008597
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008598 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00008599}
8600
Alexis Huntc46382e2010-04-28 23:02:27 +00008601static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00008602 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00008603 if (!SemaRef.getLangOptions().ObjC1)
8604 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008605
Anders Carlssonace5d072009-11-10 04:46:30 +00008606 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8607 if (!PT)
8608 return;
8609
8610 // Check if the destination is of type 'id'.
8611 if (!PT->isObjCIdType()) {
8612 // Check if the destination is the 'NSString' interface.
8613 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8614 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8615 return;
8616 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008617
Anders Carlssonace5d072009-11-10 04:46:30 +00008618 // Strip off any parens and casts.
8619 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
8620 if (!SL || SL->isWide())
8621 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008622
Douglas Gregora771f462010-03-31 17:46:05 +00008623 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00008624}
8625
Chris Lattner9bad62c2008-01-04 18:04:52 +00008626bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8627 SourceLocation Loc,
8628 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008629 Expr *SrcExpr, AssignmentAction Action,
8630 bool *Complained) {
8631 if (Complained)
8632 *Complained = false;
8633
Chris Lattner9bad62c2008-01-04 18:04:52 +00008634 // Decode the result (notice that AST's are still created for extensions).
8635 bool isInvalid = false;
8636 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00008637 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008638
Chris Lattner9bad62c2008-01-04 18:04:52 +00008639 switch (ConvTy) {
8640 default: assert(0 && "Unknown conversion type");
8641 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008642 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00008643 DiagKind = diag::ext_typecheck_convert_pointer_int;
8644 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008645 case IntToPointer:
8646 DiagKind = diag::ext_typecheck_convert_int_pointer;
8647 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008648 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00008649 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00008650 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
8651 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00008652 case IncompatiblePointerSign:
8653 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8654 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008655 case FunctionVoidPointer:
8656 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8657 break;
8658 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008659 // If the qualifiers lost were because we were applying the
8660 // (deprecated) C++ conversion from a string literal to a char*
8661 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8662 // Ideally, this check would be performed in
8663 // CheckPointerTypesForAssignment. However, that would require a
8664 // bit of refactoring (so that the second argument is an
8665 // expression, rather than a type), which should be done as part
8666 // of a larger effort to fix CheckPointerTypesForAssignment for
8667 // C++ semantics.
8668 if (getLangOptions().CPlusPlus &&
8669 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8670 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008671 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8672 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00008673 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00008674 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00008675 break;
Steve Naroff081c7422008-09-04 15:10:53 +00008676 case IntToBlockPointer:
8677 DiagKind = diag::err_int_to_block_pointer;
8678 break;
8679 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00008680 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00008681 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00008682 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00008683 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00008684 // it can give a more specific diagnostic.
8685 DiagKind = diag::warn_incompatible_qualified_id;
8686 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00008687 case IncompatibleVectors:
8688 DiagKind = diag::warn_incompatible_vectors;
8689 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008690 case Incompatible:
8691 DiagKind = diag::err_typecheck_convert_incompatible;
8692 isInvalid = true;
8693 break;
8694 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008695
Douglas Gregorc68e1402010-04-09 00:35:39 +00008696 QualType FirstType, SecondType;
8697 switch (Action) {
8698 case AA_Assigning:
8699 case AA_Initializing:
8700 // The destination type comes first.
8701 FirstType = DstType;
8702 SecondType = SrcType;
8703 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00008704
Douglas Gregorc68e1402010-04-09 00:35:39 +00008705 case AA_Returning:
8706 case AA_Passing:
8707 case AA_Converting:
8708 case AA_Sending:
8709 case AA_Casting:
8710 // The source type comes first.
8711 FirstType = SrcType;
8712 SecondType = DstType;
8713 break;
8714 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008715
Douglas Gregorc68e1402010-04-09 00:35:39 +00008716 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00008717 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008718 if (Complained)
8719 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008720 return isInvalid;
8721}
Anders Carlssone54e8a12008-11-30 19:50:32 +00008722
Chris Lattnerc71d08b2009-04-25 21:59:05 +00008723bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008724 llvm::APSInt ICEResult;
8725 if (E->isIntegerConstantExpr(ICEResult, Context)) {
8726 if (Result)
8727 *Result = ICEResult;
8728 return false;
8729 }
8730
Anders Carlssone54e8a12008-11-30 19:50:32 +00008731 Expr::EvalResult EvalResult;
8732
Mike Stump4e1f26a2009-02-19 03:04:26 +00008733 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00008734 EvalResult.HasSideEffects) {
8735 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
8736
8737 if (EvalResult.Diag) {
8738 // We only show the note if it's not the usual "invalid subexpression"
8739 // or if it's actually in a subexpression.
8740 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
8741 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
8742 Diag(EvalResult.DiagLoc, EvalResult.Diag);
8743 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008744
Anders Carlssone54e8a12008-11-30 19:50:32 +00008745 return true;
8746 }
8747
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008748 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
8749 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00008750
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008751 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008752 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
8753 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008754 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008755
Anders Carlssone54e8a12008-11-30 19:50:32 +00008756 if (Result)
8757 *Result = EvalResult.Val.getInt();
8758 return false;
8759}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008760
Douglas Gregorff790f12009-11-26 00:44:06 +00008761void
Mike Stump11289f42009-09-09 15:08:12 +00008762Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00008763 ExprEvalContexts.push_back(
8764 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008765}
8766
Mike Stump11289f42009-09-09 15:08:12 +00008767void
Douglas Gregorff790f12009-11-26 00:44:06 +00008768Sema::PopExpressionEvaluationContext() {
8769 // Pop the current expression evaluation context off the stack.
8770 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
8771 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008772
Douglas Gregorfab31f42009-12-12 07:57:52 +00008773 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
8774 if (Rec.PotentiallyReferenced) {
8775 // Mark any remaining declarations in the current position of the stack
8776 // as "referenced". If they were not meant to be referenced, semantic
8777 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008778 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00008779 I = Rec.PotentiallyReferenced->begin(),
8780 IEnd = Rec.PotentiallyReferenced->end();
8781 I != IEnd; ++I)
8782 MarkDeclarationReferenced(I->first, I->second);
8783 }
8784
8785 if (Rec.PotentiallyDiagnosed) {
8786 // Emit any pending diagnostics.
8787 for (PotentiallyEmittedDiagnostics::iterator
8788 I = Rec.PotentiallyDiagnosed->begin(),
8789 IEnd = Rec.PotentiallyDiagnosed->end();
8790 I != IEnd; ++I)
8791 Diag(I->first, I->second);
8792 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008793 }
Douglas Gregorff790f12009-11-26 00:44:06 +00008794
8795 // When are coming out of an unevaluated context, clear out any
8796 // temporaries that we may have created as part of the evaluation of
8797 // the expression in that context: they aren't relevant because they
8798 // will never be constructed.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008799 if (Rec.Context == Unevaluated &&
Douglas Gregorff790f12009-11-26 00:44:06 +00008800 ExprTemporaries.size() > Rec.NumTemporaries)
8801 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
8802 ExprTemporaries.end());
8803
8804 // Destroy the popped expression evaluation record.
8805 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008806}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008807
8808/// \brief Note that the given declaration was referenced in the source code.
8809///
8810/// This routine should be invoke whenever a given declaration is referenced
8811/// in the source code, and where that reference occurred. If this declaration
8812/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
8813/// C99 6.9p3), then the declaration will be marked as used.
8814///
8815/// \param Loc the location where the declaration was referenced.
8816///
8817/// \param D the declaration that has been referenced by the source code.
8818void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
8819 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00008820
Douglas Gregorebada0772010-06-17 23:14:26 +00008821 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00008822 return;
Mike Stump11289f42009-09-09 15:08:12 +00008823
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00008824 // Mark a parameter or variable declaration "used", regardless of whether we're in a
8825 // template or not. The reason for this is that unevaluated expressions
8826 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
8827 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008828 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008829 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00008830 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008831 return;
8832 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008833
Douglas Gregorfd27fed2010-04-07 20:29:57 +00008834 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
8835 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00008836
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008837 // Do not mark anything as "used" within a dependent context; wait for
8838 // an instantiation.
8839 if (CurContext->isDependentContext())
8840 return;
Mike Stump11289f42009-09-09 15:08:12 +00008841
Douglas Gregorff790f12009-11-26 00:44:06 +00008842 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008843 case Unevaluated:
8844 // We are in an expression that is not potentially evaluated; do nothing.
8845 return;
Mike Stump11289f42009-09-09 15:08:12 +00008846
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008847 case PotentiallyEvaluated:
8848 // We are in a potentially-evaluated expression, so this declaration is
8849 // "used"; handle this below.
8850 break;
Mike Stump11289f42009-09-09 15:08:12 +00008851
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008852 case PotentiallyPotentiallyEvaluated:
8853 // We are in an expression that may be potentially evaluated; queue this
8854 // declaration reference until we know whether the expression is
8855 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00008856 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008857 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00008858
8859 case PotentiallyEvaluatedIfUsed:
8860 // Referenced declarations will only be used if the construct in the
8861 // containing expression is used.
8862 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008863 }
Mike Stump11289f42009-09-09 15:08:12 +00008864
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008865 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00008866 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008867 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008868 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruthc9262402010-08-23 07:55:51 +00008869 if (Constructor->getParent()->hasTrivialConstructor())
8870 return;
8871 if (!Constructor->isUsed(false))
8872 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00008873 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00008874 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008875 if (!Constructor->isUsed(false))
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008876 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
8877 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008878
Douglas Gregor88d292c2010-05-13 16:44:06 +00008879 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008880 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008881 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008882 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008883 if (Destructor->isVirtual())
8884 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008885 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
8886 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
8887 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00008888 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00008889 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008890 } else if (MethodDecl->isVirtual())
8891 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008892 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00008893 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00008894 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00008895 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00008896 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00008897 bool AlreadyInstantiated = false;
8898 if (FunctionTemplateSpecializationInfo *SpecInfo
8899 = Function->getTemplateSpecializationInfo()) {
8900 if (SpecInfo->getPointOfInstantiation().isInvalid())
8901 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008902 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00008903 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00008904 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008905 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00008906 = Function->getMemberSpecializationInfo()) {
8907 if (MSInfo->getPointOfInstantiation().isInvalid())
8908 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008909 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00008910 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00008911 AlreadyInstantiated = true;
8912 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008913
Douglas Gregor7f792cf2010-01-16 22:29:39 +00008914 if (!AlreadyInstantiated) {
8915 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
8916 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
8917 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
8918 Loc));
8919 else
Chandler Carruth54080172010-08-25 08:44:16 +00008920 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00008921 }
Gabor Greifb6aba3e2010-08-28 00:16:06 +00008922 } else // Walk redefinitions, as some of them may be instantiable.
8923 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
8924 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00008925 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00008926 MarkDeclarationReferenced(Loc, *i);
8927 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008928
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008929 // FIXME: keep track of references to static functions
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00008930
8931 // Recursive functions should be marked when used from another function.
8932 if (CurContext != Function)
8933 Function->setUsed(true);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008934
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008935 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00008936 }
Mike Stump11289f42009-09-09 15:08:12 +00008937
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008938 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00008939 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00008940 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00008941 Var->getInstantiatedFromStaticDataMember()) {
8942 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
8943 assert(MSInfo && "Missing member specialization information?");
8944 if (MSInfo->getPointOfInstantiation().isInvalid() &&
8945 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
8946 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth54080172010-08-25 08:44:16 +00008947 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00008948 }
8949 }
Mike Stump11289f42009-09-09 15:08:12 +00008950
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008951 // FIXME: keep track of references to static data?
Douglas Gregora6ef8f02009-07-24 20:34:43 +00008952
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008953 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00008954 return;
Sam Weinigbae69142009-09-11 03:29:30 +00008955 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008956}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00008957
Douglas Gregor5597ab42010-05-07 23:12:07 +00008958namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00008959 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00008960 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00008961 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00008962 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
8963 Sema &S;
8964 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00008965
Douglas Gregor5597ab42010-05-07 23:12:07 +00008966 public:
8967 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00008968
Douglas Gregor5597ab42010-05-07 23:12:07 +00008969 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00008970
8971 bool TraverseTemplateArgument(const TemplateArgument &Arg);
8972 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00008973 };
8974}
8975
Chandler Carruthaf80f662010-06-09 08:17:30 +00008976bool MarkReferencedDecls::TraverseTemplateArgument(
8977 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00008978 if (Arg.getKind() == TemplateArgument::Declaration) {
8979 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
8980 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00008981
8982 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00008983}
8984
Chandler Carruthaf80f662010-06-09 08:17:30 +00008985bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00008986 if (ClassTemplateSpecializationDecl *Spec
8987 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
8988 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008989 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00008990 }
8991
Chandler Carruthc65667c2010-06-10 10:31:57 +00008992 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00008993}
8994
8995void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
8996 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00008997 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00008998}
8999
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009000namespace {
9001 /// \brief Helper class that marks all of the declarations referenced by
9002 /// potentially-evaluated subexpressions as "referenced".
9003 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9004 Sema &S;
9005
9006 public:
9007 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9008
9009 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9010
9011 void VisitDeclRefExpr(DeclRefExpr *E) {
9012 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9013 }
9014
9015 void VisitMemberExpr(MemberExpr *E) {
9016 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009017 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009018 }
9019
9020 void VisitCXXNewExpr(CXXNewExpr *E) {
9021 if (E->getConstructor())
9022 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9023 if (E->getOperatorNew())
9024 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9025 if (E->getOperatorDelete())
9026 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009027 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009028 }
9029
9030 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9031 if (E->getOperatorDelete())
9032 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009033 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9034 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9035 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9036 S.MarkDeclarationReferenced(E->getLocStart(),
9037 S.LookupDestructor(Record));
9038 }
9039
Douglas Gregor32b3de52010-09-11 23:32:50 +00009040 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009041 }
9042
9043 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9044 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009045 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009046 }
9047
9048 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9049 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9050 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009051
9052 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9053 Visit(E->getExpr());
9054 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009055 };
9056}
9057
9058/// \brief Mark any declarations that appear within this expression or any
9059/// potentially-evaluated subexpressions as "referenced".
9060void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9061 EvaluatedExprMarker(*this).Visit(E);
9062}
9063
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009064/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9065/// of the program being compiled.
9066///
9067/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009068/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009069/// possibility that the code will actually be executable. Code in sizeof()
9070/// expressions, code used only during overload resolution, etc., are not
9071/// potentially evaluated. This routine will suppress such diagnostics or,
9072/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009073/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009074/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009075///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009076/// This routine should be used for all diagnostics that describe the run-time
9077/// behavior of a program, such as passing a non-POD value through an ellipsis.
9078/// Failure to do so will likely result in spurious diagnostics or failures
9079/// during overload resolution or within sizeof/alignof/typeof/typeid.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009080bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009081 const PartialDiagnostic &PD) {
9082 switch (ExprEvalContexts.back().Context ) {
9083 case Unevaluated:
9084 // The argument will never be evaluated, so don't complain.
9085 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009086
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009087 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009088 case PotentiallyEvaluatedIfUsed:
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009089 Diag(Loc, PD);
9090 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009091
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009092 case PotentiallyPotentiallyEvaluated:
9093 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9094 break;
9095 }
9096
9097 return false;
9098}
9099
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009100bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9101 CallExpr *CE, FunctionDecl *FD) {
9102 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9103 return false;
9104
9105 PartialDiagnostic Note =
9106 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9107 << FD->getDeclName() : PDiag();
9108 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009109
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009110 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009111 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009112 PDiag(diag::err_call_function_incomplete_return)
9113 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009114 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009115 << CE->getSourceRange(),
9116 std::make_pair(NoteLoc, Note)))
9117 return true;
9118
9119 return false;
9120}
9121
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009122// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009123// will prevent this condition from triggering, which is what we want.
9124void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9125 SourceLocation Loc;
9126
John McCall0506e4a2009-11-11 02:41:58 +00009127 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009128 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009129
John McCalld5707ab2009-10-12 21:59:07 +00009130 if (isa<BinaryOperator>(E)) {
9131 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009132 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009133 return;
9134
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009135 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9136
John McCallb0e419e2009-11-12 00:06:05 +00009137 // Greylist some idioms by putting them into a warning subcategory.
9138 if (ObjCMessageExpr *ME
9139 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9140 Selector Sel = ME->getSelector();
9141
John McCallb0e419e2009-11-12 00:06:05 +00009142 // self = [<foo> init...]
9143 if (isSelfExpr(Op->getLHS())
9144 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
9145 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9146
9147 // <foo> = [<bar> nextObject]
9148 else if (Sel.isUnarySelector() &&
9149 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
9150 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9151 }
John McCall0506e4a2009-11-11 02:41:58 +00009152
John McCalld5707ab2009-10-12 21:59:07 +00009153 Loc = Op->getOperatorLoc();
9154 } else if (isa<CXXOperatorCallExpr>(E)) {
9155 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009156 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009157 return;
9158
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009159 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009160 Loc = Op->getOperatorLoc();
9161 } else {
9162 // Not an assignment.
9163 return;
9164 }
9165
John McCalld5707ab2009-10-12 21:59:07 +00009166 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00009167 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009168
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009169 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009170
9171 if (IsOrAssign)
9172 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9173 << FixItHint::CreateReplacement(Loc, "!=");
9174 else
9175 Diag(Loc, diag::note_condition_assign_to_comparison)
9176 << FixItHint::CreateReplacement(Loc, "==");
9177
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009178 Diag(Loc, diag::note_condition_assign_silence)
9179 << FixItHint::CreateInsertion(Open, "(")
9180 << FixItHint::CreateInsertion(Close, ")");
John McCalld5707ab2009-10-12 21:59:07 +00009181}
9182
9183bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
9184 DiagnoseAssignmentAsCondition(E);
9185
9186 if (!E->isTypeDependent()) {
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009187 if (E->isBoundMemberFunction(Context))
9188 return Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9189 << E->getSourceRange();
9190
John McCall34376a62010-12-04 03:47:34 +00009191 if (getLangOptions().CPlusPlus)
9192 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9193
9194 DefaultFunctionArrayLvalueConversion(E);
John McCall29cb2fd2010-12-04 06:09:13 +00009195
9196 QualType T = E->getType();
John McCall34376a62010-12-04 03:47:34 +00009197 if (!T->isScalarType()) // C99 6.8.4.1p1
9198 return Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9199 << T << E->getSourceRange();
John McCalld5707ab2009-10-12 21:59:07 +00009200 }
9201
9202 return false;
9203}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009204
John McCalldadc5752010-08-24 06:29:42 +00009205ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9206 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00009207 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009208 return ExprError();
9209
Douglas Gregorb412e172010-07-25 18:17:45 +00009210 if (CheckBooleanCondition(Sub, Loc))
Douglas Gregore60e41a2010-05-06 17:25:47 +00009211 return ExprError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00009212
9213 return Owned(Sub);
9214}
John McCall36e7fe32010-10-12 00:20:44 +00009215
9216/// Check for operands with placeholder types and complain if found.
9217/// Returns true if there was an error and no recovery was possible.
9218ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) {
9219 const BuiltinType *BT = E->getType()->getAs<BuiltinType>();
9220 if (!BT || !BT->isPlaceholderType()) return Owned(E);
9221
9222 // If this is overload, check for a single overload.
9223 if (BT->getKind() == BuiltinType::Overload) {
9224 if (FunctionDecl *Specialization
9225 = ResolveSingleFunctionTemplateSpecialization(E)) {
9226 // The access doesn't really matter in this case.
9227 DeclAccessPair Found = DeclAccessPair::make(Specialization,
9228 Specialization->getAccess());
9229 E = FixOverloadedFunctionReference(E, Found, Specialization);
9230 if (!E) return ExprError();
9231 return Owned(E);
9232 }
9233
John McCall36226622010-10-12 02:09:17 +00009234 Diag(Loc, diag::err_ovl_unresolvable) << E->getSourceRange();
John McCall36e7fe32010-10-12 00:20:44 +00009235 return ExprError();
9236 }
9237
9238 // Otherwise it's a use of undeduced auto.
9239 assert(BT->getKind() == BuiltinType::UndeducedAuto);
9240
9241 DeclRefExpr *DRE = cast<DeclRefExpr>(E->IgnoreParens());
9242 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
9243 << DRE->getDecl() << E->getSourceRange();
9244 return ExprError();
9245}