blob: ae0ed3e4f168439e291dcaf2b3db43434a60b7ca [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
Richard Smith30482bc2011-02-20 03:19:35 +000078 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +000079 if (ParsingInitForAutoVars.count(D)) {
80 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
81 << D->getDeclName();
82 return true;
Richard Smith30482bc2011-02-20 03:19:35 +000083 }
84
Chris Lattner4bf74fd2009-02-15 22:43:40 +000085 // See if the decl is deprecated.
Benjamin Kramerbfac7dc2010-10-09 15:49:00 +000086 if (const DeprecatedAttr *DA = D->getAttr<DeprecatedAttr>())
Peter Collingbourneed12ffb2011-01-02 19:53:12 +000087 EmitDeprecationWarning(D, DA->getMessage(), Loc, UnknownObjCClass);
Chris Lattner4bf74fd2009-02-15 22:43:40 +000088
Chris Lattnera27dd592009-10-25 17:21:40 +000089 // See if the decl is unavailable
Fariborz Jahanianc74073c2010-10-06 23:12:32 +000090 if (const UnavailableAttr *UA = D->getAttr<UnavailableAttr>()) {
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000091 if (UA->getMessage().empty()) {
Peter Collingbourneed12ffb2011-01-02 19:53:12 +000092 if (!UnknownObjCClass)
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000093 Diag(Loc, diag::err_unavailable) << D->getDeclName();
94 else
95 Diag(Loc, diag::warn_unavailable_fwdclass_message)
96 << D->getDeclName();
97 }
98 else
Fariborz Jahanianc74073c2010-10-06 23:12:32 +000099 Diag(Loc, diag::err_unavailable_message)
Benjamin Kramerbfac7dc2010-10-09 15:49:00 +0000100 << D->getDeclName() << UA->getMessage();
Chris Lattnera27dd592009-10-25 17:21:40 +0000101 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
102 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000103
Douglas Gregor171c45a2009-02-18 21:56:37 +0000104 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +0000105 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +0000106 if (FD->isDeleted()) {
107 Diag(Loc, diag::err_deleted_function_use);
108 Diag(D->getLocation(), diag::note_unavailable_here) << true;
109 return true;
110 }
Douglas Gregorde681d42009-02-24 04:26:15 +0000111 }
Douglas Gregor171c45a2009-02-18 21:56:37 +0000112
Anders Carlsson73067a02010-10-22 23:37:08 +0000113 // Warn if this is used but marked unused.
114 if (D->hasAttr<UnusedAttr>())
115 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
116
Douglas Gregor171c45a2009-02-18 21:56:37 +0000117 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000118}
119
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000120/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +0000121/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000122/// attribute. It warns if call does not have the sentinel argument.
123///
124void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000125 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000126 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000127 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000128 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000129
130 // FIXME: In C++0x, if any of the arguments are parameter pack
131 // expansions, we can't check for the sentinel now.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000132 int sentinelPos = attr->getSentinel();
133 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +0000134
Mike Stump87c57ac2009-05-16 07:39:55 +0000135 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
136 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000137 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000138 bool warnNotEnoughArgs = false;
139 int isMethod = 0;
140 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
141 // skip over named parameters.
142 ObjCMethodDecl::param_iterator P, E = MD->param_end();
143 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
144 if (nullPos)
145 --nullPos;
146 else
147 ++i;
148 }
149 warnNotEnoughArgs = (P != E || i >= NumArgs);
150 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000151 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000152 // skip over named parameters.
153 ObjCMethodDecl::param_iterator P, E = FD->param_end();
154 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
155 if (nullPos)
156 --nullPos;
157 else
158 ++i;
159 }
160 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000161 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000162 // block or function pointer call.
163 QualType Ty = V->getType();
164 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000165 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000166 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
167 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000168 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
169 unsigned NumArgsInProto = Proto->getNumArgs();
170 unsigned k;
171 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
172 if (nullPos)
173 --nullPos;
174 else
175 ++i;
176 }
177 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
178 }
179 if (Ty->isBlockPointerType())
180 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000181 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000182 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000183 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000184 return;
185
186 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000187 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000188 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000189 return;
190 }
191 int sentinel = i;
192 while (sentinelPos > 0 && i < NumArgs-1) {
193 --sentinelPos;
194 ++i;
195 }
196 if (sentinelPos > 0) {
197 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000198 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000199 return;
200 }
201 while (i < NumArgs-1) {
202 ++i;
203 ++sentinel;
204 }
205 Expr *sentinelExpr = Args[sentinel];
John McCall7ddbcf42010-05-06 23:53:00 +0000206 if (!sentinelExpr) return;
207 if (sentinelExpr->isTypeDependent()) return;
208 if (sentinelExpr->isValueDependent()) return;
Anders Carlssone981a8c2010-11-05 15:21:33 +0000209
210 // nullptr_t is always treated as null.
211 if (sentinelExpr->getType()->isNullPtrType()) return;
212
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000213 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000214 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
215 Expr::NPC_ValueDependentIsNull))
216 return;
217
218 // Unfortunately, __null has type 'int'.
219 if (isa<GNUNullExpr>(sentinelExpr)) return;
220
221 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
222 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000223}
224
Douglas Gregor87f95b02009-02-26 21:00:50 +0000225SourceRange Sema::getExprRange(ExprTy *E) const {
226 Expr *Ex = (Expr *)E;
227 return Ex? Ex->getSourceRange() : SourceRange();
228}
229
Chris Lattner513165e2008-07-25 21:10:04 +0000230//===----------------------------------------------------------------------===//
231// Standard Promotions and Conversions
232//===----------------------------------------------------------------------===//
233
Chris Lattner513165e2008-07-25 21:10:04 +0000234/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
235void Sema::DefaultFunctionArrayConversion(Expr *&E) {
236 QualType Ty = E->getType();
237 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
238
Chris Lattner513165e2008-07-25 21:10:04 +0000239 if (Ty->isFunctionType())
Mike Stump11289f42009-09-09 15:08:12 +0000240 ImpCastExprToType(E, Context.getPointerType(Ty),
John McCalle3027922010-08-25 11:45:40 +0000241 CK_FunctionToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000242 else if (Ty->isArrayType()) {
243 // In C90 mode, arrays only promote to pointers if the array expression is
244 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
245 // type 'array of type' is converted to an expression that has type 'pointer
246 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
247 // that has type 'array of type' ...". The relevant change is "an lvalue"
248 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000249 //
250 // C++ 4.2p1:
251 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
252 // T" can be converted to an rvalue of type "pointer to T".
253 //
John McCall086a4642010-11-24 05:12:34 +0000254 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
Anders Carlsson8fc489d2009-08-07 23:48:20 +0000255 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
John McCalle3027922010-08-25 11:45:40 +0000256 CK_ArrayToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000257 }
Chris Lattner513165e2008-07-25 21:10:04 +0000258}
259
John McCall27584242010-12-06 20:48:59 +0000260void Sema::DefaultLvalueConversion(Expr *&E) {
John McCallf3735e02010-12-01 04:43:34 +0000261 // C++ [conv.lval]p1:
262 // A glvalue of a non-function, non-array type T can be
263 // converted to a prvalue.
John McCall27584242010-12-06 20:48:59 +0000264 if (!E->isGLValue()) return;
John McCall34376a62010-12-04 03:47:34 +0000265
John McCall27584242010-12-06 20:48:59 +0000266 QualType T = E->getType();
267 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000268
John McCall27584242010-12-06 20:48:59 +0000269 // Create a load out of an ObjCProperty l-value, if necessary.
270 if (E->getObjectKind() == OK_ObjCProperty) {
271 ConvertPropertyForRValue(E);
272 if (!E->isGLValue())
John McCall34376a62010-12-04 03:47:34 +0000273 return;
Douglas Gregorb92a1562010-02-03 00:27:59 +0000274 }
John McCall27584242010-12-06 20:48:59 +0000275
276 // We don't want to throw lvalue-to-rvalue casts on top of
277 // expressions of certain types in C++.
278 if (getLangOptions().CPlusPlus &&
279 (E->getType() == Context.OverloadTy ||
280 T->isDependentType() ||
281 T->isRecordType()))
282 return;
283
284 // The C standard is actually really unclear on this point, and
285 // DR106 tells us what the result should be but not why. It's
286 // generally best to say that void types just doesn't undergo
287 // lvalue-to-rvalue at all. Note that expressions of unqualified
288 // 'void' type are never l-values, but qualified void can be.
289 if (T->isVoidType())
290 return;
291
292 // C++ [conv.lval]p1:
293 // [...] If T is a non-class type, the type of the prvalue is the
294 // cv-unqualified version of T. Otherwise, the type of the
295 // rvalue is T.
296 //
297 // C99 6.3.2.1p2:
298 // If the lvalue has qualified type, the value has the unqualified
299 // version of the type of the lvalue; otherwise, the value has the
300 // type of the lvalue.
301 if (T.hasQualifiers())
302 T = T.getUnqualifiedType();
303
Ted Kremenek64699be2011-02-16 01:57:07 +0000304 if (const ArraySubscriptExpr *ae = dyn_cast<ArraySubscriptExpr>(E))
305 CheckArrayAccess(ae);
306
John McCall27584242010-12-06 20:48:59 +0000307 E = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
308 E, 0, VK_RValue);
309}
310
311void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
312 DefaultFunctionArrayConversion(E);
313 DefaultLvalueConversion(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000314}
315
316
Chris Lattner513165e2008-07-25 21:10:04 +0000317/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000318/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-07-25 21:10:04 +0000319/// sometimes surpressed. For example, the array->pointer conversion doesn't
320/// apply if the array is an argument to the sizeof or address (&) operators.
321/// In these instances, this routine should *not* be called.
John McCallf3735e02010-12-01 04:43:34 +0000322Expr *Sema::UsualUnaryConversions(Expr *&E) {
323 // First, convert to an r-value.
324 DefaultFunctionArrayLvalueConversion(E);
325
326 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000327 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000328
329 // Try to perform integral promotions if the object has a theoretically
330 // promotable type.
331 if (Ty->isIntegralOrUnscopedEnumerationType()) {
332 // C99 6.3.1.1p2:
333 //
334 // The following may be used in an expression wherever an int or
335 // unsigned int may be used:
336 // - an object or expression with an integer type whose integer
337 // conversion rank is less than or equal to the rank of int
338 // and unsigned int.
339 // - A bit-field of type _Bool, int, signed int, or unsigned int.
340 //
341 // If an int can represent all values of the original type, the
342 // value is converted to an int; otherwise, it is converted to an
343 // unsigned int. These are called the integer promotions. All
344 // other types are unchanged by the integer promotions.
345
346 QualType PTy = Context.isPromotableBitField(E);
347 if (!PTy.isNull()) {
348 ImpCastExprToType(E, PTy, CK_IntegralCast);
349 return E;
350 }
351 if (Ty->isPromotableIntegerType()) {
352 QualType PT = Context.getPromotedIntegerType(Ty);
353 ImpCastExprToType(E, PT, CK_IntegralCast);
354 return E;
355 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000356 }
357
John McCallf3735e02010-12-01 04:43:34 +0000358 return E;
Chris Lattner513165e2008-07-25 21:10:04 +0000359}
360
Chris Lattner2ce500f2008-07-25 22:25:12 +0000361/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000362/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000363/// double. All other argument types are converted by UsualUnaryConversions().
364void Sema::DefaultArgumentPromotion(Expr *&Expr) {
365 QualType Ty = Expr->getType();
366 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000367
John McCall9bc26772010-12-06 18:36:11 +0000368 UsualUnaryConversions(Expr);
369
Chris Lattner2ce500f2008-07-25 22:25:12 +0000370 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000371 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John McCall9bc26772010-12-06 18:36:11 +0000372 return ImpCastExprToType(Expr, Context.DoubleTy, CK_FloatingCast);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000373}
374
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000375/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
376/// will warn if the resulting type is not a POD type, and rejects ObjC
377/// interfaces passed by value. This returns true if the argument type is
378/// completely illegal.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000379bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
380 FunctionDecl *FDecl) {
Anders Carlssona7d069d2009-01-16 16:48:51 +0000381 DefaultArgumentPromotion(Expr);
Mike Stump11289f42009-09-09 15:08:12 +0000382
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000383 // __builtin_va_start takes the second argument as a "varargs" argument, but
384 // it doesn't actually do anything with it. It doesn't need to be non-pod
385 // etc.
386 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
387 return false;
388
John McCall8b07ec22010-05-15 11:32:37 +0000389 if (Expr->getType()->isObjCObjectType() &&
Ted Kremenek3427fac2011-02-23 01:52:04 +0000390 DiagRuntimeBehavior(Expr->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000391 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
392 << Expr->getType() << CT))
393 return true;
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000394
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000395 if (!Expr->getType()->isPODType() &&
Ted Kremenek3427fac2011-02-23 01:52:04 +0000396 DiagRuntimeBehavior(Expr->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000397 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
398 << Expr->getType() << CT))
399 return true;
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000400
401 return false;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000402}
403
Chris Lattner513165e2008-07-25 21:10:04 +0000404/// UsualArithmeticConversions - Performs various conversions that are common to
405/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000406/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000407/// responsible for emitting appropriate error diagnostics.
408/// FIXME: verify the conversion rules for "complex int" are consistent with
409/// GCC.
410QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
411 bool isCompAssign) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000412 if (!isCompAssign)
Chris Lattner513165e2008-07-25 21:10:04 +0000413 UsualUnaryConversions(lhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000414
415 UsualUnaryConversions(rhsExpr);
Douglas Gregora11693b2008-11-12 17:17:38 +0000416
Mike Stump11289f42009-09-09 15:08:12 +0000417 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000418 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000419 QualType lhs =
420 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000421 QualType rhs =
Chris Lattner574dee62008-07-26 22:17:49 +0000422 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000423
424 // If both types are identical, no conversion is needed.
425 if (lhs == rhs)
426 return lhs;
427
428 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
429 // The caller can deal with this (e.g. pointer + int).
430 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
431 return lhs;
432
John McCalld005ac92010-11-13 08:17:45 +0000433 // Apply unary and bitfield promotions to the LHS's type.
434 QualType lhs_unpromoted = lhs;
435 if (lhs->isPromotableIntegerType())
436 lhs = Context.getPromotedIntegerType(lhs);
Eli Friedman629ffb92009-08-20 04:21:42 +0000437 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000438 if (!LHSBitfieldPromoteTy.isNull())
439 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000440 if (lhs != lhs_unpromoted && !isCompAssign)
441 ImpCastExprToType(lhsExpr, lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000442
John McCalld005ac92010-11-13 08:17:45 +0000443 // If both types are identical, no conversion is needed.
444 if (lhs == rhs)
445 return lhs;
446
447 // At this point, we have two different arithmetic types.
448
449 // Handle complex types first (C99 6.3.1.8p1).
450 bool LHSComplexFloat = lhs->isComplexType();
451 bool RHSComplexFloat = rhs->isComplexType();
452 if (LHSComplexFloat || RHSComplexFloat) {
453 // if we have an integer operand, the result is the complex type.
454
John McCallc5e62b42010-11-13 09:02:35 +0000455 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
456 if (rhs->isIntegerType()) {
457 QualType fp = cast<ComplexType>(lhs)->getElementType();
458 ImpCastExprToType(rhsExpr, fp, CK_IntegralToFloating);
459 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
460 } else {
461 assert(rhs->isComplexIntegerType());
John McCalld7646252010-11-14 08:17:51 +0000462 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000463 }
John McCalld005ac92010-11-13 08:17:45 +0000464 return lhs;
465 }
466
John McCallc5e62b42010-11-13 09:02:35 +0000467 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
468 if (!isCompAssign) {
469 // int -> float -> _Complex float
470 if (lhs->isIntegerType()) {
471 QualType fp = cast<ComplexType>(rhs)->getElementType();
472 ImpCastExprToType(lhsExpr, fp, CK_IntegralToFloating);
473 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
474 } else {
475 assert(lhs->isComplexIntegerType());
John McCalld7646252010-11-14 08:17:51 +0000476 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000477 }
478 }
John McCalld005ac92010-11-13 08:17:45 +0000479 return rhs;
480 }
481
482 // This handles complex/complex, complex/float, or float/complex.
483 // When both operands are complex, the shorter operand is converted to the
484 // type of the longer, and that is the type of the result. This corresponds
485 // to what is done when combining two real floating-point operands.
486 // The fun begins when size promotion occur across type domains.
487 // From H&S 6.3.4: When one operand is complex and the other is a real
488 // floating-point type, the less precise type is converted, within it's
489 // real or complex domain, to the precision of the other type. For example,
490 // when combining a "long double" with a "double _Complex", the
491 // "double _Complex" is promoted to "long double _Complex".
492 int order = Context.getFloatingTypeOrder(lhs, rhs);
493
494 // If both are complex, just cast to the more precise type.
495 if (LHSComplexFloat && RHSComplexFloat) {
496 if (order > 0) {
497 // _Complex float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000498 ImpCastExprToType(rhsExpr, lhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000499 return lhs;
500
501 } else if (order < 0) {
502 // _Complex float -> _Complex double
503 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000504 ImpCastExprToType(lhsExpr, rhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000505 return rhs;
506 }
507 return lhs;
508 }
509
510 // If just the LHS is complex, the RHS needs to be converted,
511 // and the LHS might need to be promoted.
512 if (LHSComplexFloat) {
513 if (order > 0) { // LHS is wider
514 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000515 QualType fp = cast<ComplexType>(lhs)->getElementType();
516 ImpCastExprToType(rhsExpr, fp, CK_FloatingCast);
517 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000518 return lhs;
519 }
520
521 // RHS is at least as wide. Find its corresponding complex type.
522 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
523
524 // double -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000525 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000526
527 // _Complex float -> _Complex double
528 if (!isCompAssign && order < 0)
John McCallc5e62b42010-11-13 09:02:35 +0000529 ImpCastExprToType(lhsExpr, result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000530
531 return result;
532 }
533
534 // Just the RHS is complex, so the LHS needs to be converted
535 // and the RHS might need to be promoted.
536 assert(RHSComplexFloat);
537
538 if (order < 0) { // RHS is wider
539 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000540 if (!isCompAssign) {
Argyrios Kyrtzidise84389b2011-01-18 18:49:33 +0000541 QualType fp = cast<ComplexType>(rhs)->getElementType();
542 ImpCastExprToType(lhsExpr, fp, CK_FloatingCast);
John McCallc5e62b42010-11-13 09:02:35 +0000543 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
544 }
John McCalld005ac92010-11-13 08:17:45 +0000545 return rhs;
546 }
547
548 // LHS is at least as wide. Find its corresponding complex type.
549 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
550
551 // double -> _Complex double
552 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000553 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000554
555 // _Complex float -> _Complex double
556 if (order > 0)
John McCallc5e62b42010-11-13 09:02:35 +0000557 ImpCastExprToType(rhsExpr, result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000558
559 return result;
560 }
561
562 // Now handle "real" floating types (i.e. float, double, long double).
563 bool LHSFloat = lhs->isRealFloatingType();
564 bool RHSFloat = rhs->isRealFloatingType();
565 if (LHSFloat || RHSFloat) {
566 // If we have two real floating types, convert the smaller operand
567 // to the bigger result.
568 if (LHSFloat && RHSFloat) {
569 int order = Context.getFloatingTypeOrder(lhs, rhs);
570 if (order > 0) {
571 ImpCastExprToType(rhsExpr, lhs, CK_FloatingCast);
572 return lhs;
573 }
574
575 assert(order < 0 && "illegal float comparison");
576 if (!isCompAssign)
577 ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast);
578 return rhs;
579 }
580
581 // If we have an integer operand, the result is the real floating type.
582 if (LHSFloat) {
583 if (rhs->isIntegerType()) {
584 // Convert rhs to the lhs floating point type.
585 ImpCastExprToType(rhsExpr, lhs, CK_IntegralToFloating);
586 return lhs;
587 }
588
589 // Convert both sides to the appropriate complex float.
590 assert(rhs->isComplexIntegerType());
591 QualType result = Context.getComplexType(lhs);
592
593 // _Complex int -> _Complex float
John McCalld7646252010-11-14 08:17:51 +0000594 ImpCastExprToType(rhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000595
596 // float -> _Complex float
597 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000598 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000599
600 return result;
601 }
602
603 assert(RHSFloat);
604 if (lhs->isIntegerType()) {
605 // Convert lhs to the rhs floating point type.
606 if (!isCompAssign)
607 ImpCastExprToType(lhsExpr, rhs, CK_IntegralToFloating);
608 return rhs;
609 }
610
611 // Convert both sides to the appropriate complex float.
612 assert(lhs->isComplexIntegerType());
613 QualType result = Context.getComplexType(rhs);
614
615 // _Complex int -> _Complex float
616 if (!isCompAssign)
John McCalld7646252010-11-14 08:17:51 +0000617 ImpCastExprToType(lhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000618
619 // float -> _Complex float
John McCallc5e62b42010-11-13 09:02:35 +0000620 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000621
622 return result;
623 }
624
625 // Handle GCC complex int extension.
626 // FIXME: if the operands are (int, _Complex long), we currently
627 // don't promote the complex. Also, signedness?
628 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
629 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
630 if (lhsComplexInt && rhsComplexInt) {
631 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
632 rhsComplexInt->getElementType());
633 assert(order && "inequal types with equal element ordering");
634 if (order > 0) {
635 // _Complex int -> _Complex long
John McCallc5e62b42010-11-13 09:02:35 +0000636 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000637 return lhs;
638 }
639
640 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000641 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000642 return rhs;
643 } else if (lhsComplexInt) {
644 // int -> _Complex int
John McCallc5e62b42010-11-13 09:02:35 +0000645 ImpCastExprToType(rhsExpr, lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000646 return lhs;
647 } else if (rhsComplexInt) {
648 // int -> _Complex int
649 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000650 ImpCastExprToType(lhsExpr, rhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000651 return rhs;
652 }
653
654 // Finally, we have two differing integer types.
655 // The rules for this case are in C99 6.3.1.8
656 int compare = Context.getIntegerTypeOrder(lhs, rhs);
657 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
658 rhsSigned = rhs->hasSignedIntegerRepresentation();
659 if (lhsSigned == rhsSigned) {
660 // Same signedness; use the higher-ranked type
661 if (compare >= 0) {
662 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
663 return lhs;
664 } else if (!isCompAssign)
665 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
666 return rhs;
667 } else if (compare != (lhsSigned ? 1 : -1)) {
668 // The unsigned type has greater than or equal rank to the
669 // signed type, so use the unsigned type
670 if (rhsSigned) {
671 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
672 return lhs;
673 } else if (!isCompAssign)
674 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
675 return rhs;
676 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
677 // The two types are different widths; if we are here, that
678 // means the signed type is larger than the unsigned type, so
679 // use the signed type.
680 if (lhsSigned) {
681 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
682 return lhs;
683 } else if (!isCompAssign)
684 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
685 return rhs;
686 } else {
687 // The signed type is higher-ranked than the unsigned type,
688 // but isn't actually any bigger (like unsigned int and long
689 // on most 32-bit systems). Use the unsigned type corresponding
690 // to the signed type.
691 QualType result =
692 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
693 ImpCastExprToType(rhsExpr, result, CK_IntegralCast);
694 if (!isCompAssign)
695 ImpCastExprToType(lhsExpr, result, CK_IntegralCast);
696 return result;
697 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000698}
699
Chris Lattner513165e2008-07-25 21:10:04 +0000700//===----------------------------------------------------------------------===//
701// Semantic Analysis for various Expression Types
702//===----------------------------------------------------------------------===//
703
704
Steve Naroff83895f72007-09-16 03:34:24 +0000705/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000706/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
707/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
708/// multiple tokens. However, the common case is that StringToks points to one
709/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000710///
John McCalldadc5752010-08-24 06:29:42 +0000711ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +0000712Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000713 assert(NumStringToks && "Must have at least one string!");
714
Chris Lattner8a24e582009-01-16 18:51:42 +0000715 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000716 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000717 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000718
Chris Lattner23b7eb62007-06-15 23:05:46 +0000719 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000720 for (unsigned i = 0; i != NumStringToks; ++i)
721 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000722
Chris Lattner36fc8792008-02-11 00:02:17 +0000723 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidiscbad7252008-08-09 17:20:01 +0000724 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattner36fc8792008-02-11 00:02:17 +0000725 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000726
727 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +0000728 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000729 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000730
Chris Lattner36fc8792008-02-11 00:02:17 +0000731 // Get an array type for the string, according to C99 6.4.5. This includes
732 // the nul terminator character as well as the string length for pascal
733 // strings.
734 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000735 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000736 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000737
Chris Lattner5b183d82006-11-10 05:03:26 +0000738 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +0000739 return Owned(StringLiteral::Create(Context, Literal.GetString(),
740 Literal.GetStringLength(),
741 Literal.AnyWide, StrTy,
742 &StringTokLocs[0],
743 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000744}
745
John McCallc63de662011-02-02 13:00:07 +0000746enum CaptureResult {
747 /// No capture is required.
748 CR_NoCapture,
749
750 /// A capture is required.
751 CR_Capture,
752
John McCall351762c2011-02-07 10:33:21 +0000753 /// A by-ref capture is required.
754 CR_CaptureByRef,
755
John McCallc63de662011-02-02 13:00:07 +0000756 /// An error occurred when trying to capture the given variable.
757 CR_Error
758};
759
760/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +0000761///
John McCallc63de662011-02-02 13:00:07 +0000762/// \param var - the variable referenced
763/// \param DC - the context which we couldn't capture through
764static CaptureResult
John McCall351762c2011-02-07 10:33:21 +0000765diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +0000766 VarDecl *var, DeclContext *DC) {
767 switch (S.ExprEvalContexts.back().Context) {
768 case Sema::Unevaluated:
769 // The argument will never be evaluated, so don't complain.
770 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +0000771
John McCallc63de662011-02-02 13:00:07 +0000772 case Sema::PotentiallyEvaluated:
773 case Sema::PotentiallyEvaluatedIfUsed:
774 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +0000775
John McCallc63de662011-02-02 13:00:07 +0000776 case Sema::PotentiallyPotentiallyEvaluated:
777 // FIXME: delay these!
778 break;
Chris Lattner497d7b02009-04-21 22:26:47 +0000779 }
Mike Stump11289f42009-09-09 15:08:12 +0000780
John McCallc63de662011-02-02 13:00:07 +0000781 // Don't diagnose about capture if we're not actually in code right
782 // now; in general, there are more appropriate places that will
783 // diagnose this.
784 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
785
786 // This particular madness can happen in ill-formed default
787 // arguments; claim it's okay and let downstream code handle it.
788 if (isa<ParmVarDecl>(var) &&
789 S.CurContext == var->getDeclContext()->getParent())
790 return CR_NoCapture;
791
792 DeclarationName functionName;
793 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
794 functionName = fn->getDeclName();
795 // FIXME: variable from enclosing block that we couldn't capture from!
796
797 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
798 << var->getIdentifier() << functionName;
799 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
800 << var->getIdentifier();
801
802 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +0000803}
804
John McCall351762c2011-02-07 10:33:21 +0000805/// There is a well-formed capture at a particular scope level;
806/// propagate it through all the nested blocks.
807static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
808 const BlockDecl::Capture &capture) {
809 VarDecl *var = capture.getVariable();
810
811 // Update all the inner blocks with the capture information.
812 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
813 i != e; ++i) {
814 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
815 innerBlock->Captures.push_back(
816 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
817 /*nested*/ true, capture.getCopyExpr()));
818 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
819 }
820
821 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
822}
823
824/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +0000825/// given value in the current context requires a variable capture.
826///
827/// This also keeps the captures set in the BlockScopeInfo records
828/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +0000829static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +0000830 ValueDecl *value) {
831 // Only variables ever require capture.
832 VarDecl *var = dyn_cast<VarDecl>(value);
John McCallf4cd4f92011-02-09 01:13:10 +0000833 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +0000834
835 // Fast path: variables from the current context never require capture.
836 DeclContext *DC = S.CurContext;
837 if (var->getDeclContext() == DC) return CR_NoCapture;
838
839 // Only variables with local storage require capture.
840 // FIXME: What about 'const' variables in C++?
841 if (!var->hasLocalStorage()) return CR_NoCapture;
842
843 // Otherwise, we need to capture.
844
845 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +0000846 do {
847 // Only blocks (and eventually C++0x closures) can capture; other
848 // scopes don't work.
849 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +0000850 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +0000851
852 BlockScopeInfo *blockScope =
853 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
854 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
855
John McCall351762c2011-02-07 10:33:21 +0000856 // Check whether we've already captured it in this block. If so,
857 // we're done.
858 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
859 return propagateCapture(S, functionScopesIndex,
860 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +0000861
862 functionScopesIndex--;
863 DC = cast<BlockDecl>(DC)->getDeclContext();
864 } while (var->getDeclContext() != DC);
865
John McCall351762c2011-02-07 10:33:21 +0000866 // Okay, we descended all the way to the block that defines the variable.
867 // Actually try to capture it.
868 QualType type = var->getType();
869
870 // Prohibit variably-modified types.
871 if (type->isVariablyModifiedType()) {
872 S.Diag(loc, diag::err_ref_vm_type);
873 S.Diag(var->getLocation(), diag::note_declared_at);
874 return CR_Error;
875 }
876
877 // Prohibit arrays, even in __block variables, but not references to
878 // them.
879 if (type->isArrayType()) {
880 S.Diag(loc, diag::err_ref_array_type);
881 S.Diag(var->getLocation(), diag::note_declared_at);
882 return CR_Error;
883 }
884
885 S.MarkDeclarationReferenced(loc, var);
886
887 // The BlocksAttr indicates the variable is bound by-reference.
888 bool byRef = var->hasAttr<BlocksAttr>();
889
890 // Build a copy expression.
891 Expr *copyExpr = 0;
892 if (!byRef && S.getLangOptions().CPlusPlus &&
893 !type->isDependentType() && type->isStructureOrClassType()) {
894 // According to the blocks spec, the capture of a variable from
895 // the stack requires a const copy constructor. This is not true
896 // of the copy/move done to move a __block variable to the heap.
897 type.addConst();
898
899 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
900 ExprResult result =
901 S.PerformCopyInitialization(
902 InitializedEntity::InitializeBlock(var->getLocation(),
903 type, false),
904 loc, S.Owned(declRef));
905
906 // Build a full-expression copy expression if initialization
907 // succeeded and used a non-trivial constructor. Recover from
908 // errors by pretending that the copy isn't necessary.
909 if (!result.isInvalid() &&
910 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
911 result = S.MaybeCreateExprWithCleanups(result);
912 copyExpr = result.take();
913 }
914 }
915
916 // We're currently at the declarer; go back to the closure.
917 functionScopesIndex++;
918 BlockScopeInfo *blockScope =
919 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
920
921 // Build a valid capture in this scope.
922 blockScope->Captures.push_back(
923 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
924 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
925
926 // Propagate that to inner captures if necessary.
927 return propagateCapture(S, functionScopesIndex,
928 blockScope->Captures.back());
929}
930
931static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
932 const DeclarationNameInfo &NameInfo,
933 bool byRef) {
934 assert(isa<VarDecl>(vd) && "capturing non-variable");
935
936 VarDecl *var = cast<VarDecl>(vd);
937 assert(var->hasLocalStorage() && "capturing non-local");
938 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
939
940 QualType exprType = var->getType().getNonReferenceType();
941
942 BlockDeclRefExpr *BDRE;
943 if (!byRef) {
944 // The variable will be bound by copy; make it const within the
945 // closure, but record that this was done in the expression.
946 bool constAdded = !exprType.isConstQualified();
947 exprType.addConst();
948
949 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
950 NameInfo.getLoc(), false,
951 constAdded);
952 } else {
953 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
954 NameInfo.getLoc(), true);
955 }
956
957 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +0000958}
Chris Lattner2a9d9892008-10-20 05:16:36 +0000959
John McCalldadc5752010-08-24 06:29:42 +0000960ExprResult
John McCall7decc9e2010-11-18 06:31:45 +0000961Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +0000962 SourceLocation Loc,
963 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000964 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +0000965 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000966}
967
John McCallf4cd4f92011-02-09 01:13:10 +0000968/// BuildDeclRefExpr - Build an expression that references a
969/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +0000970ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +0000971Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000972 const DeclarationNameInfo &NameInfo,
973 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000974 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +0000975
John McCall086a4642010-11-24 05:12:34 +0000976 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000977 SS? SS->getWithLocInContext(Context)
978 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +0000979 D, NameInfo, Ty, VK);
980
981 // Just in case we're building an illegal pointer-to-member.
982 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
983 E->setObjectKind(OK_BitField);
984
985 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000986}
987
John McCallfeb624a2010-11-23 20:48:44 +0000988static ExprResult
989BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
990 const CXXScopeSpec &SS, FieldDecl *Field,
991 DeclAccessPair FoundDecl,
992 const DeclarationNameInfo &MemberNameInfo);
993
John McCalldadc5752010-08-24 06:29:42 +0000994ExprResult
John McCallf3a88602011-02-03 08:15:49 +0000995Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
996 SourceLocation loc,
997 IndirectFieldDecl *indirectField,
998 Expr *baseObjectExpr,
999 SourceLocation opLoc) {
1000 // First, build the expression that refers to the base object.
1001
1002 bool baseObjectIsPointer = false;
1003 Qualifiers baseQuals;
1004
1005 // Case 1: the base of the indirect field is not a field.
1006 VarDecl *baseVariable = indirectField->getVarDecl();
Douglas Gregore10f36d2011-02-18 02:44:58 +00001007 CXXScopeSpec EmptySS;
John McCallf3a88602011-02-03 08:15:49 +00001008 if (baseVariable) {
1009 assert(baseVariable->getType()->isRecordType());
1010
1011 // In principle we could have a member access expression that
1012 // accesses an anonymous struct/union that's a static member of
1013 // the base object's class. However, under the current standard,
1014 // static data members cannot be anonymous structs or unions.
1015 // Supporting this is as easy as building a MemberExpr here.
1016 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1017
1018 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1019
1020 ExprResult result =
Douglas Gregore10f36d2011-02-18 02:44:58 +00001021 BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
John McCallf3a88602011-02-03 08:15:49 +00001022 if (result.isInvalid()) return ExprError();
1023
1024 baseObjectExpr = result.take();
1025 baseObjectIsPointer = false;
1026 baseQuals = baseObjectExpr->getType().getQualifiers();
1027
1028 // Case 2: the base of the indirect field is a field and the user
1029 // wrote a member expression.
1030 } else if (baseObjectExpr) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001031 // The caller provided the base object expression. Determine
1032 // whether its a pointer and whether it adds any qualifiers to the
1033 // anonymous struct/union fields we're looking into.
John McCallf3a88602011-02-03 08:15:49 +00001034 QualType objectType = baseObjectExpr->getType();
1035
1036 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1037 baseObjectIsPointer = true;
1038 objectType = ptr->getPointeeType();
1039 } else {
1040 baseObjectIsPointer = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001041 }
John McCallf3a88602011-02-03 08:15:49 +00001042 baseQuals = objectType.getQualifiers();
1043
1044 // Case 3: the base of the indirect field is a field and we should
1045 // build an implicit member access.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001046 } else {
1047 // We've found a member of an anonymous struct/union that is
1048 // inside a non-anonymous struct/union, so in a well-formed
1049 // program our base object expression is "this".
John McCallf3a88602011-02-03 08:15:49 +00001050 CXXMethodDecl *method = tryCaptureCXXThis();
1051 if (!method) {
1052 Diag(loc, diag::err_invalid_member_use_in_static_method)
1053 << indirectField->getDeclName();
1054 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001055 }
1056
John McCallf3a88602011-02-03 08:15:49 +00001057 // Our base object expression is "this".
1058 baseObjectExpr =
1059 new (Context) CXXThisExpr(loc, method->getThisType(Context),
1060 /*isImplicit=*/ true);
1061 baseObjectIsPointer = true;
1062 baseQuals = Qualifiers::fromCVRMask(method->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001063 }
1064
1065 // Build the implicit member references to the field of the
1066 // anonymous struct/union.
John McCallf3a88602011-02-03 08:15:49 +00001067 Expr *result = baseObjectExpr;
1068 IndirectFieldDecl::chain_iterator
1069 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCallfeb624a2010-11-23 20:48:44 +00001070
John McCallf3a88602011-02-03 08:15:49 +00001071 // Build the first member access in the chain with full information.
1072 if (!baseVariable) {
1073 FieldDecl *field = cast<FieldDecl>(*FI);
John McCallfeb624a2010-11-23 20:48:44 +00001074
John McCallf3a88602011-02-03 08:15:49 +00001075 // FIXME: use the real found-decl info!
1076 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall8ccfcb52009-09-24 19:53:00 +00001077
John McCallf3a88602011-02-03 08:15:49 +00001078 // Make a nameInfo that properly uses the anonymous name.
1079 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall8ccfcb52009-09-24 19:53:00 +00001080
John McCallf3a88602011-02-03 08:15:49 +00001081 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001082 EmptySS, field, foundDecl,
John McCallf3a88602011-02-03 08:15:49 +00001083 memberNameInfo).take();
1084 baseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +00001085
John McCallf3a88602011-02-03 08:15:49 +00001086 // FIXME: check qualified member access
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001087 }
1088
John McCallf3a88602011-02-03 08:15:49 +00001089 // In all cases, we should now skip the first declaration in the chain.
1090 ++FI;
1091
Douglas Gregore10f36d2011-02-18 02:44:58 +00001092 while (FI != FEnd) {
1093 FieldDecl *field = cast<FieldDecl>(*FI++);
John McCallf3a88602011-02-03 08:15:49 +00001094
1095 // FIXME: these are somewhat meaningless
1096 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1097 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCallf3a88602011-02-03 08:15:49 +00001098
1099 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001100 (FI == FEnd? SS : EmptySS), field,
1101 foundDecl, memberNameInfo)
John McCallf3a88602011-02-03 08:15:49 +00001102 .take();
1103 }
1104
1105 return Owned(result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001106}
1107
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001108/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001109/// possibly a list of template arguments.
1110///
1111/// If this produces template arguments, it is permitted to call
1112/// DecomposeTemplateName.
1113///
1114/// This actually loses a lot of source location information for
1115/// non-standard name kinds; we should consider preserving that in
1116/// some way.
1117static void DecomposeUnqualifiedId(Sema &SemaRef,
1118 const UnqualifiedId &Id,
1119 TemplateArgumentListInfo &Buffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001120 DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00001121 const TemplateArgumentListInfo *&TemplateArgs) {
1122 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1123 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1124 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1125
1126 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1127 Id.TemplateId->getTemplateArgs(),
1128 Id.TemplateId->NumArgs);
1129 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1130 TemplateArgsPtr.release();
1131
John McCall3e56fd42010-08-23 07:28:44 +00001132 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001133 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1134 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001135 TemplateArgs = &Buffer;
1136 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001137 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001138 TemplateArgs = 0;
1139 }
1140}
1141
John McCall2d74de92009-12-01 22:10:20 +00001142/// Determines if the given class is provably not derived from all of
1143/// the prospective base classes.
1144static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1145 CXXRecordDecl *Record,
1146 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +00001147 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +00001148 return false;
1149
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001150 RecordDecl *RD = Record->getDefinition();
John McCalla6d407c2009-12-01 22:28:41 +00001151 if (!RD) return false;
1152 Record = cast<CXXRecordDecl>(RD);
1153
John McCall2d74de92009-12-01 22:10:20 +00001154 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1155 E = Record->bases_end(); I != E; ++I) {
1156 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1157 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1158 if (!BaseRT) return false;
1159
1160 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +00001161 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1162 return false;
1163 }
1164
1165 return true;
1166}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001167
John McCall2d74de92009-12-01 22:10:20 +00001168enum IMAKind {
1169 /// The reference is definitely not an instance member access.
1170 IMA_Static,
1171
1172 /// The reference may be an implicit instance member access.
1173 IMA_Mixed,
1174
1175 /// The reference may be to an instance member, but it is invalid if
1176 /// so, because the context is not an instance method.
1177 IMA_Mixed_StaticContext,
1178
1179 /// The reference may be to an instance member, but it is invalid if
1180 /// so, because the context is from an unrelated class.
1181 IMA_Mixed_Unrelated,
1182
1183 /// The reference is definitely an implicit instance member access.
1184 IMA_Instance,
1185
1186 /// The reference may be to an unresolved using declaration.
1187 IMA_Unresolved,
1188
1189 /// The reference may be to an unresolved using declaration and the
1190 /// context is not an instance method.
1191 IMA_Unresolved_StaticContext,
1192
John McCall2d74de92009-12-01 22:10:20 +00001193 /// All possible referrents are instance members and the current
1194 /// context is not an instance method.
1195 IMA_Error_StaticContext,
1196
1197 /// All possible referrents are instance members of an unrelated
1198 /// class.
1199 IMA_Error_Unrelated
1200};
1201
1202/// The given lookup names class member(s) and is not being used for
1203/// an address-of-member expression. Classify the type of access
1204/// according to whether it's possible that this reference names an
1205/// instance member. This is best-effort; it is okay to
1206/// conservatively answer "yes", in which case some errors will simply
1207/// not be caught until template-instantiation.
1208static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1209 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +00001210 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +00001211
John McCall87fe5d52010-05-20 01:18:31 +00001212 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCall2d74de92009-12-01 22:10:20 +00001213 bool isStaticContext =
John McCall87fe5d52010-05-20 01:18:31 +00001214 (!isa<CXXMethodDecl>(DC) ||
1215 cast<CXXMethodDecl>(DC)->isStatic());
John McCall2d74de92009-12-01 22:10:20 +00001216
1217 if (R.isUnresolvableResult())
1218 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1219
1220 // Collect all the declaring classes of instance members we find.
1221 bool hasNonInstance = false;
Sebastian Redl34620312010-11-26 16:28:07 +00001222 bool hasField = false;
John McCall2d74de92009-12-01 22:10:20 +00001223 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1224 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCalla8ae2222010-04-06 21:38:20 +00001225 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00001226
John McCalla8ae2222010-04-06 21:38:20 +00001227 if (D->isCXXInstanceMember()) {
Sebastian Redl34620312010-11-26 16:28:07 +00001228 if (dyn_cast<FieldDecl>(D))
1229 hasField = true;
1230
John McCall2d74de92009-12-01 22:10:20 +00001231 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCall2d74de92009-12-01 22:10:20 +00001232 Classes.insert(R->getCanonicalDecl());
1233 }
1234 else
1235 hasNonInstance = true;
1236 }
1237
1238 // If we didn't find any instance members, it can't be an implicit
1239 // member reference.
1240 if (Classes.empty())
1241 return IMA_Static;
1242
1243 // If the current context is not an instance method, it can't be
1244 // an implicit member reference.
Sebastian Redl34620312010-11-26 16:28:07 +00001245 if (isStaticContext) {
1246 if (hasNonInstance)
1247 return IMA_Mixed_StaticContext;
1248
1249 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1250 // C++0x [expr.prim.general]p10:
1251 // An id-expression that denotes a non-static data member or non-static
1252 // member function of a class can only be used:
1253 // (...)
1254 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1255 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1256 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1257 if (isUnevaluatedExpression)
1258 return IMA_Mixed_StaticContext;
1259 }
1260
1261 return IMA_Error_StaticContext;
1262 }
John McCall2d74de92009-12-01 22:10:20 +00001263
1264 // If we can prove that the current context is unrelated to all the
1265 // declaring classes, it can't be an implicit member reference (in
1266 // which case it's an error if any of those members are selected).
1267 if (IsProvablyNotDerivedFrom(SemaRef,
John McCall87fe5d52010-05-20 01:18:31 +00001268 cast<CXXMethodDecl>(DC)->getParent(),
John McCall2d74de92009-12-01 22:10:20 +00001269 Classes))
1270 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1271
1272 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1273}
1274
1275/// Diagnose a reference to a field with no object available.
1276static void DiagnoseInstanceReference(Sema &SemaRef,
1277 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00001278 NamedDecl *rep,
1279 const DeclarationNameInfo &nameInfo) {
1280 SourceLocation Loc = nameInfo.getLoc();
John McCall2d74de92009-12-01 22:10:20 +00001281 SourceRange Range(Loc);
1282 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1283
John McCallf3a88602011-02-03 08:15:49 +00001284 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCall2d74de92009-12-01 22:10:20 +00001285 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1286 if (MD->isStatic()) {
1287 // "invalid use of member 'x' in static member function"
1288 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCallf3a88602011-02-03 08:15:49 +00001289 << Range << nameInfo.getName();
John McCall2d74de92009-12-01 22:10:20 +00001290 return;
1291 }
1292 }
1293
1294 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCallf3a88602011-02-03 08:15:49 +00001295 << nameInfo.getName() << Range;
John McCall2d74de92009-12-01 22:10:20 +00001296 return;
1297 }
1298
1299 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +00001300}
1301
John McCalld681c392009-12-16 08:11:27 +00001302/// Diagnose an empty lookup.
1303///
1304/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001305bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1306 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +00001307 DeclarationName Name = R.getLookupName();
1308
John McCalld681c392009-12-16 08:11:27 +00001309 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001310 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001311 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1312 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001313 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001314 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001315 diagnostic_suggest = diag::err_undeclared_use_suggest;
1316 }
John McCalld681c392009-12-16 08:11:27 +00001317
Douglas Gregor598b08f2009-12-31 05:20:13 +00001318 // If the original lookup was an unqualified lookup, fake an
1319 // unqualified lookup. This is useful when (for example) the
1320 // original lookup would not have found something because it was a
1321 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001322 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001323 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001324 if (isa<CXXRecordDecl>(DC)) {
1325 LookupQualifiedName(R, DC);
1326
1327 if (!R.empty()) {
1328 // Don't give errors about ambiguities in this lookup.
1329 R.suppressDiagnostics();
1330
1331 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1332 bool isInstance = CurMethod &&
1333 CurMethod->isInstance() &&
1334 DC == CurMethod->getParent();
1335
1336 // Give a code modification hint to insert 'this->'.
1337 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1338 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001339 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001340 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1341 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001342 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001343 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001344 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001345 Diag(R.getNameLoc(), diagnostic) << Name
1346 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1347 QualType DepThisType = DepMethod->getThisType(Context);
1348 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1349 R.getNameLoc(), DepThisType, false);
1350 TemplateArgumentListInfo TList;
1351 if (ULE->hasExplicitTemplateArgs())
1352 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001353
Douglas Gregore16af532011-02-28 18:50:33 +00001354 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001355 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001356 CXXDependentScopeMemberExpr *DepExpr =
1357 CXXDependentScopeMemberExpr::Create(
1358 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001359 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyfe712382010-08-20 20:54:15 +00001360 R.getLookupNameInfo(), &TList);
1361 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001362 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001363 // FIXME: we should be able to handle this case too. It is correct
1364 // to add this-> here. This is a workaround for PR7947.
1365 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001366 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001367 } else {
John McCalld681c392009-12-16 08:11:27 +00001368 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001369 }
John McCalld681c392009-12-16 08:11:27 +00001370
1371 // Do we really want to note all of these?
1372 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1373 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1374
1375 // Tell the callee to try to recover.
1376 return false;
1377 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001378
1379 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001380 }
1381 }
1382
Douglas Gregor598b08f2009-12-31 05:20:13 +00001383 // We didn't find anything, so try to correct for a typo.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001384 DeclarationName Corrected;
Daniel Dunbarf7ced252010-06-02 15:46:52 +00001385 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001386 if (!R.empty()) {
1387 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1388 if (SS.isEmpty())
1389 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1390 << FixItHint::CreateReplacement(R.getNameLoc(),
1391 R.getLookupName().getAsString());
1392 else
1393 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1394 << Name << computeDeclContext(SS, false) << R.getLookupName()
1395 << SS.getRange()
1396 << FixItHint::CreateReplacement(R.getNameLoc(),
1397 R.getLookupName().getAsString());
1398 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1399 Diag(ND->getLocation(), diag::note_previous_decl)
1400 << ND->getDeclName();
1401
1402 // Tell the callee to try to recover.
1403 return false;
1404 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001405
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001406 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1407 // FIXME: If we ended up with a typo for a type name or
1408 // Objective-C class name, we're in trouble because the parser
1409 // is in the wrong place to recover. Suggest the typo
1410 // correction, but don't make it a fix-it since we're not going
1411 // to recover well anyway.
1412 if (SS.isEmpty())
1413 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1414 else
1415 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1416 << Name << computeDeclContext(SS, false) << R.getLookupName()
1417 << SS.getRange();
1418
1419 // Don't try to recover; it won't work.
1420 return true;
1421 }
1422 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001423 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001424 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001425 if (SS.isEmpty())
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001426 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001427 else
Douglas Gregor25363982010-01-01 00:15:04 +00001428 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001429 << Name << computeDeclContext(SS, false) << Corrected
1430 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001431 return true;
1432 }
Douglas Gregor25363982010-01-01 00:15:04 +00001433 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001434 }
1435
1436 // Emit a special diagnostic for failed member lookups.
1437 // FIXME: computing the declaration context might fail here (?)
1438 if (!SS.isEmpty()) {
1439 Diag(R.getNameLoc(), diag::err_no_member)
1440 << Name << computeDeclContext(SS, false)
1441 << SS.getRange();
1442 return true;
1443 }
1444
John McCalld681c392009-12-16 08:11:27 +00001445 // Give up, we can't recover.
1446 Diag(R.getNameLoc(), diagnostic) << Name;
1447 return true;
1448}
1449
Douglas Gregor05fcf842010-11-02 20:36:02 +00001450ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1451 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001452 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1453 if (!IDecl)
1454 return 0;
1455 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1456 if (!ClassImpDecl)
1457 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001458 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001459 if (!property)
1460 return 0;
1461 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001462 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1463 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001464 return 0;
1465 return property;
1466}
1467
Douglas Gregor05fcf842010-11-02 20:36:02 +00001468bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1469 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1470 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1471 if (!IDecl)
1472 return false;
1473 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1474 if (!ClassImpDecl)
1475 return false;
1476 if (ObjCPropertyImplDecl *PIDecl
1477 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1478 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1479 PIDecl->getPropertyIvarDecl())
1480 return false;
1481
1482 return true;
1483}
1484
Fariborz Jahanian18722982010-07-17 00:59:30 +00001485static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001486 LookupResult &Lookup,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001487 IdentifierInfo *II,
1488 SourceLocation NameLoc) {
1489 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001490 bool LookForIvars;
1491 if (Lookup.empty())
1492 LookForIvars = true;
1493 else if (CurMeth->isClassMethod())
1494 LookForIvars = false;
1495 else
1496 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001497 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1498 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001499 if (!LookForIvars)
1500 return 0;
1501
Fariborz Jahanian18722982010-07-17 00:59:30 +00001502 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1503 if (!IDecl)
1504 return 0;
1505 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001506 if (!ClassImpDecl)
1507 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001508 bool DynamicImplSeen = false;
1509 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1510 if (!property)
1511 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001512 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001513 DynamicImplSeen =
1514 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001515 // property implementation has a designated ivar. No need to assume a new
1516 // one.
1517 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1518 return 0;
1519 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001520 if (!DynamicImplSeen) {
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001521 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1522 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001523 NameLoc,
1524 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001525 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001526 (Expr *)0, true);
1527 ClassImpDecl->addDecl(Ivar);
1528 IDecl->makeDeclVisibleInContext(Ivar, false);
1529 property->setPropertyIvarDecl(Ivar);
1530 return Ivar;
1531 }
1532 return 0;
1533}
1534
John McCalldadc5752010-08-24 06:29:42 +00001535ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001536 CXXScopeSpec &SS,
1537 UnqualifiedId &Id,
1538 bool HasTrailingLParen,
1539 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001540 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1541 "cannot be direct & operand and have a trailing lparen");
1542
1543 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001544 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001545
John McCall10eae182009-11-30 22:42:35 +00001546 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001547
1548 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001549 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001550 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001551 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001552
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001553 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001554 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001555 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001556
John McCalle66edc12009-11-24 19:00:30 +00001557 // C++ [temp.dep.expr]p3:
1558 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001559 // -- an identifier that was declared with a dependent type,
1560 // (note: handled after lookup)
1561 // -- a template-id that is dependent,
1562 // (note: handled in BuildTemplateIdExpr)
1563 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001564 // -- a nested-name-specifier that contains a class-name that
1565 // names a dependent type.
1566 // Determine whether this is a member of an unknown specialization;
1567 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001568 bool DependentID = false;
1569 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1570 Name.getCXXNameType()->isDependentType()) {
1571 DependentID = true;
1572 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001573 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001574 if (RequireCompleteDeclContext(SS, DC))
1575 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001576 } else {
1577 DependentID = true;
1578 }
1579 }
1580
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001581 if (DependentID)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001582 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001583 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001584
Fariborz Jahanian86151342010-07-22 23:33:21 +00001585 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001586 // Perform the required lookup.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001587 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001588 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001589 // Lookup the template name again to correctly establish the context in
1590 // which it was found. This is really unfortunate as we already did the
1591 // lookup to determine that it was a template name in the first place. If
1592 // this becomes a performance hit, we can work harder to preserve those
1593 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001594 bool MemberOfUnknownSpecialization;
1595 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1596 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001597
1598 if (MemberOfUnknownSpecialization ||
1599 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1600 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1601 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001602 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001603 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001604 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001605
Douglas Gregora5226932011-02-04 13:35:07 +00001606 // If the result might be in a dependent base class, this is a dependent
1607 // id-expression.
1608 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1609 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1610 TemplateArgs);
1611
John McCalle66edc12009-11-24 19:00:30 +00001612 // If this reference is in an Objective-C method, then we need to do
1613 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001614 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001615 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001616 if (E.isInvalid())
1617 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001618
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001619 if (Expr *Ex = E.takeAs<Expr>())
1620 return Owned(Ex);
1621
1622 // Synthesize ivars lazily.
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001623 if (getLangOptions().ObjCDefaultSynthProperties &&
1624 getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001625 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1626 if (const ObjCPropertyDecl *Property =
1627 canSynthesizeProvisionalIvar(II)) {
1628 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1629 Diag(Property->getLocation(), diag::note_property_declare);
1630 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001631 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1632 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001633 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001634 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001635 // for further use, this must be set to false if in class method.
1636 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001637 }
Chris Lattner59a25942008-03-31 00:36:02 +00001638 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001639
John McCalle66edc12009-11-24 19:00:30 +00001640 if (R.isAmbiguous())
1641 return ExprError();
1642
Douglas Gregor171c45a2009-02-18 21:56:37 +00001643 // Determine whether this name might be a candidate for
1644 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001645 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001646
John McCalle66edc12009-11-24 19:00:30 +00001647 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001648 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001649 // in C90, extension in C99, forbidden in C++).
1650 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1651 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1652 if (D) R.addDecl(D);
1653 }
1654
1655 // If this name wasn't predeclared and if this is not a function
1656 // call, diagnose the problem.
1657 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001658 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001659 return ExprError();
1660
1661 assert(!R.empty() &&
1662 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001663
1664 // If we found an Objective-C instance variable, let
1665 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001666 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001667 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1668 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001669 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001670 assert(E.isInvalid() || E.get());
1671 return move(E);
1672 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001673 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001674 }
Mike Stump11289f42009-09-09 15:08:12 +00001675
John McCalle66edc12009-11-24 19:00:30 +00001676 // This is guaranteed from this point on.
1677 assert(!R.empty() || ADL);
1678
John McCall2d74de92009-12-01 22:10:20 +00001679 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001680 // C++ [class.mfct.non-static]p3:
1681 // When an id-expression that is not part of a class member access
1682 // syntax and not used to form a pointer to member is used in the
1683 // body of a non-static member function of class X, if name lookup
1684 // resolves the name in the id-expression to a non-static non-type
1685 // member of some class C, the id-expression is transformed into a
1686 // class member access expression using (*this) as the
1687 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001688 //
1689 // But we don't actually need to do this for '&' operands if R
1690 // resolved to a function or overloaded function set, because the
1691 // expression is ill-formed if it actually works out to be a
1692 // non-static member function:
1693 //
1694 // C++ [expr.ref]p4:
1695 // Otherwise, if E1.E2 refers to a non-static member function. . .
1696 // [t]he expression can be used only as the left-hand operand of a
1697 // member function call.
1698 //
1699 // There are other safeguards against such uses, but it's important
1700 // to get this right here so that we don't end up making a
1701 // spuriously dependent expression if we're inside a dependent
1702 // instance method.
John McCall57500772009-12-16 12:17:52 +00001703 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001704 bool MightBeImplicitMember;
1705 if (!isAddressOfOperand)
1706 MightBeImplicitMember = true;
1707 else if (!SS.isEmpty())
1708 MightBeImplicitMember = false;
1709 else if (R.isOverloadedResult())
1710 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001711 else if (R.isUnresolvableResult())
1712 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001713 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001714 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1715 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001716
1717 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001718 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001719 }
1720
John McCalle66edc12009-11-24 19:00:30 +00001721 if (TemplateArgs)
1722 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001723
John McCalle66edc12009-11-24 19:00:30 +00001724 return BuildDeclarationNameExpr(SS, R, ADL);
1725}
1726
John McCall57500772009-12-16 12:17:52 +00001727/// Builds an expression which might be an implicit member expression.
John McCalldadc5752010-08-24 06:29:42 +00001728ExprResult
John McCall57500772009-12-16 12:17:52 +00001729Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1730 LookupResult &R,
1731 const TemplateArgumentListInfo *TemplateArgs) {
1732 switch (ClassifyImplicitMemberAccess(*this, R)) {
1733 case IMA_Instance:
1734 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1735
John McCall57500772009-12-16 12:17:52 +00001736 case IMA_Mixed:
1737 case IMA_Mixed_Unrelated:
1738 case IMA_Unresolved:
1739 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1740
1741 case IMA_Static:
1742 case IMA_Mixed_StaticContext:
1743 case IMA_Unresolved_StaticContext:
1744 if (TemplateArgs)
1745 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1746 return BuildDeclarationNameExpr(SS, R, false);
1747
1748 case IMA_Error_StaticContext:
1749 case IMA_Error_Unrelated:
John McCallf3a88602011-02-03 08:15:49 +00001750 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
1751 R.getLookupNameInfo());
John McCall57500772009-12-16 12:17:52 +00001752 return ExprError();
1753 }
1754
1755 llvm_unreachable("unexpected instance member access kind");
1756 return ExprError();
1757}
1758
John McCall10eae182009-11-30 22:42:35 +00001759/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1760/// declaration name, generally during template instantiation.
1761/// There's a large number of things which don't need to be done along
1762/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001763ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001764Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001765 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001766 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001767 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001768 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001769
John McCall0b66eb32010-05-01 00:40:08 +00001770 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001771 return ExprError();
1772
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001773 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001774 LookupQualifiedName(R, DC);
1775
1776 if (R.isAmbiguous())
1777 return ExprError();
1778
1779 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001780 Diag(NameInfo.getLoc(), diag::err_no_member)
1781 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001782 return ExprError();
1783 }
1784
1785 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1786}
1787
1788/// LookupInObjCMethod - The parser has read a name in, and Sema has
1789/// detected that we're currently inside an ObjC method. Perform some
1790/// additional lookup.
1791///
1792/// Ideally, most of this would be done by lookup, but there's
1793/// actually quite a lot of extra work involved.
1794///
1795/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001796ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001797Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001798 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001799 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001800 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001801
John McCalle66edc12009-11-24 19:00:30 +00001802 // There are two cases to handle here. 1) scoped lookup could have failed,
1803 // in which case we should look for an ivar. 2) scoped lookup could have
1804 // found a decl, but that decl is outside the current instance method (i.e.
1805 // a global variable). In these two cases, we do a lookup for an ivar with
1806 // this name, if the lookup sucedes, we replace it our current decl.
1807
1808 // If we're in a class method, we don't normally want to look for
1809 // ivars. But if we don't find anything else, and there's an
1810 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001811 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001812
1813 bool LookForIvars;
1814 if (Lookup.empty())
1815 LookForIvars = true;
1816 else if (IsClassMethod)
1817 LookForIvars = false;
1818 else
1819 LookForIvars = (Lookup.isSingleResult() &&
1820 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001821 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001822 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001823 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001824 ObjCInterfaceDecl *ClassDeclared;
1825 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1826 // Diagnose using an ivar in a class method.
1827 if (IsClassMethod)
1828 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1829 << IV->getDeclName());
1830
1831 // If we're referencing an invalid decl, just return this as a silent
1832 // error node. The error diagnostic was already emitted on the decl.
1833 if (IV->isInvalidDecl())
1834 return ExprError();
1835
1836 // Check if referencing a field with __attribute__((deprecated)).
1837 if (DiagnoseUseOfDecl(IV, Loc))
1838 return ExprError();
1839
1840 // Diagnose the use of an ivar outside of the declaring class.
1841 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1842 ClassDeclared != IFace)
1843 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1844
1845 // FIXME: This should use a new expr for a direct reference, don't
1846 // turn this into Self->ivar, just return a BareIVarExpr or something.
1847 IdentifierInfo &II = Context.Idents.get("self");
1848 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001849 SelfName.setIdentifier(&II, SourceLocation());
John McCalle66edc12009-11-24 19:00:30 +00001850 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001851 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001852 SelfName, false, false);
1853 if (SelfExpr.isInvalid())
1854 return ExprError();
1855
John McCall27584242010-12-06 20:48:59 +00001856 Expr *SelfE = SelfExpr.take();
1857 DefaultLvalueConversion(SelfE);
1858
John McCalle66edc12009-11-24 19:00:30 +00001859 MarkDeclarationReferenced(Loc, IV);
1860 return Owned(new (Context)
1861 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John McCall27584242010-12-06 20:48:59 +00001862 SelfE, true, true));
John McCalle66edc12009-11-24 19:00:30 +00001863 }
Chris Lattner87313662010-04-12 05:10:17 +00001864 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001865 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001866 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001867 ObjCInterfaceDecl *ClassDeclared;
1868 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1869 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1870 IFace == ClassDeclared)
1871 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1872 }
1873 }
1874
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001875 if (Lookup.empty() && II && AllowBuiltinCreation) {
1876 // FIXME. Consolidate this with similar code in LookupName.
1877 if (unsigned BuiltinID = II->getBuiltinID()) {
1878 if (!(getLangOptions().CPlusPlus &&
1879 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1880 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1881 S, Lookup.isForRedeclaration(),
1882 Lookup.getNameLoc());
1883 if (D) Lookup.addDecl(D);
1884 }
1885 }
1886 }
John McCalle66edc12009-11-24 19:00:30 +00001887 // Sentinel value saying that we didn't do anything special.
1888 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001889}
John McCalld14a8642009-11-21 08:51:07 +00001890
John McCall16df1e52010-03-30 21:47:33 +00001891/// \brief Cast a base object to a member's actual type.
1892///
1893/// Logically this happens in three phases:
1894///
1895/// * First we cast from the base type to the naming class.
1896/// The naming class is the class into which we were looking
1897/// when we found the member; it's the qualifier type if a
1898/// qualifier was provided, and otherwise it's the base type.
1899///
1900/// * Next we cast from the naming class to the declaring class.
1901/// If the member we found was brought into a class's scope by
1902/// a using declaration, this is that class; otherwise it's
1903/// the class declaring the member.
1904///
1905/// * Finally we cast from the declaring class to the "true"
1906/// declaring class of the member. This conversion does not
1907/// obey access control.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001908bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001909Sema::PerformObjectMemberConversion(Expr *&From,
1910 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001911 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001912 NamedDecl *Member) {
1913 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1914 if (!RD)
1915 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001916
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001917 QualType DestRecordType;
1918 QualType DestType;
1919 QualType FromRecordType;
1920 QualType FromType = From->getType();
1921 bool PointerConversions = false;
1922 if (isa<FieldDecl>(Member)) {
1923 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001924
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001925 if (FromType->getAs<PointerType>()) {
1926 DestType = Context.getPointerType(DestRecordType);
1927 FromRecordType = FromType->getPointeeType();
1928 PointerConversions = true;
1929 } else {
1930 DestType = DestRecordType;
1931 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001932 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001933 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1934 if (Method->isStatic())
1935 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001936
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001937 DestType = Method->getThisType(Context);
1938 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001939
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001940 if (FromType->getAs<PointerType>()) {
1941 FromRecordType = FromType->getPointeeType();
1942 PointerConversions = true;
1943 } else {
1944 FromRecordType = FromType;
1945 DestType = DestRecordType;
1946 }
1947 } else {
1948 // No conversion necessary.
1949 return false;
1950 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001951
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001952 if (DestType->isDependentType() || FromType->isDependentType())
1953 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001954
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001955 // If the unqualified types are the same, no conversion is necessary.
1956 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1957 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001958
John McCall16df1e52010-03-30 21:47:33 +00001959 SourceRange FromRange = From->getSourceRange();
1960 SourceLocation FromLoc = FromRange.getBegin();
1961
John McCall2536c6d2010-08-25 10:28:54 +00001962 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001963
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001964 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001965 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001966 // class name.
1967 //
1968 // If the member was a qualified name and the qualified referred to a
1969 // specific base subobject type, we'll cast to that intermediate type
1970 // first and then to the object in which the member is declared. That allows
1971 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1972 //
1973 // class Base { public: int x; };
1974 // class Derived1 : public Base { };
1975 // class Derived2 : public Base { };
1976 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1977 //
1978 // void VeryDerived::f() {
1979 // x = 17; // error: ambiguous base subobjects
1980 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1981 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001982 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00001983 QualType QType = QualType(Qualifier->getAsType(), 0);
1984 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1985 assert(QType->isRecordType() && "lookup done with non-record type");
1986
1987 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1988
1989 // In C++98, the qualifier type doesn't actually have to be a base
1990 // type of the object type, in which case we just ignore it.
1991 // Otherwise build the appropriate casts.
1992 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00001993 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001994 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001995 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00001996 return true;
1997
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001998 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00001999 QType = Context.getPointerType(QType);
John McCall2536c6d2010-08-25 10:28:54 +00002000 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2001 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00002002
2003 FromType = QType;
2004 FromRecordType = QRecordType;
2005
2006 // If the qualifier type was the same as the destination type,
2007 // we're done.
2008 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2009 return false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002010 }
2011 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002012
John McCall16df1e52010-03-30 21:47:33 +00002013 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002014
John McCall16df1e52010-03-30 21:47:33 +00002015 // If we actually found the member through a using declaration, cast
2016 // down to the using declaration's type.
2017 //
2018 // Pointer equality is fine here because only one declaration of a
2019 // class ever has member declarations.
2020 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2021 assert(isa<UsingShadowDecl>(FoundDecl));
2022 QualType URecordType = Context.getTypeDeclType(
2023 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2024
2025 // We only need to do this if the naming-class to declaring-class
2026 // conversion is non-trivial.
2027 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2028 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002029 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002030 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002031 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00002032 return true;
Alexis Huntc46382e2010-04-28 23:02:27 +00002033
John McCall16df1e52010-03-30 21:47:33 +00002034 QualType UType = URecordType;
2035 if (PointerConversions)
2036 UType = Context.getPointerType(UType);
John McCalle3027922010-08-25 11:45:40 +00002037 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00002038 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00002039 FromType = UType;
2040 FromRecordType = URecordType;
2041 }
2042
2043 // We don't do access control for the conversion from the
2044 // declaring class to the true declaring class.
2045 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002046 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002047
John McCallcf142162010-08-07 06:22:56 +00002048 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002049 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2050 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002051 IgnoreAccess))
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002052 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002053
John McCalle3027922010-08-25 11:45:40 +00002054 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00002055 VK, &BasePath);
Fariborz Jahanian3f150832009-07-29 19:40:11 +00002056 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002057}
Douglas Gregor3256d042009-06-30 15:47:41 +00002058
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002059/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00002060static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00002061 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalla8ae2222010-04-06 21:38:20 +00002062 DeclAccessPair FoundDecl,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002063 const DeclarationNameInfo &MemberNameInfo,
2064 QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +00002065 ExprValueKind VK, ExprObjectKind OK,
John McCalle66edc12009-11-24 19:00:30 +00002066 const TemplateArgumentListInfo *TemplateArgs = 0) {
Douglas Gregorea972d32011-02-28 21:54:11 +00002067 return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002068 Member, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002069 TemplateArgs, Ty, VK, OK);
Douglas Gregorc1905232009-08-26 22:36:53 +00002070}
2071
John McCallfeb624a2010-11-23 20:48:44 +00002072static ExprResult
2073BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2074 const CXXScopeSpec &SS, FieldDecl *Field,
2075 DeclAccessPair FoundDecl,
2076 const DeclarationNameInfo &MemberNameInfo) {
2077 // x.a is an l-value if 'a' has a reference type. Otherwise:
2078 // x.a is an l-value/x-value/pr-value if the base is (and note
2079 // that *x is always an l-value), except that if the base isn't
2080 // an ordinary object then we must have an rvalue.
2081 ExprValueKind VK = VK_LValue;
2082 ExprObjectKind OK = OK_Ordinary;
2083 if (!IsArrow) {
2084 if (BaseExpr->getObjectKind() == OK_Ordinary)
2085 VK = BaseExpr->getValueKind();
2086 else
2087 VK = VK_RValue;
2088 }
2089 if (VK != VK_RValue && Field->isBitField())
2090 OK = OK_BitField;
2091
2092 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2093 QualType MemberType = Field->getType();
2094 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2095 MemberType = Ref->getPointeeType();
2096 VK = VK_LValue;
2097 } else {
2098 QualType BaseType = BaseExpr->getType();
2099 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2100
2101 Qualifiers BaseQuals = BaseType.getQualifiers();
2102
2103 // GC attributes are never picked up by members.
2104 BaseQuals.removeObjCGCAttr();
2105
2106 // CVR attributes from the base are picked up by members,
2107 // except that 'mutable' members don't pick up 'const'.
2108 if (Field->isMutable()) BaseQuals.removeConst();
2109
2110 Qualifiers MemberQuals
2111 = S.Context.getCanonicalType(MemberType).getQualifiers();
2112
2113 // TR 18037 does not allow fields to be declared with address spaces.
2114 assert(!MemberQuals.hasAddressSpace());
2115
2116 Qualifiers Combined = BaseQuals + MemberQuals;
2117 if (Combined != MemberQuals)
2118 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2119 }
2120
2121 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
2122 if (S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2123 FoundDecl, Field))
2124 return ExprError();
2125 return S.Owned(BuildMemberExpr(S.Context, BaseExpr, IsArrow, SS,
2126 Field, FoundDecl, MemberNameInfo,
2127 MemberType, VK, OK));
2128}
2129
John McCall2d74de92009-12-01 22:10:20 +00002130/// Builds an implicit member access expression. The current context
2131/// is known to be an instance method, and the given unqualified lookup
2132/// set is known to contain only instance members, at least one of which
2133/// is from an appropriate type.
John McCalldadc5752010-08-24 06:29:42 +00002134ExprResult
John McCall2d74de92009-12-01 22:10:20 +00002135Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2136 LookupResult &R,
2137 const TemplateArgumentListInfo *TemplateArgs,
2138 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00002139 assert(!R.empty() && !R.isAmbiguous());
2140
John McCallf3a88602011-02-03 08:15:49 +00002141 SourceLocation loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00002142
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002143 // We may have found a field within an anonymous union or struct
2144 // (C++ [class.union]).
John McCalle66edc12009-11-24 19:00:30 +00002145 // FIXME: template-ids inside anonymous structs?
Francois Pichet783dd6e2010-11-21 06:08:52 +00002146 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCallf3a88602011-02-03 08:15:49 +00002147 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002148
John McCallf3a88602011-02-03 08:15:49 +00002149 // If this is known to be an instance access, go ahead and build an
2150 // implicit 'this' expression now.
John McCall2d74de92009-12-01 22:10:20 +00002151 // 'this' expression now.
John McCallf3a88602011-02-03 08:15:49 +00002152 CXXMethodDecl *method = tryCaptureCXXThis();
2153 assert(method && "didn't correctly pre-flight capture of 'this'");
2154
2155 QualType thisType = method->getThisType(Context);
2156 Expr *baseExpr = 0; // null signifies implicit access
John McCall2d74de92009-12-01 22:10:20 +00002157 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00002158 SourceLocation Loc = R.getNameLoc();
2159 if (SS.getRange().isValid())
2160 Loc = SS.getRange().getBegin();
John McCallf3a88602011-02-03 08:15:49 +00002161 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002162 }
2163
John McCallf3a88602011-02-03 08:15:49 +00002164 return BuildMemberReferenceExpr(baseExpr, thisType,
John McCall2d74de92009-12-01 22:10:20 +00002165 /*OpLoc*/ SourceLocation(),
2166 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00002167 SS,
2168 /*FirstQualifierInScope*/ 0,
2169 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00002170}
2171
John McCalle66edc12009-11-24 19:00:30 +00002172bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002173 const LookupResult &R,
2174 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002175 // Only when used directly as the postfix-expression of a call.
2176 if (!HasTrailingLParen)
2177 return false;
2178
2179 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002180 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002181 return false;
2182
2183 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002184 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002185 return false;
2186
2187 // Turn off ADL when we find certain kinds of declarations during
2188 // normal lookup:
2189 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2190 NamedDecl *D = *I;
2191
2192 // C++0x [basic.lookup.argdep]p3:
2193 // -- a declaration of a class member
2194 // Since using decls preserve this property, we check this on the
2195 // original decl.
John McCall57500772009-12-16 12:17:52 +00002196 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002197 return false;
2198
2199 // C++0x [basic.lookup.argdep]p3:
2200 // -- a block-scope function declaration that is not a
2201 // using-declaration
2202 // NOTE: we also trigger this for function templates (in fact, we
2203 // don't check the decl type at all, since all other decl types
2204 // turn off ADL anyway).
2205 if (isa<UsingShadowDecl>(D))
2206 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2207 else if (D->getDeclContext()->isFunctionOrMethod())
2208 return false;
2209
2210 // C++0x [basic.lookup.argdep]p3:
2211 // -- a declaration that is neither a function or a function
2212 // template
2213 // And also for builtin functions.
2214 if (isa<FunctionDecl>(D)) {
2215 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2216
2217 // But also builtin functions.
2218 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2219 return false;
2220 } else if (!isa<FunctionTemplateDecl>(D))
2221 return false;
2222 }
2223
2224 return true;
2225}
2226
2227
John McCalld14a8642009-11-21 08:51:07 +00002228/// Diagnoses obvious problems with the use of the given declaration
2229/// as an expression. This is only actually called for lookups that
2230/// were not overloaded, and it doesn't promise that the declaration
2231/// will in fact be used.
2232static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2233 if (isa<TypedefDecl>(D)) {
2234 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2235 return true;
2236 }
2237
2238 if (isa<ObjCInterfaceDecl>(D)) {
2239 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2240 return true;
2241 }
2242
2243 if (isa<NamespaceDecl>(D)) {
2244 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2245 return true;
2246 }
2247
2248 return false;
2249}
2250
John McCalldadc5752010-08-24 06:29:42 +00002251ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002252Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002253 LookupResult &R,
2254 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002255 // If this is a single, fully-resolved result and we don't need ADL,
2256 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002257 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002258 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2259 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002260
2261 // We only need to check the declaration if there's exactly one
2262 // result, because in the overloaded case the results can only be
2263 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002264 if (R.isSingleResult() &&
2265 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002266 return ExprError();
2267
John McCall58cc69d2010-01-27 01:50:18 +00002268 // Otherwise, just build an unresolved lookup expression. Suppress
2269 // any lookup-related diagnostics; we'll hash these out later, when
2270 // we've picked a target.
2271 R.suppressDiagnostics();
2272
John McCalld14a8642009-11-21 08:51:07 +00002273 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002274 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002275 SS.getWithLocInContext(Context),
2276 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002277 NeedsADL, R.isOverloadedResult(),
2278 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002279
2280 return Owned(ULE);
2281}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002282
John McCalld14a8642009-11-21 08:51:07 +00002283/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002284ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002285Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002286 const DeclarationNameInfo &NameInfo,
2287 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002288 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002289 assert(!isa<FunctionTemplateDecl>(D) &&
2290 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002291
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002292 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002293 if (CheckDeclInExpr(*this, Loc, D))
2294 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002295
Douglas Gregore7488b92009-12-01 16:58:18 +00002296 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2297 // Specifically diagnose references to class templates that are missing
2298 // a template argument list.
2299 Diag(Loc, diag::err_template_decl_ref)
2300 << Template << SS.getRange();
2301 Diag(Template->getLocation(), diag::note_template_decl_here);
2302 return ExprError();
2303 }
2304
2305 // Make sure that we're referring to a value.
2306 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2307 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002308 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002309 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002310 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002311 return ExprError();
2312 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002313
Douglas Gregor171c45a2009-02-18 21:56:37 +00002314 // Check whether this declaration can be used. Note that we suppress
2315 // this check when we're going to perform argument-dependent lookup
2316 // on this function name, because this might not be the function
2317 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002318 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002319 return ExprError();
2320
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002321 // Only create DeclRefExpr's for valid Decl's.
2322 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002323 return ExprError();
2324
John McCallf3a88602011-02-03 08:15:49 +00002325 // Handle members of anonymous structs and unions. If we got here,
2326 // and the reference is to a class member indirect field, then this
2327 // must be the subject of a pointer-to-member expression.
2328 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2329 if (!indirectField->isCXXClassMember())
2330 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2331 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002332
Chris Lattner2a9d9892008-10-20 05:16:36 +00002333 // If the identifier reference is inside a block, and it refers to a value
2334 // that is outside the block, create a BlockDeclRefExpr instead of a
2335 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2336 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002337 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002338 // We do not do this for things like enum constants, global variables, etc,
2339 // as they do not get snapshotted.
2340 //
John McCall351762c2011-02-07 10:33:21 +00002341 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002342 case CR_Error:
2343 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002344
John McCallc63de662011-02-02 13:00:07 +00002345 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002346 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2347 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2348
2349 case CR_CaptureByRef:
2350 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2351 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002352
2353 case CR_NoCapture: {
2354 // If this reference is not in a block or if the referenced
2355 // variable is within the block, create a normal DeclRefExpr.
2356
2357 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002358 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002359
2360 switch (D->getKind()) {
2361 // Ignore all the non-ValueDecl kinds.
2362#define ABSTRACT_DECL(kind)
2363#define VALUE(type, base)
2364#define DECL(type, base) \
2365 case Decl::type:
2366#include "clang/AST/DeclNodes.inc"
2367 llvm_unreachable("invalid value decl kind");
2368 return ExprError();
2369
2370 // These shouldn't make it here.
2371 case Decl::ObjCAtDefsField:
2372 case Decl::ObjCIvar:
2373 llvm_unreachable("forming non-member reference to ivar?");
2374 return ExprError();
2375
2376 // Enum constants are always r-values and never references.
2377 // Unresolved using declarations are dependent.
2378 case Decl::EnumConstant:
2379 case Decl::UnresolvedUsingValue:
2380 valueKind = VK_RValue;
2381 break;
2382
2383 // Fields and indirect fields that got here must be for
2384 // pointer-to-member expressions; we just call them l-values for
2385 // internal consistency, because this subexpression doesn't really
2386 // exist in the high-level semantics.
2387 case Decl::Field:
2388 case Decl::IndirectField:
2389 assert(getLangOptions().CPlusPlus &&
2390 "building reference to field in C?");
2391
2392 // These can't have reference type in well-formed programs, but
2393 // for internal consistency we do this anyway.
2394 type = type.getNonReferenceType();
2395 valueKind = VK_LValue;
2396 break;
2397
2398 // Non-type template parameters are either l-values or r-values
2399 // depending on the type.
2400 case Decl::NonTypeTemplateParm: {
2401 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2402 type = reftype->getPointeeType();
2403 valueKind = VK_LValue; // even if the parameter is an r-value reference
2404 break;
2405 }
2406
2407 // For non-references, we need to strip qualifiers just in case
2408 // the template parameter was declared as 'const int' or whatever.
2409 valueKind = VK_RValue;
2410 type = type.getUnqualifiedType();
2411 break;
2412 }
2413
2414 case Decl::Var:
2415 // In C, "extern void blah;" is valid and is an r-value.
2416 if (!getLangOptions().CPlusPlus &&
2417 !type.hasQualifiers() &&
2418 type->isVoidType()) {
2419 valueKind = VK_RValue;
2420 break;
2421 }
2422 // fallthrough
2423
2424 case Decl::ImplicitParam:
2425 case Decl::ParmVar:
2426 // These are always l-values.
2427 valueKind = VK_LValue;
2428 type = type.getNonReferenceType();
2429 break;
2430
2431 case Decl::Function: {
2432 // Functions are l-values in C++.
2433 if (getLangOptions().CPlusPlus) {
2434 valueKind = VK_LValue;
2435 break;
2436 }
2437
2438 // C99 DR 316 says that, if a function type comes from a
2439 // function definition (without a prototype), that type is only
2440 // used for checking compatibility. Therefore, when referencing
2441 // the function, we pretend that we don't have the full function
2442 // type.
2443 if (!cast<FunctionDecl>(VD)->hasPrototype())
2444 if (const FunctionProtoType *proto = type->getAs<FunctionProtoType>())
2445 type = Context.getFunctionNoProtoType(proto->getResultType(),
2446 proto->getExtInfo());
2447
2448 // Functions are r-values in C.
2449 valueKind = VK_RValue;
2450 break;
2451 }
2452
2453 case Decl::CXXMethod:
2454 // C++ methods are l-values if static, r-values if non-static.
2455 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2456 valueKind = VK_LValue;
2457 break;
2458 }
2459 // fallthrough
2460
2461 case Decl::CXXConversion:
2462 case Decl::CXXDestructor:
2463 case Decl::CXXConstructor:
2464 valueKind = VK_RValue;
2465 break;
2466 }
2467
2468 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2469 }
2470
John McCallc63de662011-02-02 13:00:07 +00002471 }
John McCall7decc9e2010-11-18 06:31:45 +00002472
John McCall351762c2011-02-07 10:33:21 +00002473 llvm_unreachable("unknown capture result");
2474 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002475}
Chris Lattnere168f762006-11-10 05:29:30 +00002476
John McCalldadc5752010-08-24 06:29:42 +00002477ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Sebastian Redlffbcf962009-01-18 18:53:16 +00002478 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002479 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002480
Chris Lattnere168f762006-11-10 05:29:30 +00002481 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002482 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002483 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2484 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2485 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002486 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002487
Chris Lattnera81a0272008-01-12 08:14:25 +00002488 // Pre-defined identifiers are of type char[x], where x is the length of the
2489 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002490
Anders Carlsson2fb08242009-09-08 18:24:21 +00002491 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002492 if (!currentDecl && getCurBlock())
2493 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002494 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002495 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002496 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002497 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002498
Anders Carlsson0b209a82009-09-11 01:22:35 +00002499 QualType ResTy;
2500 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2501 ResTy = Context.DependentTy;
2502 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002503 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002504
Anders Carlsson0b209a82009-09-11 01:22:35 +00002505 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002506 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002507 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2508 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002509 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002510}
2511
John McCalldadc5752010-08-24 06:29:42 +00002512ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002513 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002514 bool Invalid = false;
2515 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2516 if (Invalid)
2517 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002518
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002519 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2520 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00002521 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002522 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002523
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002524 QualType Ty;
2525 if (!getLangOptions().CPlusPlus)
2526 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2527 else if (Literal.isWide())
2528 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002529 else if (Literal.isMultiChar())
2530 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002531 else
2532 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002533
Sebastian Redl20614a72009-01-20 22:23:13 +00002534 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2535 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002536 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002537}
2538
John McCalldadc5752010-08-24 06:29:42 +00002539ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002540 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002541 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2542 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002543 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002544 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002545 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002546 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002547 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002548
Chris Lattner23b7eb62007-06-15 23:05:46 +00002549 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002550 // Add padding so that NumericLiteralParser can overread by one character.
2551 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002552 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002553
Chris Lattner67ca9252007-05-21 01:08:44 +00002554 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002555 bool Invalid = false;
2556 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2557 if (Invalid)
2558 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002559
Mike Stump11289f42009-09-09 15:08:12 +00002560 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002561 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002562 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002563 return ExprError();
2564
Chris Lattner1c20a172007-08-26 03:42:43 +00002565 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002566
Chris Lattner1c20a172007-08-26 03:42:43 +00002567 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002568 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002569 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002570 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002571 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002572 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002573 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002574 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002575
2576 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2577
John McCall53b93a02009-12-24 09:08:04 +00002578 using llvm::APFloat;
2579 APFloat Val(Format);
2580
2581 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002582
2583 // Overflow is always an error, but underflow is only an error if
2584 // we underflowed to zero (APFloat reports denormals as underflow).
2585 if ((result & APFloat::opOverflow) ||
2586 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002587 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002588 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002589 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002590 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002591 APFloat::getLargest(Format).toString(buffer);
2592 } else {
John McCall62abc942010-02-26 23:35:57 +00002593 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002594 APFloat::getSmallest(Format).toString(buffer);
2595 }
2596
2597 Diag(Tok.getLocation(), diagnostic)
2598 << Ty
2599 << llvm::StringRef(buffer.data(), buffer.size());
2600 }
2601
2602 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002603 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002604
Peter Collingbourne0b69e1a2010-12-04 01:50:56 +00002605 if (getLangOptions().SinglePrecisionConstants && Ty == Context.DoubleTy)
2606 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2607
Chris Lattner1c20a172007-08-26 03:42:43 +00002608 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002609 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002610 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002611 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002612
Neil Boothac582c52007-08-29 22:00:19 +00002613 // long long is a C99 feature.
2614 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002615 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002616 Diag(Tok.getLocation(), diag::ext_longlong);
2617
Chris Lattner67ca9252007-05-21 01:08:44 +00002618 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002619 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002620
Chris Lattner67ca9252007-05-21 01:08:44 +00002621 if (Literal.GetIntegerValue(ResultVal)) {
2622 // If this value didn't fit into uintmax_t, warn and force to ull.
2623 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002624 Ty = Context.UnsignedLongLongTy;
2625 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002626 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002627 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002628 // If this value fits into a ULL, try to figure out what else it fits into
2629 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002630
Chris Lattner67ca9252007-05-21 01:08:44 +00002631 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2632 // be an unsigned int.
2633 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2634
2635 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002636 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002637 if (!Literal.isLong && !Literal.isLongLong) {
2638 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002639 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002640
Chris Lattner67ca9252007-05-21 01:08:44 +00002641 // Does it fit in a unsigned int?
2642 if (ResultVal.isIntN(IntSize)) {
2643 // Does it fit in a signed int?
2644 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002645 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002646 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002647 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002648 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002649 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002650 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002651
Chris Lattner67ca9252007-05-21 01:08:44 +00002652 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002653 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002654 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002655
Chris Lattner67ca9252007-05-21 01:08:44 +00002656 // Does it fit in a unsigned long?
2657 if (ResultVal.isIntN(LongSize)) {
2658 // Does it fit in a signed long?
2659 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002660 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002661 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002662 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002663 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002664 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002665 }
2666
Chris Lattner67ca9252007-05-21 01:08:44 +00002667 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002668 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002669 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002670
Chris Lattner67ca9252007-05-21 01:08:44 +00002671 // Does it fit in a unsigned long long?
2672 if (ResultVal.isIntN(LongLongSize)) {
2673 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002674 // To be compatible with MSVC, hex integer literals ending with the
2675 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002676 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2677 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002678 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002679 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002680 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002681 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002682 }
2683 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002684
Chris Lattner67ca9252007-05-21 01:08:44 +00002685 // If we still couldn't decide a type, we probably have something that
2686 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002687 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002688 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002689 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002690 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002691 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002692
Chris Lattner55258cf2008-05-09 05:59:00 +00002693 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002694 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002695 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002696 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002697 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002698
Chris Lattner1c20a172007-08-26 03:42:43 +00002699 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2700 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002701 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002702 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002703
2704 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002705}
2706
John McCalldadc5752010-08-24 06:29:42 +00002707ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002708 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002709 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002710 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002711}
2712
Steve Naroff71b59a92007-06-04 22:22:31 +00002713/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00002714/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002715bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00002716 SourceLocation OpLoc,
John McCall36e7fe32010-10-12 00:20:44 +00002717 SourceRange ExprRange,
Sebastian Redl6f282892008-11-11 17:56:53 +00002718 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002719 if (exprType->isDependentType())
2720 return false;
2721
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002722 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2723 // the result is the size of the referenced type."
2724 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2725 // result shall be the alignment of the referenced type."
2726 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2727 exprType = Ref->getPointeeType();
2728
Steve Naroff043d45d2007-05-15 02:32:35 +00002729 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00002730 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002731 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00002732 if (isSizeof)
2733 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2734 return false;
2735 }
Mike Stump11289f42009-09-09 15:08:12 +00002736
Chris Lattner62975a72009-04-24 00:30:45 +00002737 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00002738 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002739 Diag(OpLoc, diag::ext_sizeof_void_type)
2740 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00002741 return false;
2742 }
Mike Stump11289f42009-09-09 15:08:12 +00002743
Chris Lattner62975a72009-04-24 00:30:45 +00002744 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002745 PDiag(diag::err_sizeof_alignof_incomplete_type)
2746 << int(!isSizeof) << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002747 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002748
Chris Lattner62975a72009-04-24 00:30:45 +00002749 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCall8b07ec22010-05-15 11:32:37 +00002750 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002751 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002752 << exprType << isSizeof << ExprRange;
2753 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00002754 }
Mike Stump11289f42009-09-09 15:08:12 +00002755
Chris Lattner62975a72009-04-24 00:30:45 +00002756 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002757}
2758
John McCall36e7fe32010-10-12 00:20:44 +00002759static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2760 SourceRange ExprRange) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002761 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002762
Mike Stump11289f42009-09-09 15:08:12 +00002763 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002764 if (isa<DeclRefExpr>(E))
2765 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002766
2767 // Cannot know anything else if the expression is dependent.
2768 if (E->isTypeDependent())
2769 return false;
2770
Douglas Gregor71235ec2009-05-02 02:18:30 +00002771 if (E->getBitField()) {
John McCall36e7fe32010-10-12 00:20:44 +00002772 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor71235ec2009-05-02 02:18:30 +00002773 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002774 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002775
2776 // Alignment of a field access is always okay, so long as it isn't a
2777 // bit-field.
2778 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002779 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002780 return false;
2781
John McCall36e7fe32010-10-12 00:20:44 +00002782 return S.CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
Chris Lattner8dff0172009-01-24 20:17:12 +00002783}
2784
Douglas Gregor0950e412009-03-13 21:01:28 +00002785/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002786ExprResult
John McCallbcd03502009-12-07 02:54:59 +00002787Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall4c98fd82009-11-04 07:28:41 +00002788 SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00002789 bool isSizeOf, SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002790 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002791 return ExprError();
2792
John McCallbcd03502009-12-07 02:54:59 +00002793 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002794
Douglas Gregor0950e412009-03-13 21:01:28 +00002795 if (!T->isDependentType() &&
2796 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2797 return ExprError();
2798
2799 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCallbcd03502009-12-07 02:54:59 +00002800 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregor0950e412009-03-13 21:01:28 +00002801 Context.getSizeType(), OpLoc,
2802 R.getEnd()));
2803}
2804
2805/// \brief Build a sizeof or alignof expression given an expression
2806/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002807ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00002808Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00002809 bool isSizeOf, SourceRange R) {
2810 // Verify that the operand is valid.
2811 bool isInvalid = false;
2812 if (E->isTypeDependent()) {
2813 // Delay type-checking for type-dependent expressions.
2814 } else if (!isSizeOf) {
John McCall36e7fe32010-10-12 00:20:44 +00002815 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002816 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00002817 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2818 isInvalid = true;
John McCall36226622010-10-12 02:09:17 +00002819 } else if (E->getType()->isPlaceholderType()) {
2820 ExprResult PE = CheckPlaceholderExpr(E, OpLoc);
2821 if (PE.isInvalid()) return ExprError();
2822 return CreateSizeOfAlignOfExpr(PE.take(), OpLoc, isSizeOf, R);
Douglas Gregor0950e412009-03-13 21:01:28 +00002823 } else {
2824 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2825 }
2826
2827 if (isInvalid)
2828 return ExprError();
2829
2830 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2831 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2832 Context.getSizeType(), OpLoc,
2833 R.getEnd()));
2834}
2835
Sebastian Redl6f282892008-11-11 17:56:53 +00002836/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2837/// the same for @c alignof and @c __alignof
2838/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002839ExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00002840Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2841 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002842 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002843 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002844
Sebastian Redl6f282892008-11-11 17:56:53 +00002845 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002846 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002847 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
John McCallbcd03502009-12-07 02:54:59 +00002848 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002849 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002850
Douglas Gregor0950e412009-03-13 21:01:28 +00002851 Expr *ArgEx = (Expr *)TyOrEx;
John McCalldadc5752010-08-24 06:29:42 +00002852 ExprResult Result
Douglas Gregor0950e412009-03-13 21:01:28 +00002853 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2854
Douglas Gregor0950e412009-03-13 21:01:28 +00002855 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002856}
2857
John McCall4bc41ae2010-11-18 19:01:18 +00002858static QualType CheckRealImagOperand(Sema &S, Expr *&V, SourceLocation Loc,
2859 bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002860 if (V->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002861 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002862
John McCall34376a62010-12-04 03:47:34 +00002863 // _Real and _Imag are only l-values for normal l-values.
2864 if (V->getObjectKind() != OK_Ordinary)
John McCall27584242010-12-06 20:48:59 +00002865 S.DefaultLvalueConversion(V);
John McCall34376a62010-12-04 03:47:34 +00002866
Chris Lattnere267f5d2007-08-26 05:39:26 +00002867 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00002868 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002869 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002870
Chris Lattnere267f5d2007-08-26 05:39:26 +00002871 // Otherwise they pass through real integer and floating point types here.
2872 if (V->getType()->isArithmeticType())
2873 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002874
John McCall36226622010-10-12 02:09:17 +00002875 // Test for placeholders.
John McCall4bc41ae2010-11-18 19:01:18 +00002876 ExprResult PR = S.CheckPlaceholderExpr(V, Loc);
John McCall36226622010-10-12 02:09:17 +00002877 if (PR.isInvalid()) return QualType();
2878 if (PR.take() != V) {
2879 V = PR.take();
John McCall4bc41ae2010-11-18 19:01:18 +00002880 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00002881 }
2882
Chris Lattnere267f5d2007-08-26 05:39:26 +00002883 // Reject anything else.
John McCall4bc41ae2010-11-18 19:01:18 +00002884 S.Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00002885 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002886 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002887}
2888
2889
Chris Lattnere168f762006-11-10 05:29:30 +00002890
John McCalldadc5752010-08-24 06:29:42 +00002891ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002892Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002893 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002894 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002895 switch (Kind) {
2896 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002897 case tok::plusplus: Opc = UO_PostInc; break;
2898 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002899 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002900
John McCallb268a282010-08-23 23:25:46 +00002901 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002902}
2903
John McCall4bc41ae2010-11-18 19:01:18 +00002904/// Expressions of certain arbitrary types are forbidden by C from
2905/// having l-value type. These are:
2906/// - 'void', but not qualified void
2907/// - function types
2908///
2909/// The exact rule here is C99 6.3.2.1:
2910/// An lvalue is an expression with an object type or an incomplete
2911/// type other than void.
2912static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
2913 return ((T->isVoidType() && !T.hasQualifiers()) ||
2914 T->isFunctionType());
2915}
2916
John McCalldadc5752010-08-24 06:29:42 +00002917ExprResult
John McCallb268a282010-08-23 23:25:46 +00002918Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2919 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002920 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002921 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002922 if (Result.isInvalid()) return ExprError();
2923 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002924
John McCallb268a282010-08-23 23:25:46 +00002925 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00002926
Douglas Gregor40412ac2008-11-19 17:17:41 +00002927 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002928 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002929 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002930 Context.DependentTy,
2931 VK_LValue, OK_Ordinary,
2932 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002933 }
2934
Mike Stump11289f42009-09-09 15:08:12 +00002935 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002936 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002937 LHSExp->getType()->isEnumeralType() ||
2938 RHSExp->getType()->isRecordType() ||
2939 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00002940 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00002941 }
2942
John McCallb268a282010-08-23 23:25:46 +00002943 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00002944}
2945
2946
John McCalldadc5752010-08-24 06:29:42 +00002947ExprResult
John McCallb268a282010-08-23 23:25:46 +00002948Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2949 Expr *Idx, SourceLocation RLoc) {
2950 Expr *LHSExp = Base;
2951 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00002952
Chris Lattner36d572b2007-07-16 00:14:47 +00002953 // Perform default conversions.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002954 if (!LHSExp->getType()->getAs<VectorType>())
2955 DefaultFunctionArrayLvalueConversion(LHSExp);
2956 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002957
Chris Lattner36d572b2007-07-16 00:14:47 +00002958 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00002959 ExprValueKind VK = VK_LValue;
2960 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00002961
Steve Naroffc1aadb12007-03-28 21:49:40 +00002962 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00002963 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00002964 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00002965 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00002966 Expr *BaseExpr, *IndexExpr;
2967 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002968 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2969 BaseExpr = LHSExp;
2970 IndexExpr = RHSExp;
2971 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002972 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00002973 BaseExpr = LHSExp;
2974 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002975 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002976 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00002977 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00002978 BaseExpr = RHSExp;
2979 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002980 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002981 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002982 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002983 BaseExpr = LHSExp;
2984 IndexExpr = RHSExp;
2985 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002986 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002987 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002988 // Handle the uncommon case of "123[Ptr]".
2989 BaseExpr = RHSExp;
2990 IndexExpr = LHSExp;
2991 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00002992 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00002993 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00002994 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00002995 VK = LHSExp->getValueKind();
2996 if (VK != VK_RValue)
2997 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00002998
Chris Lattner36d572b2007-07-16 00:14:47 +00002999 // FIXME: need to deal with const...
3000 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003001 } else if (LHSTy->isArrayType()) {
3002 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003003 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003004 // wasn't promoted because of the C90 rule that doesn't
3005 // allow promoting non-lvalue arrays. Warn, then
3006 // force the promotion here.
3007 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3008 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003009 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
John McCalle3027922010-08-25 11:45:40 +00003010 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00003011 LHSTy = LHSExp->getType();
3012
3013 BaseExpr = LHSExp;
3014 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003015 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003016 } else if (RHSTy->isArrayType()) {
3017 // Same as previous, except for 123[f().a] case
3018 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3019 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003020 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
John McCalle3027922010-08-25 11:45:40 +00003021 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00003022 RHSTy = RHSExp->getType();
3023
3024 BaseExpr = RHSExp;
3025 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003026 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003027 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003028 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3029 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003030 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003031 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003032 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003033 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3034 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003035
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003036 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003037 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3038 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003039 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3040
Douglas Gregorac1fb652009-03-24 19:52:54 +00003041 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003042 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3043 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003044 // incomplete types are not object types.
3045 if (ResultType->isFunctionType()) {
3046 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3047 << ResultType << BaseExpr->getSourceRange();
3048 return ExprError();
3049 }
Mike Stump11289f42009-09-09 15:08:12 +00003050
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003051 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3052 // GNU extension: subscripting on pointer to void
3053 Diag(LLoc, diag::ext_gnu_void_ptr)
3054 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003055
3056 // C forbids expressions of unqualified void type from being l-values.
3057 // See IsCForbiddenLValueType.
3058 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003059 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003060 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003061 PDiag(diag::err_subscript_incomplete_type)
3062 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003063 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003064
Chris Lattner62975a72009-04-24 00:30:45 +00003065 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003066 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003067 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3068 << ResultType << BaseExpr->getSourceRange();
3069 return ExprError();
3070 }
Mike Stump11289f42009-09-09 15:08:12 +00003071
John McCall4bc41ae2010-11-18 19:01:18 +00003072 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3073 !IsCForbiddenLValueType(Context, ResultType));
3074
Mike Stump4e1f26a2009-02-19 03:04:26 +00003075 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003076 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003077}
3078
John McCall4bc41ae2010-11-18 19:01:18 +00003079/// Check an ext-vector component access expression.
3080///
3081/// VK should be set in advance to the value kind of the base
3082/// expression.
3083static QualType
3084CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3085 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00003086 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00003087 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3088 // see FIXME there.
3089 //
3090 // FIXME: This logic can be greatly simplified by splitting it along
3091 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00003092 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00003093
Steve Narofff8fd09e2007-07-27 22:15:19 +00003094 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003095 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003096
Mike Stump4e1f26a2009-02-19 03:04:26 +00003097 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00003098 // special names that indicate a subset of exactly half the elements are
3099 // to be selected.
3100 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003101
Nate Begemanbb70bf62009-01-18 01:47:54 +00003102 // This flag determines whether or not CompName has an 's' char prefix,
3103 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00003104 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00003105
John McCall4bc41ae2010-11-18 19:01:18 +00003106 bool HasRepeated = false;
3107 bool HasIndex[16] = {};
3108
3109 int Idx;
3110
Nate Begemanf322eab2008-05-09 06:41:27 +00003111 // Check that we've found one of the special components, or that the component
3112 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003113 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00003114 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3115 HalvingSwizzle = true;
John McCall4bc41ae2010-11-18 19:01:18 +00003116 } else if (!HexSwizzle &&
3117 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3118 do {
3119 if (HasIndex[Idx]) HasRepeated = true;
3120 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003121 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003122 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3123 } else {
3124 if (HexSwizzle) compStr++;
3125 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3126 if (HasIndex[Idx]) HasRepeated = true;
3127 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003128 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003129 }
Chris Lattner7e152db2007-08-02 22:33:49 +00003130 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00003131
Mike Stump4e1f26a2009-02-19 03:04:26 +00003132 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00003133 // We didn't get to the end of the string. This means the component names
3134 // didn't come from the same set *or* we encountered an illegal name.
John McCall4bc41ae2010-11-18 19:01:18 +00003135 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramere8394df2010-08-11 14:47:12 +00003136 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00003137 return QualType();
3138 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003139
Nate Begemanbb70bf62009-01-18 01:47:54 +00003140 // Ensure no component accessor exceeds the width of the vector type it
3141 // operates on.
3142 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003143 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003144
3145 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00003146 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00003147
3148 while (*compStr) {
3149 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall4bc41ae2010-11-18 19:01:18 +00003150 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begemanbb70bf62009-01-18 01:47:54 +00003151 << baseType << SourceRange(CompLoc);
3152 return QualType();
3153 }
3154 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00003155 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003156
Steve Narofff8fd09e2007-07-27 22:15:19 +00003157 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003158 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00003159 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00003160 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00003161 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00003162 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00003163 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003164 if (HexSwizzle)
3165 CompSize--;
3166
Steve Narofff8fd09e2007-07-27 22:15:19 +00003167 if (CompSize == 1)
3168 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003169
John McCall4bc41ae2010-11-18 19:01:18 +00003170 if (HasRepeated) VK = VK_RValue;
3171
3172 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003173 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00003174 // diagostics look bad. We want extended vector types to appear built-in.
John McCall4bc41ae2010-11-18 19:01:18 +00003175 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3176 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3177 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00003178 }
3179 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00003180}
3181
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003182static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00003183 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003184 const Selector &Sel,
3185 ASTContext &Context) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003186 if (Member)
3187 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3188 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003189 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003190 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00003191
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003192 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3193 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003194 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3195 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003196 return D;
3197 }
3198 return 0;
3199}
3200
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003201static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3202 IdentifierInfo *Member,
3203 const Selector &Sel,
3204 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003205 // Check protocols on qualified interfaces.
3206 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00003207 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003208 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003209 if (Member)
3210 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3211 GDecl = PD;
3212 break;
3213 }
3214 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003215 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003216 GDecl = OMD;
3217 break;
3218 }
3219 }
3220 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00003221 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003222 E = QIdTy->qual_end(); I != E; ++I) {
3223 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003224 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3225 Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003226 if (GDecl)
3227 return GDecl;
3228 }
3229 }
3230 return GDecl;
3231}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00003232
John McCalldadc5752010-08-24 06:29:42 +00003233ExprResult
John McCallb268a282010-08-23 23:25:46 +00003234Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCall2d74de92009-12-01 22:10:20 +00003235 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003236 const CXXScopeSpec &SS,
3237 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003238 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003239 const TemplateArgumentListInfo *TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00003240 // Even in dependent contexts, try to diagnose base expressions with
3241 // obviously wrong types, e.g.:
3242 //
3243 // T* t;
3244 // t.f;
3245 //
3246 // In Obj-C++, however, the above expression is valid, since it could be
3247 // accessing the 'f' property if T is an Obj-C interface. The extra check
3248 // allows this, while still reporting an error if T is a struct pointer.
3249 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00003250 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00003251 if (PT && (!getLangOptions().ObjC1 ||
3252 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00003253 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003254 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00003255 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00003256 return ExprError();
3257 }
3258 }
3259
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003260 assert(BaseType->isDependentType() ||
3261 NameInfo.getName().isDependentName() ||
Douglas Gregor41f90302010-04-12 20:54:26 +00003262 isDependentScopeSpecifier(SS));
John McCall10eae182009-11-30 22:42:35 +00003263
3264 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3265 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00003266 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003267 IsArrow, OpLoc,
Douglas Gregore16af532011-02-28 18:50:33 +00003268 SS.getWithLocInContext(Context),
John McCall10eae182009-11-30 22:42:35 +00003269 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003270 NameInfo, TemplateArgs));
John McCall10eae182009-11-30 22:42:35 +00003271}
3272
3273/// We know that the given qualified member reference points only to
3274/// declarations which do not belong to the static type of the base
3275/// expression. Diagnose the problem.
3276static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3277 Expr *BaseExpr,
3278 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003279 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00003280 NamedDecl *rep,
3281 const DeclarationNameInfo &nameInfo) {
John McCallcd4b4772009-12-02 03:53:29 +00003282 // If this is an implicit member access, use a different set of
3283 // diagnostics.
3284 if (!BaseExpr)
John McCallf3a88602011-02-03 08:15:49 +00003285 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall10eae182009-11-30 22:42:35 +00003286
John McCallf3a88602011-02-03 08:15:49 +00003287 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3288 << SS.getRange() << rep << BaseType;
John McCall10eae182009-11-30 22:42:35 +00003289}
3290
3291// Check whether the declarations we found through a nested-name
3292// specifier in a member expression are actually members of the base
3293// type. The restriction here is:
3294//
3295// C++ [expr.ref]p2:
3296// ... In these cases, the id-expression shall name a
3297// member of the class or of one of its base classes.
3298//
3299// So it's perfectly legitimate for the nested-name specifier to name
3300// an unrelated class, and for us to find an overload set including
3301// decls from classes which are not superclasses, as long as the decl
3302// we actually pick through overload resolution is from a superclass.
3303bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3304 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003305 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003306 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00003307 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3308 if (!BaseRT) {
3309 // We can't check this yet because the base type is still
3310 // dependent.
3311 assert(BaseType->isDependentType());
3312 return false;
3313 }
3314 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00003315
3316 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00003317 // If this is an implicit member reference and we find a
3318 // non-instance member, it's not an error.
John McCalla8ae2222010-04-06 21:38:20 +00003319 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCall2d74de92009-12-01 22:10:20 +00003320 return false;
John McCall10eae182009-11-30 22:42:35 +00003321
John McCall2d74de92009-12-01 22:10:20 +00003322 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman75300492010-07-27 20:51:02 +00003323 DeclContext *DC = (*I)->getDeclContext();
3324 while (DC->isTransparentContext())
3325 DC = DC->getParent();
John McCall2d74de92009-12-01 22:10:20 +00003326
Douglas Gregora9c3e822010-07-28 22:27:52 +00003327 if (!DC->isRecord())
3328 continue;
3329
John McCall2d74de92009-12-01 22:10:20 +00003330 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman75300492010-07-27 20:51:02 +00003331 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCall2d74de92009-12-01 22:10:20 +00003332
3333 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3334 return false;
3335 }
3336
John McCallf3a88602011-02-03 08:15:49 +00003337 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3338 R.getRepresentativeDecl(),
3339 R.getLookupNameInfo());
John McCall2d74de92009-12-01 22:10:20 +00003340 return true;
3341}
3342
3343static bool
3344LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3345 SourceRange BaseRange, const RecordType *RTy,
John McCalle9cccd82010-06-16 08:42:20 +00003346 SourceLocation OpLoc, CXXScopeSpec &SS,
3347 bool HasTemplateArgs) {
John McCall2d74de92009-12-01 22:10:20 +00003348 RecordDecl *RDecl = RTy->getDecl();
3349 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor89336232010-03-29 23:34:08 +00003350 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCall2d74de92009-12-01 22:10:20 +00003351 << BaseRange))
3352 return true;
3353
John McCalle9cccd82010-06-16 08:42:20 +00003354 if (HasTemplateArgs) {
3355 // LookupTemplateName doesn't expect these both to exist simultaneously.
3356 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3357
3358 bool MOUS;
3359 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3360 return false;
3361 }
3362
John McCall2d74de92009-12-01 22:10:20 +00003363 DeclContext *DC = RDecl;
3364 if (SS.isSet()) {
3365 // If the member name was a qualified-id, look into the
3366 // nested-name-specifier.
3367 DC = SemaRef.computeDeclContext(SS, false);
3368
John McCall0b66eb32010-05-01 00:40:08 +00003369 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCallcd4b4772009-12-02 03:53:29 +00003370 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3371 << SS.getRange() << DC;
3372 return true;
3373 }
3374
John McCall2d74de92009-12-01 22:10:20 +00003375 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003376
John McCall2d74de92009-12-01 22:10:20 +00003377 if (!isa<TypeDecl>(DC)) {
3378 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3379 << DC << SS.getRange();
3380 return true;
John McCall10eae182009-11-30 22:42:35 +00003381 }
3382 }
3383
John McCall2d74de92009-12-01 22:10:20 +00003384 // The record definition is complete, now look up the member.
3385 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00003386
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003387 if (!R.empty())
3388 return false;
3389
3390 // We didn't find anything with the given name, so try to correct
3391 // for typos.
3392 DeclarationName Name = R.getLookupName();
Alexis Huntc46382e2010-04-28 23:02:27 +00003393 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003394 !R.empty() &&
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003395 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3396 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3397 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003398 << FixItHint::CreateReplacement(R.getNameLoc(),
3399 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003400 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3401 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3402 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003403 return false;
3404 } else {
3405 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003406 R.setLookupName(Name);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003407 }
3408
John McCall10eae182009-11-30 22:42:35 +00003409 return false;
3410}
3411
John McCalldadc5752010-08-24 06:29:42 +00003412ExprResult
John McCallb268a282010-08-23 23:25:46 +00003413Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00003414 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003415 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003416 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003417 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003418 const TemplateArgumentListInfo *TemplateArgs) {
John McCallcd4b4772009-12-02 03:53:29 +00003419 if (BaseType->isDependentType() ||
3420 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallb268a282010-08-23 23:25:46 +00003421 return ActOnDependentMemberExpr(Base, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003422 IsArrow, OpLoc,
3423 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003424 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003425
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003426 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00003427
John McCall2d74de92009-12-01 22:10:20 +00003428 // Implicit member accesses.
3429 if (!Base) {
3430 QualType RecordTy = BaseType;
3431 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3432 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3433 RecordTy->getAs<RecordType>(),
John McCalle9cccd82010-06-16 08:42:20 +00003434 OpLoc, SS, TemplateArgs != 0))
John McCall2d74de92009-12-01 22:10:20 +00003435 return ExprError();
3436
3437 // Explicit member accesses.
3438 } else {
John McCalldadc5752010-08-24 06:29:42 +00003439 ExprResult Result =
John McCall2d74de92009-12-01 22:10:20 +00003440 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCall48871652010-08-21 09:40:31 +00003441 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCall2d74de92009-12-01 22:10:20 +00003442
3443 if (Result.isInvalid()) {
3444 Owned(Base);
3445 return ExprError();
3446 }
3447
3448 if (Result.get())
3449 return move(Result);
Sebastian Redlfa1f70f2010-05-07 09:25:11 +00003450
3451 // LookupMemberExpr can modify Base, and thus change BaseType
3452 BaseType = Base->getType();
John McCall10eae182009-11-30 22:42:35 +00003453 }
3454
John McCallb268a282010-08-23 23:25:46 +00003455 return BuildMemberReferenceExpr(Base, BaseType,
John McCall38836f02010-01-15 08:34:02 +00003456 OpLoc, IsArrow, SS, FirstQualifierInScope,
3457 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003458}
3459
John McCalldadc5752010-08-24 06:29:42 +00003460ExprResult
John McCallb268a282010-08-23 23:25:46 +00003461Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCall2d74de92009-12-01 22:10:20 +00003462 SourceLocation OpLoc, bool IsArrow,
3463 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00003464 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00003465 LookupResult &R,
Douglas Gregorb139cd52010-05-01 20:49:11 +00003466 const TemplateArgumentListInfo *TemplateArgs,
3467 bool SuppressQualifierCheck) {
John McCall2d74de92009-12-01 22:10:20 +00003468 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00003469 if (IsArrow) {
3470 assert(BaseType->isPointerType());
3471 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3472 }
John McCalla8ae2222010-04-06 21:38:20 +00003473 R.setBaseObjectType(BaseType);
John McCall10eae182009-11-30 22:42:35 +00003474
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003475 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3476 DeclarationName MemberName = MemberNameInfo.getName();
3477 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall10eae182009-11-30 22:42:35 +00003478
3479 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00003480 return ExprError();
3481
John McCall10eae182009-11-30 22:42:35 +00003482 if (R.empty()) {
3483 // Rederive where we looked up.
3484 DeclContext *DC = (SS.isSet()
3485 ? computeDeclContext(SS, false)
3486 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00003487
John McCall10eae182009-11-30 22:42:35 +00003488 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00003489 << MemberName << DC
3490 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00003491 return ExprError();
3492 }
3493
John McCall38836f02010-01-15 08:34:02 +00003494 // Diagnose lookups that find only declarations from a non-base
3495 // type. This is possible for either qualified lookups (which may
3496 // have been qualified with an unrelated type) or implicit member
3497 // expressions (which were found with unqualified lookup and thus
3498 // may have come from an enclosing scope). Note that it's okay for
3499 // lookup to find declarations from a non-base type as long as those
3500 // aren't the ones picked by overload resolution.
3501 if ((SS.isSet() || !BaseExpr ||
3502 (isa<CXXThisExpr>(BaseExpr) &&
3503 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00003504 !SuppressQualifierCheck &&
John McCall38836f02010-01-15 08:34:02 +00003505 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00003506 return ExprError();
3507
3508 // Construct an unresolved result if we in fact got an unresolved
3509 // result.
3510 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall58cc69d2010-01-27 01:50:18 +00003511 // Suppress any lookup-related diagnostics; we'll do these when we
3512 // pick a member.
3513 R.suppressDiagnostics();
3514
John McCall10eae182009-11-30 22:42:35 +00003515 UnresolvedMemberExpr *MemExpr
Douglas Gregora6e053e2010-12-15 01:34:56 +00003516 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00003517 BaseExpr, BaseExprType,
3518 IsArrow, OpLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00003519 SS.getWithLocInContext(Context),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003520 MemberNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003521 TemplateArgs, R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00003522
3523 return Owned(MemExpr);
3524 }
3525
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003526 assert(R.isSingleResult());
John McCalla8ae2222010-04-06 21:38:20 +00003527 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall10eae182009-11-30 22:42:35 +00003528 NamedDecl *MemberDecl = R.getFoundDecl();
3529
3530 // FIXME: diagnose the presence of template arguments now.
3531
3532 // If the decl being referenced had an error, return an error for this
3533 // sub-expr without emitting another error, in order to avoid cascading
3534 // error cases.
3535 if (MemberDecl->isInvalidDecl())
3536 return ExprError();
3537
John McCall2d74de92009-12-01 22:10:20 +00003538 // Handle the implicit-member-access case.
3539 if (!BaseExpr) {
3540 // If this is not an instance member, convert to a non-member access.
John McCalla8ae2222010-04-06 21:38:20 +00003541 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003542 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCall2d74de92009-12-01 22:10:20 +00003543
Douglas Gregorb15af892010-01-07 23:12:05 +00003544 SourceLocation Loc = R.getNameLoc();
3545 if (SS.getRange().isValid())
3546 Loc = SS.getRange().getBegin();
3547 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003548 }
3549
John McCall10eae182009-11-30 22:42:35 +00003550 bool ShouldCheckUse = true;
3551 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3552 // Don't diagnose the use of a virtual member function unless it's
3553 // explicitly qualified.
3554 if (MD->isVirtual() && !SS.isSet())
3555 ShouldCheckUse = false;
3556 }
3557
3558 // Check the use of this member.
3559 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3560 Owned(BaseExpr);
3561 return ExprError();
3562 }
3563
John McCall34376a62010-12-04 03:47:34 +00003564 // Perform a property load on the base regardless of whether we
3565 // actually need it for the declaration.
3566 if (BaseExpr->getObjectKind() == OK_ObjCProperty)
3567 ConvertPropertyForRValue(BaseExpr);
3568
John McCallfeb624a2010-11-23 20:48:44 +00003569 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3570 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3571 SS, FD, FoundDecl, MemberNameInfo);
John McCall10eae182009-11-30 22:42:35 +00003572
Francois Pichet783dd6e2010-11-21 06:08:52 +00003573 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3574 // We may have found a field within an anonymous union or struct
3575 // (C++ [class.union]).
John McCallf3a88602011-02-03 08:15:49 +00003576 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCall34376a62010-12-04 03:47:34 +00003577 BaseExpr, OpLoc);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003578
John McCall10eae182009-11-30 22:42:35 +00003579 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3580 MarkDeclarationReferenced(MemberLoc, Var);
3581 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003582 Var, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003583 Var->getType().getNonReferenceType(),
John McCall4bc41ae2010-11-18 19:01:18 +00003584 VK_LValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003585 }
3586
John McCall7decc9e2010-11-18 06:31:45 +00003587 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall10eae182009-11-30 22:42:35 +00003588 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3589 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003590 MemberFn, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003591 MemberFn->getType(),
3592 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3593 OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003594 }
John McCall7decc9e2010-11-18 06:31:45 +00003595 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall10eae182009-11-30 22:42:35 +00003596
3597 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3598 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3599 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003600 Enum, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003601 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003602 }
3603
3604 Owned(BaseExpr);
3605
Douglas Gregor861eb802010-04-25 20:55:08 +00003606 // We found something that we didn't expect. Complain.
John McCall10eae182009-11-30 22:42:35 +00003607 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003608 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregor861eb802010-04-25 20:55:08 +00003609 << MemberName << BaseType << int(IsArrow);
3610 else
3611 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3612 << MemberName << BaseType << int(IsArrow);
John McCall10eae182009-11-30 22:42:35 +00003613
Douglas Gregor861eb802010-04-25 20:55:08 +00003614 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3615 << MemberName;
Douglas Gregor516d6722010-04-25 21:15:30 +00003616 R.suppressDiagnostics();
Douglas Gregor861eb802010-04-25 20:55:08 +00003617 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00003618}
3619
John McCall68fc88ec2010-12-15 16:46:44 +00003620/// Given that normal member access failed on the given expression,
3621/// and given that the expression's type involves builtin-id or
3622/// builtin-Class, decide whether substituting in the redefinition
3623/// types would be profitable. The redefinition type is whatever
3624/// this translation unit tried to typedef to id/Class; we store
3625/// it to the side and then re-use it in places like this.
3626static bool ShouldTryAgainWithRedefinitionType(Sema &S, Expr *&base) {
3627 const ObjCObjectPointerType *opty
3628 = base->getType()->getAs<ObjCObjectPointerType>();
3629 if (!opty) return false;
3630
3631 const ObjCObjectType *ty = opty->getObjectType();
3632
3633 QualType redef;
3634 if (ty->isObjCId()) {
3635 redef = S.Context.ObjCIdRedefinitionType;
3636 } else if (ty->isObjCClass()) {
3637 redef = S.Context.ObjCClassRedefinitionType;
3638 } else {
3639 return false;
3640 }
3641
3642 // Do the substitution as long as the redefinition type isn't just a
3643 // possibly-qualified pointer to builtin-id or builtin-Class again.
3644 opty = redef->getAs<ObjCObjectPointerType>();
3645 if (opty && !opty->getObjectType()->getInterface() != 0)
3646 return false;
3647
3648 S.ImpCastExprToType(base, redef, CK_BitCast);
3649 return true;
3650}
3651
John McCall10eae182009-11-30 22:42:35 +00003652/// Look up the given member of the given non-type-dependent
3653/// expression. This can return in one of two ways:
3654/// * If it returns a sentinel null-but-valid result, the caller will
3655/// assume that lookup was performed and the results written into
3656/// the provided structure. It will take over from there.
3657/// * Otherwise, the returned expression will be produced in place of
3658/// an ordinary member expression.
3659///
3660/// The ObjCImpDecl bit is a gross hack that will need to be properly
3661/// fixed for ObjC++.
John McCalldadc5752010-08-24 06:29:42 +00003662ExprResult
John McCall10eae182009-11-30 22:42:35 +00003663Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00003664 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003665 CXXScopeSpec &SS,
John McCall48871652010-08-21 09:40:31 +00003666 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003667 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00003668
Steve Naroffeaaae462007-12-16 21:42:28 +00003669 // Perform default conversions.
3670 DefaultFunctionArrayConversion(BaseExpr);
John McCall15317a22010-12-15 04:42:30 +00003671 if (IsArrow) DefaultLvalueConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003672
Steve Naroff185616f2007-07-26 03:11:44 +00003673 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00003674 assert(!BaseType->isDependentType());
3675
3676 DeclarationName MemberName = R.getLookupName();
3677 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00003678
John McCall68fc88ec2010-12-15 16:46:44 +00003679 // For later type-checking purposes, turn arrow accesses into dot
3680 // accesses. The only access type we support that doesn't follow
3681 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
3682 // and those never use arrows, so this is unaffected.
3683 if (IsArrow) {
3684 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3685 BaseType = Ptr->getPointeeType();
3686 else if (const ObjCObjectPointerType *Ptr
3687 = BaseType->getAs<ObjCObjectPointerType>())
3688 BaseType = Ptr->getPointeeType();
3689 else if (BaseType->isRecordType()) {
3690 // Recover from arrow accesses to records, e.g.:
3691 // struct MyRecord foo;
3692 // foo->bar
3693 // This is actually well-formed in C++ if MyRecord has an
3694 // overloaded operator->, but that should have been dealt with
3695 // by now.
3696 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3697 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3698 << FixItHint::CreateReplacement(OpLoc, ".");
3699 IsArrow = false;
3700 } else {
3701 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3702 << BaseType << BaseExpr->getSourceRange();
3703 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00003704 }
3705 }
3706
John McCall68fc88ec2010-12-15 16:46:44 +00003707 // Handle field access to simple records.
3708 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
3709 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
3710 RTy, OpLoc, SS, HasTemplateArgs))
3711 return ExprError();
3712
3713 // Returning valid-but-null is how we indicate to the caller that
3714 // the lookup result was filled in.
3715 return Owned((Expr*) 0);
David Chisnall9f57c292009-08-17 16:35:33 +00003716 }
John McCall10eae182009-11-30 22:42:35 +00003717
John McCall68fc88ec2010-12-15 16:46:44 +00003718 // Handle ivar access to Objective-C objects.
3719 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003720 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall68fc88ec2010-12-15 16:46:44 +00003721
3722 // There are three cases for the base type:
3723 // - builtin id (qualified or unqualified)
3724 // - builtin Class (qualified or unqualified)
3725 // - an interface
3726 ObjCInterfaceDecl *IDecl = OTy->getInterface();
3727 if (!IDecl) {
3728 // There's an implicit 'isa' ivar on all objects.
3729 // But we only actually find it this way on objects of type 'id',
3730 // apparently.
3731 if (OTy->isObjCId() && Member->isStr("isa"))
3732 return Owned(new (Context) ObjCIsaExpr(BaseExpr, IsArrow, MemberLoc,
3733 Context.getObjCClassType()));
3734
3735 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3736 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3737 ObjCImpDecl, HasTemplateArgs);
3738 goto fail;
3739 }
3740
3741 ObjCInterfaceDecl *ClassDeclared;
3742 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
3743
3744 if (!IV) {
3745 // Attempt to correct for typos in ivar names.
3746 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3747 LookupMemberName);
3748 if (CorrectTypo(Res, 0, 0, IDecl, false,
3749 IsArrow ? CTC_ObjCIvarLookup
3750 : CTC_ObjCPropertyLookup) &&
3751 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
3752 Diag(R.getNameLoc(),
3753 diag::err_typecheck_member_reference_ivar_suggest)
3754 << IDecl->getDeclName() << MemberName << IV->getDeclName()
3755 << FixItHint::CreateReplacement(R.getNameLoc(),
3756 IV->getNameAsString());
3757 Diag(IV->getLocation(), diag::note_previous_decl)
3758 << IV->getDeclName();
3759 } else {
3760 Res.clear();
3761 Res.setLookupName(Member);
3762
3763 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
3764 << IDecl->getDeclName() << MemberName
3765 << BaseExpr->getSourceRange();
3766 return ExprError();
3767 }
3768 }
3769
3770 // If the decl being referenced had an error, return an error for this
3771 // sub-expr without emitting another error, in order to avoid cascading
3772 // error cases.
3773 if (IV->isInvalidDecl())
3774 return ExprError();
3775
3776 // Check whether we can reference this field.
3777 if (DiagnoseUseOfDecl(IV, MemberLoc))
3778 return ExprError();
3779 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3780 IV->getAccessControl() != ObjCIvarDecl::Package) {
3781 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3782 if (ObjCMethodDecl *MD = getCurMethodDecl())
3783 ClassOfMethodDecl = MD->getClassInterface();
3784 else if (ObjCImpDecl && getCurFunctionDecl()) {
3785 // Case of a c-function declared inside an objc implementation.
3786 // FIXME: For a c-style function nested inside an objc implementation
3787 // class, there is no implementation context available, so we pass
3788 // down the context as argument to this routine. Ideally, this context
3789 // need be passed down in the AST node and somehow calculated from the
3790 // AST for a function decl.
3791 if (ObjCImplementationDecl *IMPD =
3792 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
3793 ClassOfMethodDecl = IMPD->getClassInterface();
3794 else if (ObjCCategoryImplDecl* CatImplClass =
3795 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
3796 ClassOfMethodDecl = CatImplClass->getClassInterface();
3797 }
3798
3799 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3800 if (ClassDeclared != IDecl ||
3801 ClassOfMethodDecl != ClassDeclared)
3802 Diag(MemberLoc, diag::error_private_ivar_access)
3803 << IV->getDeclName();
3804 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3805 // @protected
3806 Diag(MemberLoc, diag::error_protected_ivar_access)
3807 << IV->getDeclName();
3808 }
3809
3810 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3811 MemberLoc, BaseExpr,
3812 IsArrow));
3813 }
3814
3815 // Objective-C property access.
3816 const ObjCObjectPointerType *OPT;
3817 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
3818 // This actually uses the base as an r-value.
3819 DefaultLvalueConversion(BaseExpr);
3820 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr->getType()));
3821
3822 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3823
3824 const ObjCObjectType *OT = OPT->getObjectType();
3825
3826 // id, with and without qualifiers.
3827 if (OT->isObjCId()) {
3828 // Check protocols on qualified interfaces.
3829 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3830 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
3831 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3832 // Check the use of this declaration
3833 if (DiagnoseUseOfDecl(PD, MemberLoc))
3834 return ExprError();
3835
3836 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3837 VK_LValue,
3838 OK_ObjCProperty,
3839 MemberLoc,
3840 BaseExpr));
3841 }
3842
3843 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3844 // Check the use of this method.
3845 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3846 return ExprError();
3847 Selector SetterSel =
3848 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3849 PP.getSelectorTable(), Member);
3850 ObjCMethodDecl *SMD = 0;
3851 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
3852 SetterSel, Context))
3853 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3854 QualType PType = OMD->getSendResultType();
3855
3856 ExprValueKind VK = VK_LValue;
3857 if (!getLangOptions().CPlusPlus &&
3858 IsCForbiddenLValueType(Context, PType))
3859 VK = VK_RValue;
3860 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3861
3862 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
3863 VK, OK,
3864 MemberLoc, BaseExpr));
3865 }
3866 }
3867
3868 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3869 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3870 ObjCImpDecl, HasTemplateArgs);
3871
3872 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3873 << MemberName << BaseType);
3874 }
3875
3876 // 'Class', unqualified only.
3877 if (OT->isObjCClass()) {
3878 // Only works in a method declaration (??!).
3879 ObjCMethodDecl *MD = getCurMethodDecl();
3880 if (!MD) {
3881 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3882 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3883 ObjCImpDecl, HasTemplateArgs);
3884
3885 goto fail;
3886 }
3887
3888 // Also must look for a getter name which uses property syntax.
3889 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003890 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3891 ObjCMethodDecl *Getter;
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003892 if ((Getter = IFace->lookupClassMethod(Sel))) {
3893 // Check the use of this method.
3894 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3895 return ExprError();
John McCall68fc88ec2010-12-15 16:46:44 +00003896 } else
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00003897 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003898 // If we found a getter then this may be a valid dot-reference, we
3899 // will look for the matching setter, in case it is needed.
3900 Selector SetterSel =
John McCall68fc88ec2010-12-15 16:46:44 +00003901 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3902 PP.getSelectorTable(), Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003903 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3904 if (!Setter) {
3905 // If this reference is in an @implementation, also check for 'private'
3906 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00003907 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003908 }
3909 // Look through local category implementations associated with the class.
3910 if (!Setter)
3911 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003912
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003913 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3914 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003915
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003916 if (Getter || Setter) {
3917 QualType PType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003918
John McCall4bc41ae2010-11-18 19:01:18 +00003919 ExprValueKind VK = VK_LValue;
3920 if (Getter) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00003921 PType = Getter->getSendResultType();
John McCall4bc41ae2010-11-18 19:01:18 +00003922 if (!getLangOptions().CPlusPlus &&
3923 IsCForbiddenLValueType(Context, PType))
3924 VK = VK_RValue;
3925 } else {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003926 // Get the expression type from Setter's incoming parameter.
3927 PType = (*(Setter->param_end() -1))->getType();
John McCall4bc41ae2010-11-18 19:01:18 +00003928 }
3929 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3930
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003931 // FIXME: we must check that the setter has property type.
John McCallb7bd14f2010-12-02 01:19:52 +00003932 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
3933 PType, VK, OK,
3934 MemberLoc, BaseExpr));
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003935 }
John McCall68fc88ec2010-12-15 16:46:44 +00003936
3937 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3938 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3939 ObjCImpDecl, HasTemplateArgs);
3940
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003941 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall68fc88ec2010-12-15 16:46:44 +00003942 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003943 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003944
John McCall68fc88ec2010-12-15 16:46:44 +00003945 // Normal property access.
3946 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc,
3947 SourceLocation(), QualType(), false);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003948 }
Alexis Huntc46382e2010-04-28 23:02:27 +00003949
Chris Lattnerb63a7452008-07-21 04:28:12 +00003950 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003951 if (BaseType->isExtVectorType()) {
John McCall15317a22010-12-15 04:42:30 +00003952 // FIXME: this expr should store IsArrow.
Anders Carlssonf571c112009-08-26 18:25:21 +00003953 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall15317a22010-12-15 04:42:30 +00003954 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr->getValueKind());
John McCall4bc41ae2010-11-18 19:01:18 +00003955 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
3956 Member, MemberLoc);
Chris Lattnerb63a7452008-07-21 04:28:12 +00003957 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003958 return ExprError();
John McCall4bc41ae2010-11-18 19:01:18 +00003959
3960 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr,
3961 *Member, MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00003962 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003963
John McCall68fc88ec2010-12-15 16:46:44 +00003964 // Adjust builtin-sel to the appropriate redefinition type if that's
3965 // not just a pointer to builtin-sel again.
3966 if (IsArrow &&
3967 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
3968 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
3969 ImpCastExprToType(BaseExpr, Context.ObjCSelRedefinitionType, CK_BitCast);
3970 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3971 ObjCImpDecl, HasTemplateArgs);
3972 }
3973
3974 // Failure cases.
3975 fail:
3976
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00003977 // Recover from dot accesses to pointers, e.g.:
3978 // type *foo;
3979 // foo.bar
3980 // This is actually well-formed in two cases:
3981 // - 'type' is an Objective C type
3982 // - 'bar' is a pseudo-destructor name which happens to refer to
3983 // the appropriate pointer type
John McCall68fc88ec2010-12-15 16:46:44 +00003984 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00003985 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
3986 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
John McCall68fc88ec2010-12-15 16:46:44 +00003987 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00003988 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3989 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall68fc88ec2010-12-15 16:46:44 +00003990
3991 // Recurse as an -> access.
3992 IsArrow = true;
3993 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3994 ObjCImpDecl, HasTemplateArgs);
3995 }
John McCall68fc88ec2010-12-15 16:46:44 +00003996 }
3997
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00003998 // If the user is trying to apply -> or . to a function name, it's probably
3999 // because they forgot parentheses to call that function.
4000 bool TryCall = false;
4001 bool Overloaded = false;
4002 UnresolvedSet<8> AllOverloads;
4003 if (const OverloadExpr *Overloads = dyn_cast<OverloadExpr>(BaseExpr)) {
4004 AllOverloads.append(Overloads->decls_begin(), Overloads->decls_end());
4005 TryCall = true;
4006 Overloaded = true;
4007 } else if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(BaseExpr)) {
4008 if (FunctionDecl* Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
4009 AllOverloads.addDecl(Fun);
4010 TryCall = true;
4011 }
4012 }
John McCall68fc88ec2010-12-15 16:46:44 +00004013
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004014 if (TryCall) {
4015 // Plunder the overload set for something that would make the member
4016 // expression valid.
4017 UnresolvedSet<4> ViableOverloads;
4018 bool HasViableZeroArgOverload = false;
4019 for (OverloadExpr::decls_iterator it = AllOverloads.begin(),
4020 DeclsEnd = AllOverloads.end(); it != DeclsEnd; ++it) {
4021 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*it);
4022 QualType ResultTy = OverloadDecl->getResultType();
4023 if ((!IsArrow && ResultTy->isRecordType()) ||
4024 (IsArrow && ResultTy->isPointerType() &&
4025 ResultTy->getPointeeType()->isRecordType())) {
4026 ViableOverloads.addDecl(*it);
4027 if (OverloadDecl->getMinRequiredArguments() == 0) {
4028 HasViableZeroArgOverload = true;
4029 }
John McCall68fc88ec2010-12-15 16:46:44 +00004030 }
4031 }
4032
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004033 if (!HasViableZeroArgOverload || ViableOverloads.size() != 1) {
4034 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
4035 << 1 << 0
4036 << BaseExpr->getSourceRange();
4037 int ViableOverloadCount = ViableOverloads.size();
4038 int I;
4039 for (I = 0; I < ViableOverloadCount; ++I) {
4040 // FIXME: Magic number for max shown overloads stolen from
4041 // OverloadCandidateSet::NoteCandidates.
4042 if (I >= 4 && Diags.getShowOverloads() == Diagnostic::Ovl_Best) {
4043 break;
4044 }
4045 Diag(ViableOverloads[I].getDecl()->getSourceRange().getBegin(),
4046 diag::note_member_ref_possible_intended_overload);
4047 }
4048 if (I != ViableOverloadCount) {
4049 Diag(BaseExpr->getExprLoc(), diag::note_ovl_too_many_candidates)
4050 << int(ViableOverloadCount - I);
4051 }
4052 return ExprError();
4053 }
4054 } else {
4055 // We don't have an expression that's convenient to get a Decl from, but we
4056 // can at least check if the type is "function of 0 arguments which returns
4057 // an acceptable type".
4058 const FunctionType *Fun = NULL;
4059 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4060 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
4061 TryCall = true;
4062 }
4063 } else if ((Fun = BaseType->getAs<FunctionType>())) {
4064 TryCall = true;
4065 }
John McCall68fc88ec2010-12-15 16:46:44 +00004066
4067 if (TryCall) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004068 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
4069 if (FPT->getNumArgs() == 0) {
4070 QualType ResultTy = Fun->getResultType();
4071 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
4072 (IsArrow && ResultTy->isPointerType() &&
4073 ResultTy->getPointeeType()->isRecordType());
4074 }
Matt Beaumont-Gay956fc1c2011-02-17 02:54:17 +00004075 }
John McCall68fc88ec2010-12-15 16:46:44 +00004076 }
4077 }
4078
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004079 if (TryCall) {
4080 // At this point, we know BaseExpr looks like it's potentially callable with
4081 // 0 arguments, and that it returns something of a reasonable type, so we
4082 // can emit a fixit and carry on pretending that BaseExpr was actually a
4083 // CallExpr.
4084 SourceLocation ParenInsertionLoc =
4085 PP.getLocForEndOfToken(BaseExpr->getLocEnd());
4086 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
4087 << int(Overloaded) << 1
4088 << BaseExpr->getSourceRange()
4089 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
4090 ExprResult NewBase = ActOnCallExpr(0, BaseExpr, ParenInsertionLoc,
4091 MultiExprArg(*this, 0, 0),
4092 ParenInsertionLoc);
4093 if (NewBase.isInvalid())
4094 return ExprError();
4095 BaseExpr = NewBase.takeAs<Expr>();
4096 DefaultFunctionArrayConversion(BaseExpr);
4097 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4098 ObjCImpDecl, HasTemplateArgs);
4099 }
4100
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004101 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
4102 << BaseType << BaseExpr->getSourceRange();
4103
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004104 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00004105}
4106
John McCall10eae182009-11-30 22:42:35 +00004107/// The main callback when the parser finds something like
4108/// expression . [nested-name-specifier] identifier
4109/// expression -> [nested-name-specifier] identifier
4110/// where 'identifier' encompasses a fairly broad spectrum of
4111/// possibilities, including destructor and operator references.
4112///
4113/// \param OpKind either tok::arrow or tok::period
4114/// \param HasTrailingLParen whether the next token is '(', which
4115/// is used to diagnose mis-uses of special members that can
4116/// only be called
4117/// \param ObjCImpDecl the current ObjC @implementation decl;
4118/// this is an ugly hack around the fact that ObjC @implementations
4119/// aren't properly put in the context chain
John McCalldadc5752010-08-24 06:29:42 +00004120ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall15317a22010-12-15 04:42:30 +00004121 SourceLocation OpLoc,
4122 tok::TokenKind OpKind,
4123 CXXScopeSpec &SS,
4124 UnqualifiedId &Id,
4125 Decl *ObjCImpDecl,
4126 bool HasTrailingLParen) {
John McCall10eae182009-11-30 22:42:35 +00004127 if (SS.isSet() && SS.isInvalid())
4128 return ExprError();
4129
Francois Pichet64225792011-01-18 05:04:39 +00004130 // Warn about the explicit constructor calls Microsoft extension.
4131 if (getLangOptions().Microsoft &&
4132 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4133 Diag(Id.getSourceRange().getBegin(),
4134 diag::ext_ms_explicit_constructor_call);
4135
John McCall10eae182009-11-30 22:42:35 +00004136 TemplateArgumentListInfo TemplateArgsBuffer;
4137
4138 // Decompose the name into its component parts.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004139 DeclarationNameInfo NameInfo;
John McCall10eae182009-11-30 22:42:35 +00004140 const TemplateArgumentListInfo *TemplateArgs;
4141 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004142 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004143
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004144 DeclarationName Name = NameInfo.getName();
John McCall10eae182009-11-30 22:42:35 +00004145 bool IsArrow = (OpKind == tok::arrow);
4146
4147 NamedDecl *FirstQualifierInScope
4148 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4149 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4150
4151 // This is a postfix expression, so get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004152 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00004153 if (Result.isInvalid()) return ExprError();
4154 Base = Result.take();
John McCall10eae182009-11-30 22:42:35 +00004155
Douglas Gregor41f90302010-04-12 20:54:26 +00004156 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4157 isDependentScopeSpecifier(SS)) {
John McCallb268a282010-08-23 23:25:46 +00004158 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00004159 IsArrow, OpLoc,
4160 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004161 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004162 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004163 LookupResult R(*this, NameInfo, LookupMemberName);
John McCalle9cccd82010-06-16 08:42:20 +00004164 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
4165 SS, ObjCImpDecl, TemplateArgs != 0);
Alexis Huntc46382e2010-04-28 23:02:27 +00004166
John McCalle9cccd82010-06-16 08:42:20 +00004167 if (Result.isInvalid()) {
4168 Owned(Base);
4169 return ExprError();
4170 }
John McCall10eae182009-11-30 22:42:35 +00004171
John McCalle9cccd82010-06-16 08:42:20 +00004172 if (Result.get()) {
4173 // The only way a reference to a destructor can be used is to
4174 // immediately call it, which falls into this case. If the
4175 // next token is not a '(', produce a diagnostic and build the
4176 // call now.
4177 if (!HasTrailingLParen &&
4178 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCallb268a282010-08-23 23:25:46 +00004179 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall10eae182009-11-30 22:42:35 +00004180
John McCalle9cccd82010-06-16 08:42:20 +00004181 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00004182 }
4183
John McCallb268a282010-08-23 23:25:46 +00004184 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00004185 OpLoc, IsArrow, SS, FirstQualifierInScope,
4186 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004187 }
4188
4189 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00004190}
4191
John McCalldadc5752010-08-24 06:29:42 +00004192ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00004193 FunctionDecl *FD,
4194 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00004195 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004196 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00004197 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00004198 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004199 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00004200 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004201 return ExprError();
4202 }
4203
4204 if (Param->hasUninstantiatedDefaultArg()) {
4205 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00004206
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004207 // Instantiate the expression.
4208 MultiLevelTemplateArgumentList ArgList
4209 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00004210
Nico Weber44887f62010-11-29 18:19:25 +00004211 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004212 = ArgList.getInnermost();
4213 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4214 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00004215
Nico Weber44887f62010-11-29 18:19:25 +00004216 ExprResult Result;
4217 {
4218 // C++ [dcl.fct.default]p5:
4219 // The names in the [default argument] expression are bound, and
4220 // the semantic constraints are checked, at the point where the
4221 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00004222 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00004223 Result = SubstExpr(UninstExpr, ArgList);
4224 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004225 if (Result.isInvalid())
4226 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004227
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004228 // Check the expression as an initializer for the parameter.
4229 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004230 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004231 InitializationKind Kind
4232 = InitializationKind::CreateCopy(Param->getLocation(),
4233 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4234 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00004235
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004236 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4237 Result = InitSeq.Perform(*this, Entity, Kind,
4238 MultiExprArg(*this, &ResultE, 1));
4239 if (Result.isInvalid())
4240 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004241
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004242 // Build the default argument expression.
4243 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4244 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00004245 }
4246
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004247 // If the default expression creates temporaries, we need to
4248 // push them to the current stack of expression temporaries so they'll
4249 // be properly destroyed.
4250 // FIXME: We should really be rebuilding the default argument with new
4251 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00004252 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4253 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4254 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4255 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4256 ExprTemporaries.push_back(Temporary);
4257 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004258
4259 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00004260 // Just mark all of the declarations in this potentially-evaluated expression
4261 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004262 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00004263 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00004264}
4265
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004266/// ConvertArgumentsForCall - Converts the arguments specified in
4267/// Args/NumArgs to the parameter types of the function FDecl with
4268/// function prototype Proto. Call is the call expression itself, and
4269/// Fn is the function expression. For a C++ member function, this
4270/// routine does not attempt to convert the object argument. Returns
4271/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004272bool
4273Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004274 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004275 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004276 Expr **Args, unsigned NumArgs,
4277 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00004278 // Bail out early if calling a builtin with custom typechecking.
4279 // We don't need to do this in the
4280 if (FDecl)
4281 if (unsigned ID = FDecl->getBuiltinID())
4282 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4283 return false;
4284
Mike Stump4e1f26a2009-02-19 03:04:26 +00004285 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004286 // assignment, to the types of the corresponding parameter, ...
4287 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00004288 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004289
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004290 // If too few arguments are available (and we don't have default
4291 // arguments for the remaining parameters), don't make the call.
4292 if (NumArgs < NumArgsInProto) {
4293 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4294 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004295 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00004296 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00004297 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004298 }
4299
4300 // If too many are passed and not variadic, error on the extras and drop
4301 // them.
4302 if (NumArgs > NumArgsInProto) {
4303 if (!Proto->isVariadic()) {
4304 Diag(Args[NumArgsInProto]->getLocStart(),
4305 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004306 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004307 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004308 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4309 Args[NumArgs-1]->getLocEnd());
4310 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00004311 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004312 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004313 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004314 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004315 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004316 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004317 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4318 if (Fn->getType()->isBlockPointerType())
4319 CallType = VariadicBlock; // Block
4320 else if (isa<MemberExpr>(Fn))
4321 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004322 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004323 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004324 if (Invalid)
4325 return true;
4326 unsigned TotalNumArgs = AllArgs.size();
4327 for (unsigned i = 0; i < TotalNumArgs; ++i)
4328 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004329
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004330 return false;
4331}
Mike Stump4e1f26a2009-02-19 03:04:26 +00004332
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004333bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4334 FunctionDecl *FDecl,
4335 const FunctionProtoType *Proto,
4336 unsigned FirstProtoArg,
4337 Expr **Args, unsigned NumArgs,
4338 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004339 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004340 unsigned NumArgsInProto = Proto->getNumArgs();
4341 unsigned NumArgsToCheck = NumArgs;
4342 bool Invalid = false;
4343 if (NumArgs != NumArgsInProto)
4344 // Use default arguments for missing arguments
4345 NumArgsToCheck = NumArgsInProto;
4346 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004347 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004348 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004349 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004350
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004351 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004352 if (ArgIx < NumArgs) {
4353 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004354
Eli Friedman3164fb12009-03-22 22:00:50 +00004355 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4356 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00004357 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004358 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00004359 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004360
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004361 // Pass the argument
4362 ParmVarDecl *Param = 0;
4363 if (FDecl && i < FDecl->getNumParams())
4364 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00004365
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004366 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004367 Param? InitializedEntity::InitializeParameter(Context, Param)
4368 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCalldadc5752010-08-24 06:29:42 +00004369 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00004370 SourceLocation(),
4371 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004372 if (ArgE.isInvalid())
4373 return true;
4374
4375 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004376 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00004377 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004378
John McCalldadc5752010-08-24 06:29:42 +00004379 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004380 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004381 if (ArgExpr.isInvalid())
4382 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004383
Anders Carlsson355933d2009-08-25 03:49:14 +00004384 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004385 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004386 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004387 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004388
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004389 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004390 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004391 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004392 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004393 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004394 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004395 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004396 }
4397 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00004398 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004399}
4400
Steve Naroff83895f72007-09-16 03:34:24 +00004401/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00004402/// This provides the location of the left/right parens and a list of comma
4403/// locations.
John McCalldadc5752010-08-24 06:29:42 +00004404ExprResult
John McCallb268a282010-08-23 23:25:46 +00004405Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004406 MultiExprArg args, SourceLocation RParenLoc,
4407 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004408 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00004409
4410 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004411 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00004412 if (Result.isInvalid()) return ExprError();
4413 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00004414
John McCallb268a282010-08-23 23:25:46 +00004415 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00004416
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004417 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00004418 // If this is a pseudo-destructor expression, build the call immediately.
4419 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4420 if (NumArgs > 0) {
4421 // Pseudo-destructor calls should not have any arguments.
4422 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00004423 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00004424 SourceRange(Args[0]->getLocStart(),
4425 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00004426
Douglas Gregorad8a3362009-09-04 17:36:40 +00004427 NumArgs = 0;
4428 }
Mike Stump11289f42009-09-09 15:08:12 +00004429
Douglas Gregorad8a3362009-09-04 17:36:40 +00004430 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00004431 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00004432 }
Mike Stump11289f42009-09-09 15:08:12 +00004433
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004434 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00004435 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00004436 // FIXME: Will need to cache the results of name lookup (including ADL) in
4437 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004438 bool Dependent = false;
4439 if (Fn->isTypeDependent())
4440 Dependent = true;
4441 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4442 Dependent = true;
4443
Peter Collingbourne41f85462011-02-09 21:07:24 +00004444 if (Dependent) {
4445 if (ExecConfig) {
4446 return Owned(new (Context) CUDAKernelCallExpr(
4447 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4448 Context.DependentTy, VK_RValue, RParenLoc));
4449 } else {
4450 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4451 Context.DependentTy, VK_RValue,
4452 RParenLoc));
4453 }
4454 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004455
4456 // Determine whether this is a call to an object (C++ [over.call.object]).
4457 if (Fn->getType()->isRecordType())
4458 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004459 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004460
John McCall10eae182009-11-30 22:42:35 +00004461 Expr *NakedFn = Fn->IgnoreParens();
4462
4463 // Determine whether this is a call to an unresolved member function.
4464 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4465 // If lookup was unresolved but not dependent (i.e. didn't find
4466 // an unresolved using declaration), it has to be an overloaded
4467 // function set, which means it must contain either multiple
4468 // declarations (all methods or method templates) or a single
4469 // method template.
4470 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor516d6722010-04-25 21:15:30 +00004471 isa<FunctionTemplateDecl>(
4472 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00004473 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00004474
John McCall2d74de92009-12-01 22:10:20 +00004475 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004476 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00004477 }
4478
Douglas Gregore254f902009-02-04 00:32:51 +00004479 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00004480 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004481 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00004482 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00004483 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004484 RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004485 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004486
Anders Carlsson61914b52009-10-03 17:40:22 +00004487 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00004488 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
John McCalle3027922010-08-25 11:45:40 +00004489 if (BO->getOpcode() == BO_PtrMemD ||
4490 BO->getOpcode() == BO_PtrMemI) {
Douglas Gregorc8be9522010-05-04 18:18:31 +00004491 if (const FunctionProtoType *FPT
4492 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00004493 QualType ResultTy = FPT->getCallResultType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00004494 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004495
Douglas Gregor125fa402011-02-04 12:57:49 +00004496 // Check that the object type isn't more qualified than the
4497 // member function we're calling.
4498 Qualifiers FuncQuals = Qualifiers::fromCVRMask(FPT->getTypeQuals());
4499 Qualifiers ObjectQuals
4500 = BO->getOpcode() == BO_PtrMemD
4501 ? BO->getLHS()->getType().getQualifiers()
4502 : BO->getLHS()->getType()->getAs<PointerType>()
4503 ->getPointeeType().getQualifiers();
4504
4505 Qualifiers Difference = ObjectQuals - FuncQuals;
4506 Difference.removeObjCGCAttr();
4507 Difference.removeAddressSpace();
4508 if (Difference) {
4509 std::string QualsString = Difference.getAsString();
4510 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
4511 << BO->getType().getUnqualifiedType()
4512 << QualsString
4513 << (QualsString.find(' ') == std::string::npos? 1 : 2);
4514 }
4515
John McCallb268a282010-08-23 23:25:46 +00004516 CXXMemberCallExpr *TheCall
Abramo Bagnara21e9d862010-12-03 21:39:42 +00004517 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
John McCall7decc9e2010-11-18 06:31:45 +00004518 NumArgs, ResultTy, VK,
John McCallb268a282010-08-23 23:25:46 +00004519 RParenLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004520
4521 if (CheckCallReturnType(FPT->getResultType(),
4522 BO->getRHS()->getSourceRange().getBegin(),
John McCallb268a282010-08-23 23:25:46 +00004523 TheCall, 0))
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004524 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00004525
John McCallb268a282010-08-23 23:25:46 +00004526 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004527 RParenLoc))
4528 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00004529
John McCallb268a282010-08-23 23:25:46 +00004530 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004531 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004532 return ExprError(Diag(Fn->getLocStart(),
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004533 diag::err_typecheck_call_not_function)
4534 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson61914b52009-10-03 17:40:22 +00004535 }
4536 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004537 }
4538
Douglas Gregore254f902009-02-04 00:32:51 +00004539 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004540 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00004541 // lookup and whether there were any explicitly-specified template arguments.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004542
Eli Friedmane14b1992009-12-26 03:35:45 +00004543 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00004544 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4545 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4546 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004547 RParenLoc, ExecConfig);
Douglas Gregor928479e2010-11-09 20:03:54 +00004548 }
4549
John McCall57500772009-12-16 12:17:52 +00004550 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00004551 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4552 if (UnOp->getOpcode() == UO_AddrOf)
4553 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4554
John McCall57500772009-12-16 12:17:52 +00004555 if (isa<DeclRefExpr>(NakedFn))
4556 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4557
Peter Collingbourne41f85462011-02-09 21:07:24 +00004558 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
4559 ExecConfig);
4560}
4561
4562ExprResult
4563Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4564 MultiExprArg execConfig, SourceLocation GGGLoc) {
4565 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4566 if (!ConfigDecl)
4567 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4568 << "cudaConfigureCall");
4569 QualType ConfigQTy = ConfigDecl->getType();
4570
4571 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4572 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
4573
4574 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00004575}
4576
John McCall57500772009-12-16 12:17:52 +00004577/// BuildResolvedCallExpr - Build a call to a resolved expression,
4578/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00004579/// unary-convert to an expression of function-pointer or
4580/// block-pointer type.
4581///
4582/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00004583ExprResult
John McCall2d74de92009-12-01 22:10:20 +00004584Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4585 SourceLocation LParenLoc,
4586 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004587 SourceLocation RParenLoc,
4588 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00004589 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4590
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004591 // Promote the function operand.
4592 UsualUnaryConversions(Fn);
4593
Chris Lattner08464942007-12-28 05:29:59 +00004594 // Make the call expr early, before semantic checks. This guarantees cleanup
4595 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00004596 CallExpr *TheCall;
4597 if (Config) {
4598 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4599 cast<CallExpr>(Config),
4600 Args, NumArgs,
4601 Context.BoolTy,
4602 VK_RValue,
4603 RParenLoc);
4604 } else {
4605 TheCall = new (Context) CallExpr(Context, Fn,
4606 Args, NumArgs,
4607 Context.BoolTy,
4608 VK_RValue,
4609 RParenLoc);
4610 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004611
John McCallbebede42011-02-26 05:39:39 +00004612 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4613
4614 // Bail out early if calling a builtin with custom typechecking.
4615 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4616 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4617
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004618 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00004619 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004620 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4621 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00004622 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00004623 if (FuncT == 0)
4624 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4625 << Fn->getType() << Fn->getSourceRange());
4626 } else if (const BlockPointerType *BPT =
4627 Fn->getType()->getAs<BlockPointerType>()) {
4628 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4629 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004630 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4631 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00004632 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004633
Peter Collingbourne4b66c472011-02-23 01:53:29 +00004634 if (getLangOptions().CUDA) {
4635 if (Config) {
4636 // CUDA: Kernel calls must be to global functions
4637 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4638 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4639 << FDecl->getName() << Fn->getSourceRange());
4640
4641 // CUDA: Kernel function must have 'void' return type
4642 if (!FuncT->getResultType()->isVoidType())
4643 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4644 << Fn->getType() << Fn->getSourceRange());
4645 }
4646 }
4647
Eli Friedman3164fb12009-03-22 22:00:50 +00004648 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004649 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00004650 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004651 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00004652 return ExprError();
4653
Chris Lattner08464942007-12-28 05:29:59 +00004654 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004655 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00004656 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004657
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004658 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00004659 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004660 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004661 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00004662 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004663 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004664
Douglas Gregord8e97de2009-04-02 15:37:10 +00004665 if (FDecl) {
4666 // Check if we have too few/too many template arguments, based
4667 // on our knowledge of the function definition.
4668 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00004669 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004670 const FunctionProtoType *Proto
4671 = Def->getType()->getAs<FunctionProtoType>();
4672 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004673 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4674 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004675 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00004676
4677 // If the function we're calling isn't a function prototype, but we have
4678 // a function prototype from a prior declaratiom, use that prototype.
4679 if (!FDecl->hasPrototype())
4680 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00004681 }
4682
Steve Naroff0b661582007-08-28 23:30:39 +00004683 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00004684 for (unsigned i = 0; i != NumArgs; i++) {
4685 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00004686
4687 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004688 InitializedEntity Entity
4689 = InitializedEntity::InitializeParameter(Context,
4690 Proto->getArgType(i));
4691 ExprResult ArgE = PerformCopyInitialization(Entity,
4692 SourceLocation(),
4693 Owned(Arg));
4694 if (ArgE.isInvalid())
4695 return true;
4696
4697 Arg = ArgE.takeAs<Expr>();
4698
4699 } else {
4700 DefaultArgumentPromotion(Arg);
Douglas Gregor8e09a722010-10-25 20:39:23 +00004701 }
4702
Douglas Gregor83025412010-10-26 05:45:40 +00004703 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4704 Arg->getType(),
4705 PDiag(diag::err_call_incomplete_argument)
4706 << Arg->getSourceRange()))
4707 return ExprError();
4708
Chris Lattner08464942007-12-28 05:29:59 +00004709 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00004710 }
Steve Naroffae4143e2007-04-26 20:39:23 +00004711 }
Chris Lattner08464942007-12-28 05:29:59 +00004712
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004713 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4714 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004715 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4716 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004717
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00004718 // Check for sentinels
4719 if (NDecl)
4720 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004721
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004722 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004723 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00004724 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004725 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004726
John McCallbebede42011-02-26 05:39:39 +00004727 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00004728 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004729 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00004730 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004731 return ExprError();
4732 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004733
John McCallb268a282010-08-23 23:25:46 +00004734 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00004735}
4736
John McCalldadc5752010-08-24 06:29:42 +00004737ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004738Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004739 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00004740 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00004741 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00004742 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00004743
4744 TypeSourceInfo *TInfo;
4745 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4746 if (!TInfo)
4747 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4748
John McCallb268a282010-08-23 23:25:46 +00004749 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00004750}
4751
John McCalldadc5752010-08-24 06:29:42 +00004752ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00004753Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00004754 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00004755 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00004756
Eli Friedman37a186d2008-05-20 05:22:08 +00004757 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004758 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4759 PDiag(diag::err_illegal_decl_array_incomplete_type)
4760 << SourceRange(LParenLoc,
4761 literalExpr->getSourceRange().getEnd())))
4762 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00004763 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004764 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4765 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00004766 } else if (!literalType->isDependentType() &&
4767 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00004768 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00004769 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00004770 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004771 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00004772
Douglas Gregor85dabae2009-12-16 01:38:02 +00004773 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00004774 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004775 InitializationKind Kind
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004776 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004777 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00004778 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00004779 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00004780 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00004781 &literalType);
4782 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004783 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00004784 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00004785
Chris Lattner79413952008-12-04 23:50:19 +00004786 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00004787 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00004788 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004789 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004790 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004791
John McCall7decc9e2010-11-18 06:31:45 +00004792 // In C, compound literals are l-values for some reason.
4793 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
4794
John McCall5d7aa7f2010-01-19 22:33:45 +00004795 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCall7decc9e2010-11-18 06:31:45 +00004796 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004797}
4798
John McCalldadc5752010-08-24 06:29:42 +00004799ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00004800Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004801 SourceLocation RBraceLoc) {
4802 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00004803 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00004804
Steve Naroff30d242c2007-09-15 18:49:24 +00004805 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004806 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004807
Ted Kremenekac034612010-04-13 23:39:13 +00004808 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4809 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004810 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004811 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004812}
4813
John McCalld7646252010-11-14 08:17:51 +00004814/// Prepares for a scalar cast, performing all the necessary stages
4815/// except the final cast and returning the kind required.
4816static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
4817 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4818 // Also, callers should have filtered out the invalid cases with
4819 // pointers. Everything else should be possible.
4820
Abramo Bagnaraba854972011-01-04 09:50:03 +00004821 QualType SrcTy = Src->getType();
John McCalld7646252010-11-14 08:17:51 +00004822 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004823 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004824
John McCall8cb679e2010-11-15 09:13:47 +00004825 switch (SrcTy->getScalarTypeKind()) {
4826 case Type::STK_MemberPointer:
4827 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00004828
John McCall8cb679e2010-11-15 09:13:47 +00004829 case Type::STK_Pointer:
4830 switch (DestTy->getScalarTypeKind()) {
4831 case Type::STK_Pointer:
4832 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00004833 CK_AnyPointerToObjCPointerCast :
4834 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00004835 case Type::STK_Bool:
4836 return CK_PointerToBoolean;
4837 case Type::STK_Integral:
4838 return CK_PointerToIntegral;
4839 case Type::STK_Floating:
4840 case Type::STK_FloatingComplex:
4841 case Type::STK_IntegralComplex:
4842 case Type::STK_MemberPointer:
4843 llvm_unreachable("illegal cast from pointer");
4844 }
4845 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004846
John McCall8cb679e2010-11-15 09:13:47 +00004847 case Type::STK_Bool: // casting from bool is like casting from an integer
4848 case Type::STK_Integral:
4849 switch (DestTy->getScalarTypeKind()) {
4850 case Type::STK_Pointer:
John McCalld7646252010-11-14 08:17:51 +00004851 if (Src->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004852 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004853 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004854 case Type::STK_Bool:
4855 return CK_IntegralToBoolean;
4856 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004857 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004858 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004859 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004860 case Type::STK_IntegralComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004861 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallfcef3cf2010-12-14 17:51:41 +00004862 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004863 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004864 case Type::STK_FloatingComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004865 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004866 CK_IntegralToFloating);
4867 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004868 case Type::STK_MemberPointer:
4869 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004870 }
4871 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004872
John McCall8cb679e2010-11-15 09:13:47 +00004873 case Type::STK_Floating:
4874 switch (DestTy->getScalarTypeKind()) {
4875 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004876 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004877 case Type::STK_Bool:
4878 return CK_FloatingToBoolean;
4879 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004880 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004881 case Type::STK_FloatingComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004882 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallfcef3cf2010-12-14 17:51:41 +00004883 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004884 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004885 case Type::STK_IntegralComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004886 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004887 CK_FloatingToIntegral);
4888 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004889 case Type::STK_Pointer:
4890 llvm_unreachable("valid float->pointer cast?");
4891 case Type::STK_MemberPointer:
4892 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004893 }
4894 break;
4895
John McCall8cb679e2010-11-15 09:13:47 +00004896 case Type::STK_FloatingComplex:
4897 switch (DestTy->getScalarTypeKind()) {
4898 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004899 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004900 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004901 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004902 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00004903 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00004904 if (S.Context.hasSameType(ET, DestTy))
4905 return CK_FloatingComplexToReal;
4906 S.ImpCastExprToType(Src, ET, CK_FloatingComplexToReal);
4907 return CK_FloatingCast;
4908 }
John McCall8cb679e2010-11-15 09:13:47 +00004909 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004910 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004911 case Type::STK_Integral:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004912 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004913 CK_FloatingComplexToReal);
4914 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004915 case Type::STK_Pointer:
4916 llvm_unreachable("valid complex float->pointer cast?");
4917 case Type::STK_MemberPointer:
4918 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004919 }
4920 break;
4921
John McCall8cb679e2010-11-15 09:13:47 +00004922 case Type::STK_IntegralComplex:
4923 switch (DestTy->getScalarTypeKind()) {
4924 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004925 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004926 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004927 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004928 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00004929 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00004930 if (S.Context.hasSameType(ET, DestTy))
4931 return CK_IntegralComplexToReal;
4932 S.ImpCastExprToType(Src, ET, CK_IntegralComplexToReal);
4933 return CK_IntegralCast;
4934 }
John McCall8cb679e2010-11-15 09:13:47 +00004935 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004936 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004937 case Type::STK_Floating:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004938 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004939 CK_IntegralComplexToReal);
4940 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004941 case Type::STK_Pointer:
4942 llvm_unreachable("valid complex int->pointer cast?");
4943 case Type::STK_MemberPointer:
4944 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004945 }
4946 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00004947 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004948
John McCalld7646252010-11-14 08:17:51 +00004949 llvm_unreachable("Unhandled scalar cast");
4950 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00004951}
4952
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004953/// CheckCastTypes - Check type constraints for casting between types.
John McCall7decc9e2010-11-18 06:31:45 +00004954bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
4955 Expr *&castExpr, CastKind& Kind, ExprValueKind &VK,
4956 CXXCastPath &BasePath, bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00004957 if (getLangOptions().CPlusPlus)
Douglas Gregor15417cf2010-11-03 00:35:38 +00004958 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
4959 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00004960 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00004961 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00004962
John McCall7decc9e2010-11-18 06:31:45 +00004963 // We only support r-value casts in C.
4964 VK = VK_RValue;
4965
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004966 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4967 // type needs to be scalar.
4968 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00004969 // We don't necessarily do lvalue-to-rvalue conversions on this.
4970 IgnoredValueConversions(castExpr);
4971
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004972 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00004973 Kind = CK_ToVoid;
Anders Carlssonef918ac2009-10-16 02:35:04 +00004974 return false;
4975 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004976
John McCall34376a62010-12-04 03:47:34 +00004977 DefaultFunctionArrayLvalueConversion(castExpr);
4978
Eli Friedmane98194d2010-07-17 20:43:49 +00004979 if (RequireCompleteType(TyR.getBegin(), castType,
4980 diag::err_typecheck_cast_to_incomplete))
4981 return true;
4982
Anders Carlssonef918ac2009-10-16 02:35:04 +00004983 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004984 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004985 (castType->isStructureType() || castType->isUnionType())) {
4986 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00004987 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004988 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
4989 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004990 Kind = CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00004991 return false;
4992 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004993
Anders Carlsson525b76b2009-10-16 02:48:28 +00004994 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004995 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004996 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004997 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004998 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004999 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005000 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00005001 castExpr->getType()) &&
5002 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005003 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
5004 << castExpr->getSourceRange();
5005 break;
5006 }
5007 }
5008 if (Field == FieldEnd)
5009 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
5010 << castExpr->getType() << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005011 Kind = CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00005012 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005013 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005014
Anders Carlsson525b76b2009-10-16 02:48:28 +00005015 // Reject any other conversions to non-scalar types.
5016 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
5017 << castType << castExpr->getSourceRange();
5018 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005019
John McCalld7646252010-11-14 08:17:51 +00005020 // The type we're casting to is known to be a scalar or vector.
5021
5022 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005023 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00005024 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00005025 return Diag(castExpr->getLocStart(),
5026 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005027 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00005028 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005029
5030 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00005031 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005032
Anders Carlsson525b76b2009-10-16 02:48:28 +00005033 if (castType->isVectorType())
5034 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
5035 if (castExpr->getType()->isVectorType())
5036 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
5037
John McCalld7646252010-11-14 08:17:51 +00005038 // The source and target types are both scalars, i.e.
5039 // - arithmetic types (fundamental, enum, and complex)
5040 // - all kinds of pointers
5041 // Note that member pointers were filtered out with C++, above.
5042
Anders Carlsson43d70f82009-10-16 05:23:41 +00005043 if (isa<ObjCSelectorExpr>(castExpr))
5044 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005045
John McCalld7646252010-11-14 08:17:51 +00005046 // If either type is a pointer, the other type has to be either an
5047 // integer or a pointer.
Anders Carlsson525b76b2009-10-16 02:48:28 +00005048 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005049 QualType castExprType = castExpr->getType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005050 if (!castExprType->isIntegralType(Context) &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005051 castExprType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005052 return Diag(castExpr->getLocStart(),
5053 diag::err_cast_pointer_from_non_pointer_int)
5054 << castExprType << castExpr->getSourceRange();
5055 } else if (!castExpr->getType()->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00005056 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005057 return Diag(castExpr->getLocStart(),
5058 diag::err_cast_pointer_to_non_pointer_int)
5059 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005060 }
Anders Carlsson094c4592009-10-18 18:12:03 +00005061
John McCalld7646252010-11-14 08:17:51 +00005062 Kind = PrepareScalarCast(*this, castExpr, castType);
John McCall2b5c1b22010-08-12 21:44:57 +00005063
John McCalld7646252010-11-14 08:17:51 +00005064 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00005065 CheckCastAlign(castExpr, castType, TyR);
5066
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005067 return false;
5068}
5069
Anders Carlsson525b76b2009-10-16 02:48:28 +00005070bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00005071 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00005072 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005073
Anders Carlssonde71adf2007-11-27 05:51:55 +00005074 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00005075 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00005076 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00005077 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00005078 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00005079 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005080 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005081 } else
5082 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00005083 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005084 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005085
John McCalle3027922010-08-25 11:45:40 +00005086 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005087 return false;
5088}
5089
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005090bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
John McCalle3027922010-08-25 11:45:40 +00005091 CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00005092 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005093
Anders Carlsson43d70f82009-10-16 05:23:41 +00005094 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005095
Nate Begemanc8961a42009-06-27 22:05:55 +00005096 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5097 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00005098 if (SrcTy->isVectorType()) {
5099 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
5100 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5101 << DestTy << SrcTy << R;
John McCalle3027922010-08-25 11:45:40 +00005102 Kind = CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00005103 return false;
5104 }
5105
Nate Begemanbd956c42009-06-28 02:36:38 +00005106 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00005107 // conversion will take place first from scalar to elt type, and then
5108 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00005109 if (SrcTy->isPointerType())
5110 return Diag(R.getBegin(),
5111 diag::err_invalid_conversion_between_vector_and_scalar)
5112 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00005113
5114 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5115 ImpCastExprToType(CastExpr, DestElemTy,
John McCalld7646252010-11-14 08:17:51 +00005116 PrepareScalarCast(*this, CastExpr, DestElemTy));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005117
John McCalle3027922010-08-25 11:45:40 +00005118 Kind = CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00005119 return false;
5120}
5121
John McCalldadc5752010-08-24 06:29:42 +00005122ExprResult
John McCallba7bf592010-08-24 05:47:05 +00005123Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00005124 SourceLocation RParenLoc, Expr *castExpr) {
5125 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00005126 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00005127
John McCall97513962010-01-15 18:39:57 +00005128 TypeSourceInfo *castTInfo;
5129 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5130 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00005131 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00005132
Nate Begeman5ec4b312009-08-10 23:49:36 +00005133 // If the Expr being casted is a ParenListExpr, handle it specially.
5134 if (isa<ParenListExpr>(castExpr))
John McCallb268a282010-08-23 23:25:46 +00005135 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCalle15bbff2010-01-18 19:35:47 +00005136 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00005137
John McCallb268a282010-08-23 23:25:46 +00005138 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00005139}
5140
John McCalldadc5752010-08-24 06:29:42 +00005141ExprResult
John McCallebe54742010-01-15 18:56:44 +00005142Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00005143 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00005144 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00005145 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00005146 CXXCastPath BasePath;
John McCallebe54742010-01-15 18:56:44 +00005147 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
John McCall7decc9e2010-11-18 06:31:45 +00005148 Kind, VK, BasePath))
Sebastian Redlb5d49352009-01-19 22:31:54 +00005149 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00005150
John McCallcf142162010-08-07 06:22:56 +00005151 return Owned(CStyleCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +00005152 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00005153 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00005154 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00005155}
5156
Nate Begeman5ec4b312009-08-10 23:49:36 +00005157/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5158/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00005159ExprResult
John McCallb268a282010-08-23 23:25:46 +00005160Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005161 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5162 if (!E)
5163 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00005164
John McCalldadc5752010-08-24 06:29:42 +00005165 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00005166
Nate Begeman5ec4b312009-08-10 23:49:36 +00005167 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00005168 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5169 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00005170
John McCallb268a282010-08-23 23:25:46 +00005171 if (Result.isInvalid()) return ExprError();
5172
5173 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005174}
5175
John McCalldadc5752010-08-24 06:29:42 +00005176ExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00005177Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00005178 SourceLocation RParenLoc, Expr *Op,
John McCalle15bbff2010-01-18 19:35:47 +00005179 TypeSourceInfo *TInfo) {
John McCallb268a282010-08-23 23:25:46 +00005180 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCalle15bbff2010-01-18 19:35:47 +00005181 QualType Ty = TInfo->getType();
John Thompson781ad172010-06-30 22:55:51 +00005182 bool isAltiVecLiteral = false;
Mike Stump11289f42009-09-09 15:08:12 +00005183
John Thompson781ad172010-06-30 22:55:51 +00005184 // Check for an altivec literal,
5185 // i.e. all the elements are integer constants.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005186 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5187 if (PE->getNumExprs() == 0) {
5188 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5189 return ExprError();
5190 }
John Thompson781ad172010-06-30 22:55:51 +00005191 if (PE->getNumExprs() == 1) {
5192 if (!PE->getExpr(0)->getType()->isVectorType())
5193 isAltiVecLiteral = true;
5194 }
5195 else
5196 isAltiVecLiteral = true;
5197 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00005198
John Thompson781ad172010-06-30 22:55:51 +00005199 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
5200 // then handle it as such.
5201 if (isAltiVecLiteral) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005202 llvm::SmallVector<Expr *, 8> initExprs;
5203 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5204 initExprs.push_back(PE->getExpr(i));
5205
5206 // FIXME: This means that pretty-printing the final AST will produce curly
5207 // braces instead of the original commas.
Ted Kremenekac034612010-04-13 23:39:13 +00005208 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5209 &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00005210 initExprs.size(), RParenLoc);
5211 E->setType(Ty);
John McCallb268a282010-08-23 23:25:46 +00005212 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005213 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005214 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00005215 // sequence of BinOp comma operators.
John McCalldadc5752010-08-24 06:29:42 +00005216 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCallb268a282010-08-23 23:25:46 +00005217 if (Result.isInvalid()) return ExprError();
5218 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005219 }
5220}
5221
John McCalldadc5752010-08-24 06:29:42 +00005222ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00005223 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005224 MultiExprArg Val,
John McCallba7bf592010-08-24 05:47:05 +00005225 ParsedType TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005226 unsigned nexprs = Val.size();
5227 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005228 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5229 Expr *expr;
5230 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5231 expr = new (Context) ParenExpr(L, R, exprs[0]);
5232 else
5233 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005234 return Owned(expr);
5235}
5236
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005237/// \brief Emit a specialized diagnostic when one expression is a null pointer
5238/// constant and the other is not a pointer.
5239bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5240 SourceLocation QuestionLoc) {
5241 Expr *NullExpr = LHS;
5242 Expr *NonPointerExpr = RHS;
5243 Expr::NullPointerConstantKind NullKind =
5244 NullExpr->isNullPointerConstant(Context,
5245 Expr::NPC_ValueDependentIsNotNull);
5246
5247 if (NullKind == Expr::NPCK_NotNull) {
5248 NullExpr = RHS;
5249 NonPointerExpr = LHS;
5250 NullKind =
5251 NullExpr->isNullPointerConstant(Context,
5252 Expr::NPC_ValueDependentIsNotNull);
5253 }
5254
5255 if (NullKind == Expr::NPCK_NotNull)
5256 return false;
5257
5258 if (NullKind == Expr::NPCK_ZeroInteger) {
5259 // In this case, check to make sure that we got here from a "NULL"
5260 // string in the source code.
5261 NullExpr = NullExpr->IgnoreParenImpCasts();
5262 SourceManager& SM = Context.getSourceManager();
5263 SourceLocation Loc = SM.getInstantiationLoc(NullExpr->getExprLoc());
5264 unsigned Len =
5265 Lexer::MeasureTokenLength(Loc, SM, Context.getLangOptions());
5266 if (Len != 4 || memcmp(SM.getCharacterData(Loc), "NULL", 4))
5267 return false;
5268 }
5269
5270 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5271 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5272 << NonPointerExpr->getType() << DiagType
5273 << NonPointerExpr->getSourceRange();
5274 return true;
5275}
5276
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005277/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5278/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00005279/// C99 6.5.15
5280QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005281 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00005282 SourceLocation QuestionLoc) {
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005283 // If both LHS and RHS are overloaded functions, try to resolve them.
5284 if (Context.hasSameType(LHS->getType(), RHS->getType()) &&
5285 LHS->getType()->isSpecificBuiltinType(BuiltinType::Overload)) {
5286 ExprResult LHSResult = CheckPlaceholderExpr(LHS, QuestionLoc);
5287 if (LHSResult.isInvalid())
5288 return QualType();
5289
5290 ExprResult RHSResult = CheckPlaceholderExpr(RHS, QuestionLoc);
5291 if (RHSResult.isInvalid())
5292 return QualType();
5293
5294 LHS = LHSResult.take();
5295 RHS = RHSResult.take();
5296 }
5297
Sebastian Redl1a99f442009-04-16 17:51:27 +00005298 // C++ is sufficiently different to merit its own checker.
5299 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00005300 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00005301
5302 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005303 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005304
Chris Lattner432cff52009-02-18 04:28:32 +00005305 UsualUnaryConversions(Cond);
John McCallc07a0c72011-02-17 10:25:35 +00005306 UsualUnaryConversions(LHS);
Chris Lattner432cff52009-02-18 04:28:32 +00005307 UsualUnaryConversions(RHS);
5308 QualType CondTy = Cond->getType();
5309 QualType LHSTy = LHS->getType();
5310 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00005311
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005312 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005313 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00005314 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5315 // Throw an error if its not either.
5316 if (getLangOptions().OpenCL) {
5317 if (!CondTy->isVectorType()) {
5318 Diag(Cond->getLocStart(),
5319 diag::err_typecheck_cond_expect_scalar_or_vector)
5320 << CondTy;
5321 return QualType();
5322 }
5323 }
5324 else {
5325 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5326 << CondTy;
5327 return QualType();
5328 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005329 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005330
Chris Lattnere2949f42008-01-06 22:42:25 +00005331 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005332 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5333 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00005334
Nate Begemanabb5a732010-09-20 22:41:17 +00005335 // OpenCL: If the condition is a vector, and both operands are scalar,
5336 // attempt to implicity convert them to the vector type to act like the
5337 // built in select.
5338 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5339 // Both operands should be of scalar type.
5340 if (!LHSTy->isScalarType()) {
5341 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5342 << CondTy;
5343 return QualType();
5344 }
5345 if (!RHSTy->isScalarType()) {
5346 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5347 << CondTy;
5348 return QualType();
5349 }
5350 // Implicity convert these scalars to the type of the condition.
5351 ImpCastExprToType(LHS, CondTy, CK_IntegralCast);
5352 ImpCastExprToType(RHS, CondTy, CK_IntegralCast);
5353 }
5354
Chris Lattnere2949f42008-01-06 22:42:25 +00005355 // If both operands have arithmetic type, do the usual arithmetic conversions
5356 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00005357 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5358 UsualArithmeticConversions(LHS, RHS);
5359 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00005360 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005361
Chris Lattnere2949f42008-01-06 22:42:25 +00005362 // If both operands are the same structure or union type, the result is that
5363 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005364 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5365 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00005366 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005367 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00005368 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00005369 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00005370 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005371 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005372
Chris Lattnere2949f42008-01-06 22:42:25 +00005373 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00005374 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00005375 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5376 if (!LHSTy->isVoidType())
5377 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5378 << RHS->getSourceRange();
5379 if (!RHSTy->isVoidType())
5380 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5381 << LHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005382 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid);
5383 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00005384 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00005385 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00005386 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5387 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00005388 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005389 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005390 // promote the null to a pointer.
John McCall8cb679e2010-11-15 09:13:47 +00005391 ImpCastExprToType(RHS, LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005392 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005393 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005394 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005395 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00005396 ImpCastExprToType(LHS, RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005397 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005398 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005399
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005400 // All objective-c pointer type analysis is done here.
5401 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5402 QuestionLoc);
5403 if (!compositeType.isNull())
5404 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005405
5406
Steve Naroff05efa972009-07-01 14:36:47 +00005407 // Handle block pointer types.
5408 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5409 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5410 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5411 QualType destType = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005412 ImpCastExprToType(LHS, destType, CK_BitCast);
5413 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005414 return destType;
5415 }
5416 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005417 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00005418 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00005419 }
Steve Naroff05efa972009-07-01 14:36:47 +00005420 // We have 2 block pointer types.
5421 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5422 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00005423 return LHSTy;
5424 }
Steve Naroff05efa972009-07-01 14:36:47 +00005425 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005426 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5427 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005428
Steve Naroff05efa972009-07-01 14:36:47 +00005429 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5430 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00005431 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005432 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00005433 // In this situation, we assume void* type. No especially good
5434 // reason, but this is what gcc does, and we do have to pick
5435 // to get a consistent AST.
5436 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005437 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5438 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00005439 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005440 }
Steve Naroff05efa972009-07-01 14:36:47 +00005441 // The block pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00005442 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5443 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00005444 return LHSTy;
5445 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005446
Steve Naroff05efa972009-07-01 14:36:47 +00005447 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5448 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5449 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005450 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5451 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00005452
5453 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5454 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5455 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00005456 QualType destPointee
5457 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005458 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005459 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005460 ImpCastExprToType(LHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005461 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005462 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005463 return destType;
5464 }
5465 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00005466 QualType destPointee
5467 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005468 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005469 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005470 ImpCastExprToType(RHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005471 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005472 ImpCastExprToType(LHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005473 return destType;
5474 }
5475
5476 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5477 // Two identical pointer types are always compatible.
5478 return LHSTy;
5479 }
5480 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5481 rhptee.getUnqualifiedType())) {
5482 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5483 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5484 // In this situation, we assume void* type. No especially good
5485 // reason, but this is what gcc does, and we do have to pick
5486 // to get a consistent AST.
5487 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005488 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5489 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005490 return incompatTy;
5491 }
5492 // The pointer types are compatible.
5493 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5494 // differently qualified versions of compatible types, the result type is
5495 // a pointer to an appropriately qualified version of the *composite*
5496 // type.
5497 // FIXME: Need to calculate the composite type.
5498 // FIXME: Need to add qualifiers
John McCalle3027922010-08-25 11:45:40 +00005499 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5500 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005501 return LHSTy;
5502 }
Mike Stump11289f42009-09-09 15:08:12 +00005503
John McCalle84af4e2010-11-13 01:35:44 +00005504 // GCC compatibility: soften pointer/integer mismatch. Note that
5505 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00005506 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5507 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5508 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005509 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005510 return RHSTy;
5511 }
5512 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5513 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5514 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005515 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005516 return LHSTy;
5517 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00005518
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005519 // Emit a better diagnostic if one of the expressions is a null pointer
5520 // constant and the other is not a pointer type. In this case, the user most
5521 // likely forgot to take the address of the other expression.
5522 if (DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
5523 return QualType();
5524
Chris Lattnere2949f42008-01-06 22:42:25 +00005525 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00005526 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5527 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005528 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00005529}
5530
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005531/// FindCompositeObjCPointerType - Helper method to find composite type of
5532/// two objective-c pointer types of the two input expressions.
5533QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
5534 SourceLocation QuestionLoc) {
5535 QualType LHSTy = LHS->getType();
5536 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005537
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005538 // Handle things like Class and struct objc_class*. Here we case the result
5539 // to the pseudo-builtin, because that will be implicitly cast back to the
5540 // redefinition type if an attempt is made to access its fields.
5541 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005542 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005543 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005544 return LHSTy;
5545 }
5546 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005547 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005548 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005549 return RHSTy;
5550 }
5551 // And the same for struct objc_object* / id
5552 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005553 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005554 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005555 return LHSTy;
5556 }
5557 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005558 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005559 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005560 return RHSTy;
5561 }
5562 // And the same for struct objc_selector* / SEL
5563 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005564 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005565 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005566 return LHSTy;
5567 }
5568 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005569 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005570 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005571 return RHSTy;
5572 }
5573 // Check constraints for Objective-C object pointers types.
5574 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005575
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005576 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5577 // Two identical object pointer types are always compatible.
5578 return LHSTy;
5579 }
5580 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5581 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5582 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005583
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005584 // If both operands are interfaces and either operand can be
5585 // assigned to the other, use that type as the composite
5586 // type. This allows
5587 // xxx ? (A*) a : (B*) b
5588 // where B is a subclass of A.
5589 //
5590 // Additionally, as for assignment, if either type is 'id'
5591 // allow silent coercion. Finally, if the types are
5592 // incompatible then make sure to use 'id' as the composite
5593 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005594
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005595 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5596 // It could return the composite type.
5597 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5598 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5599 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5600 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5601 } else if ((LHSTy->isObjCQualifiedIdType() ||
5602 RHSTy->isObjCQualifiedIdType()) &&
5603 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5604 // Need to handle "id<xx>" explicitly.
5605 // GCC allows qualified id and any Objective-C type to devolve to
5606 // id. Currently localizing to here until clear this should be
5607 // part of ObjCQualifiedIdTypesAreCompatible.
5608 compositeType = Context.getObjCIdType();
5609 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5610 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005611 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005612 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5613 ;
5614 else {
5615 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5616 << LHSTy << RHSTy
5617 << LHS->getSourceRange() << RHS->getSourceRange();
5618 QualType incompatTy = Context.getObjCIdType();
John McCalle3027922010-08-25 11:45:40 +00005619 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5620 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005621 return incompatTy;
5622 }
5623 // The object pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00005624 ImpCastExprToType(LHS, compositeType, CK_BitCast);
5625 ImpCastExprToType(RHS, compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005626 return compositeType;
5627 }
5628 // Check Objective-C object pointer types and 'void *'
5629 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5630 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5631 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5632 QualType destPointee
5633 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5634 QualType destType = Context.getPointerType(destPointee);
5635 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005636 ImpCastExprToType(LHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005637 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005638 ImpCastExprToType(RHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005639 return destType;
5640 }
5641 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5642 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5643 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5644 QualType destPointee
5645 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5646 QualType destType = Context.getPointerType(destPointee);
5647 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005648 ImpCastExprToType(RHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005649 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005650 ImpCastExprToType(LHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005651 return destType;
5652 }
5653 return QualType();
5654}
5655
Steve Naroff83895f72007-09-16 03:34:24 +00005656/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005657/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005658ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005659 SourceLocation ColonLoc,
5660 Expr *CondExpr, Expr *LHSExpr,
5661 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005662 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5663 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005664 OpaqueValueExpr *opaqueValue = 0;
5665 Expr *commonExpr = 0;
5666 if (LHSExpr == 0) {
5667 commonExpr = CondExpr;
5668
5669 // We usually want to apply unary conversions *before* saving, except
5670 // in the special case of a C++ l-value conditional.
5671 if (!(getLangOptions().CPlusPlus
5672 && !commonExpr->isTypeDependent()
5673 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5674 && commonExpr->isGLValue()
5675 && commonExpr->isOrdinaryOrBitFieldObject()
5676 && RHSExpr->isOrdinaryOrBitFieldObject()
5677 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5678 UsualUnaryConversions(commonExpr);
5679 }
5680
5681 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5682 commonExpr->getType(),
5683 commonExpr->getValueKind(),
5684 commonExpr->getObjectKind());
5685 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005686 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005687
John McCall7decc9e2010-11-18 06:31:45 +00005688 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005689 ExprObjectKind OK = OK_Ordinary;
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00005690 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr,
John McCallc07a0c72011-02-17 10:25:35 +00005691 VK, OK, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00005692 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005693 return ExprError();
5694
John McCallc07a0c72011-02-17 10:25:35 +00005695 if (!commonExpr)
5696 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
5697 LHSExpr, ColonLoc,
5698 RHSExpr, result, VK, OK));
5699
5700 return Owned(new (Context)
5701 BinaryConditionalOperator(commonExpr, opaqueValue, CondExpr, LHSExpr,
5702 RHSExpr, QuestionLoc, ColonLoc, result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005703}
5704
John McCallaba90822011-01-31 23:13:11 +00005705// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005706// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005707// routine is it effectively iqnores the qualifiers on the top level pointee.
5708// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5709// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005710static Sema::AssignConvertType
5711checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5712 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5713 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005714
Steve Naroff1f4d7272007-05-11 04:00:31 +00005715 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005716 const Type *lhptee, *rhptee;
5717 Qualifiers lhq, rhq;
5718 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5719 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005720
John McCallaba90822011-01-31 23:13:11 +00005721 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005722
5723 // C99 6.5.16.1p1: This following citation is common to constraints
5724 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5725 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005726 Qualifiers lq;
5727
5728 if (!lhq.compatiblyIncludes(rhq)) {
5729 // Treat address-space mismatches as fatal. TODO: address subspaces
5730 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5731 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5732
5733 // For GCC compatibility, other qualifier mismatches are treated
5734 // as still compatible in C.
5735 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5736 }
Steve Naroff3f597292007-05-11 22:18:03 +00005737
Mike Stump4e1f26a2009-02-19 03:04:26 +00005738 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5739 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005740 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005741 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005742 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005743 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005744
Chris Lattner0a788432008-01-03 22:56:36 +00005745 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005746 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005747 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005748 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005749
Chris Lattner0a788432008-01-03 22:56:36 +00005750 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005751 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005752 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005753
5754 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005755 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005756 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005757 }
John McCall4fff8f62011-02-01 00:10:29 +00005758
Mike Stump4e1f26a2009-02-19 03:04:26 +00005759 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005760 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005761 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5762 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005763 // Check if the pointee types are compatible ignoring the sign.
5764 // We explicitly check for char so that we catch "char" vs
5765 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005766 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005767 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005768 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005769 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005770
Chris Lattnerec3a1562009-10-17 20:33:28 +00005771 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005772 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005773 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005774 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005775
John McCall4fff8f62011-02-01 00:10:29 +00005776 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005777 // Types are compatible ignoring the sign. Qualifier incompatibility
5778 // takes priority over sign incompatibility because the sign
5779 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005780 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005781 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005782
John McCallaba90822011-01-31 23:13:11 +00005783 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005784 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005785
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005786 // If we are a multi-level pointer, it's possible that our issue is simply
5787 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5788 // the eventual target type is the same and the pointers have the same
5789 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005790 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005791 do {
John McCall4fff8f62011-02-01 00:10:29 +00005792 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5793 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005794 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005795
John McCall4fff8f62011-02-01 00:10:29 +00005796 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005797 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005798 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005799
Eli Friedman80160bd2009-03-22 23:59:44 +00005800 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005801 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005802 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005803 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005804}
5805
John McCallaba90822011-01-31 23:13:11 +00005806/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005807/// block pointer types are compatible or whether a block and normal pointer
5808/// are compatible. It is more restrict than comparing two function pointer
5809// types.
John McCallaba90822011-01-31 23:13:11 +00005810static Sema::AssignConvertType
5811checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5812 QualType rhsType) {
5813 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5814 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5815
Steve Naroff081c7422008-09-04 15:10:53 +00005816 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005817
Steve Naroff081c7422008-09-04 15:10:53 +00005818 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00005819 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5820 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005821
John McCallaba90822011-01-31 23:13:11 +00005822 // In C++, the types have to match exactly.
5823 if (S.getLangOptions().CPlusPlus)
5824 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005825
John McCallaba90822011-01-31 23:13:11 +00005826 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005827
Steve Naroff081c7422008-09-04 15:10:53 +00005828 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005829 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5830 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005831
John McCallaba90822011-01-31 23:13:11 +00005832 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5833 return Sema::IncompatibleBlockPointer;
5834
Steve Naroff081c7422008-09-04 15:10:53 +00005835 return ConvTy;
5836}
5837
John McCallaba90822011-01-31 23:13:11 +00005838/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005839/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005840static Sema::AssignConvertType
5841checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5842 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5843 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5844
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005845 if (lhsType->isObjCBuiltinType()) {
5846 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005847 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5848 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005849 return Sema::IncompatiblePointer;
5850 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005851 }
5852 if (rhsType->isObjCBuiltinType()) {
5853 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005854 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5855 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005856 return Sema::IncompatiblePointer;
5857 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005858 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005859 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005860 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005861 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005862 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005863
John McCallaba90822011-01-31 23:13:11 +00005864 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5865 return Sema::CompatiblePointerDiscardsQualifiers;
5866
5867 if (S.Context.typesAreCompatible(lhsType, rhsType))
5868 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005869 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005870 return Sema::IncompatibleObjCQualifiedId;
5871 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005872}
5873
John McCall29600e12010-11-16 02:32:08 +00005874Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005875Sema::CheckAssignmentConstraints(SourceLocation Loc,
5876 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00005877 // Fake up an opaque expression. We don't actually care about what
5878 // cast operations are required, so if CheckAssignmentConstraints
5879 // adds casts to this they'll be wasted, but fortunately that doesn't
5880 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00005881 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John McCall29600e12010-11-16 02:32:08 +00005882 Expr *rhsPtr = &rhs;
5883 CastKind K = CK_Invalid;
5884
5885 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5886}
5887
Mike Stump4e1f26a2009-02-19 03:04:26 +00005888/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5889/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005890/// pointers. Here are some objectionable examples that GCC considers warnings:
5891///
5892/// int a, *pint;
5893/// short *pshort;
5894/// struct foo *pfoo;
5895///
5896/// pint = pshort; // warning: assignment from incompatible pointer type
5897/// a = pint; // warning: assignment makes integer from pointer without a cast
5898/// pint = a; // warning: assignment makes pointer from integer without a cast
5899/// pint = pfoo; // warning: assignment from incompatible pointer type
5900///
5901/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005902/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005903///
John McCall8cb679e2010-11-15 09:13:47 +00005904/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005905Sema::AssignConvertType
John McCall29600e12010-11-16 02:32:08 +00005906Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs,
John McCall8cb679e2010-11-15 09:13:47 +00005907 CastKind &Kind) {
John McCall29600e12010-11-16 02:32:08 +00005908 QualType rhsType = rhs->getType();
5909
Chris Lattnera52c2f22008-01-04 23:18:45 +00005910 // Get canonical types. We're not formatting these types, just comparing
5911 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00005912 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5913 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005914
John McCalle5255932011-01-31 22:28:28 +00005915 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00005916 if (lhsType == rhsType) {
5917 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005918 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005919 }
5920
Douglas Gregor6b754842008-10-28 00:22:11 +00005921 // If the left-hand side is a reference type, then we are in a
5922 // (rare!) case where we've allowed the use of references in C,
5923 // e.g., as a parameter type in a built-in function. In this case,
5924 // just make sure that the type referenced is compatible with the
5925 // right-hand side type. The caller is responsible for adjusting
5926 // lhsType so that the resulting expression does not have reference
5927 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005928 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005929 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5930 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005931 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005932 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005933 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005934 }
John McCalle5255932011-01-31 22:28:28 +00005935
Nate Begemanbd956c42009-06-28 02:36:38 +00005936 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5937 // to the same ExtVector type.
5938 if (lhsType->isExtVectorType()) {
5939 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005940 return Incompatible;
5941 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005942 // CK_VectorSplat does T -> vector T, so first cast to the
5943 // element type.
5944 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5945 if (elType != rhsType) {
5946 Kind = PrepareScalarCast(*this, rhs, elType);
5947 ImpCastExprToType(rhs, elType, Kind);
5948 }
5949 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005950 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005951 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005952 }
Mike Stump11289f42009-09-09 15:08:12 +00005953
John McCalle5255932011-01-31 22:28:28 +00005954 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00005955 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005956 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005957 // Allow assignments of an AltiVec vector type to an equivalent GCC
5958 // vector type and vice versa
5959 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5960 Kind = CK_BitCast;
5961 return Compatible;
5962 }
5963
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005964 // If we are allowing lax vector conversions, and LHS and RHS are both
5965 // vectors, the total size only needs to be the same. This is a bitcast;
5966 // no bits are changed but the result type is different.
5967 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00005968 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00005969 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005970 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005971 }
Chris Lattner881a2122008-01-04 23:32:24 +00005972 }
5973 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005974 }
Eli Friedman3360d892008-05-30 18:07:22 +00005975
John McCalle5255932011-01-31 22:28:28 +00005976 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00005977 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00005978 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00005979 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005980 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005981 }
Eli Friedman3360d892008-05-30 18:07:22 +00005982
John McCalle5255932011-01-31 22:28:28 +00005983 // Conversions to normal pointers.
5984 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5985 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00005986 if (isa<PointerType>(rhsType)) {
5987 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00005988 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00005989 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005990
John McCalle5255932011-01-31 22:28:28 +00005991 // int -> T*
5992 if (rhsType->isIntegerType()) {
5993 Kind = CK_IntegralToPointer; // FIXME: null?
5994 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005995 }
John McCalle5255932011-01-31 22:28:28 +00005996
5997 // C pointers are not compatible with ObjC object pointers,
5998 // with two exceptions:
5999 if (isa<ObjCObjectPointerType>(rhsType)) {
6000 // - conversions to void*
6001 if (lhsPointer->getPointeeType()->isVoidType()) {
6002 Kind = CK_AnyPointerToObjCPointerCast;
6003 return Compatible;
6004 }
6005
6006 // - conversions from 'Class' to the redefinition type
6007 if (rhsType->isObjCClassType() &&
6008 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006009 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006010 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006011 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006012
John McCalle5255932011-01-31 22:28:28 +00006013 Kind = CK_BitCast;
6014 return IncompatiblePointer;
6015 }
6016
6017 // U^ -> void*
6018 if (rhsType->getAs<BlockPointerType>()) {
6019 if (lhsPointer->getPointeeType()->isVoidType()) {
6020 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006021 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006022 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006023 }
John McCalle5255932011-01-31 22:28:28 +00006024
Steve Naroff081c7422008-09-04 15:10:53 +00006025 return Incompatible;
6026 }
6027
John McCalle5255932011-01-31 22:28:28 +00006028 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00006029 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006030 // U^ -> T^
6031 if (rhsType->isBlockPointerType()) {
6032 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00006033 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006034 }
6035
6036 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006037 if (rhsType->isIntegerType()) {
6038 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00006039 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006040 }
6041
John McCalle5255932011-01-31 22:28:28 +00006042 // id -> T^
6043 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6044 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006045 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006046 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006047
John McCalle5255932011-01-31 22:28:28 +00006048 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006049 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00006050 if (RHSPT->getPointeeType()->isVoidType()) {
6051 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006052 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006053 }
John McCall8cb679e2010-11-15 09:13:47 +00006054
Chris Lattnera52c2f22008-01-04 23:18:45 +00006055 return Incompatible;
6056 }
6057
John McCalle5255932011-01-31 22:28:28 +00006058 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006059 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006060 // A* -> B*
6061 if (rhsType->isObjCObjectPointerType()) {
6062 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006063 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006064 }
6065
6066 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00006067 if (rhsType->isIntegerType()) {
6068 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00006069 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006070 }
6071
John McCalle5255932011-01-31 22:28:28 +00006072 // In general, C pointers are not compatible with ObjC object pointers,
6073 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00006074 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006075 // - conversions from 'void*'
6076 if (rhsType->isVoidPointerType()) {
6077 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006078 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006079 }
6080
6081 // - conversions to 'Class' from its redefinition type
6082 if (lhsType->isObjCClassType() &&
6083 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6084 Kind = CK_BitCast;
6085 return Compatible;
6086 }
6087
6088 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006089 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006090 }
John McCalle5255932011-01-31 22:28:28 +00006091
6092 // T^ -> A*
6093 if (rhsType->isBlockPointerType()) {
6094 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006095 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006096 }
6097
Steve Naroff7cae42b2009-07-10 23:34:53 +00006098 return Incompatible;
6099 }
John McCalle5255932011-01-31 22:28:28 +00006100
6101 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00006102 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006103 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006104 if (lhsType == Context.BoolTy) {
6105 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00006106 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006107 }
Eli Friedman3360d892008-05-30 18:07:22 +00006108
John McCalle5255932011-01-31 22:28:28 +00006109 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006110 if (lhsType->isIntegerType()) {
6111 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006112 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006113 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006114
Chris Lattnera52c2f22008-01-04 23:18:45 +00006115 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00006116 }
John McCalle5255932011-01-31 22:28:28 +00006117
6118 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006119 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006120 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006121 if (lhsType == Context.BoolTy) {
6122 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006123 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006124 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006125
John McCalle5255932011-01-31 22:28:28 +00006126 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006127 if (lhsType->isIntegerType()) {
6128 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006129 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006130 }
6131
Steve Naroff7cae42b2009-07-10 23:34:53 +00006132 return Incompatible;
6133 }
Eli Friedman3360d892008-05-30 18:07:22 +00006134
John McCalle5255932011-01-31 22:28:28 +00006135 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00006136 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006137 if (Context.typesAreCompatible(lhsType, rhsType)) {
6138 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00006139 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006140 }
Bill Wendling216423b2007-05-30 06:30:29 +00006141 }
John McCalle5255932011-01-31 22:28:28 +00006142
Steve Naroff98cf3e92007-06-06 18:38:38 +00006143 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00006144}
6145
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006146/// \brief Constructs a transparent union from an expression that is
6147/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00006148static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006149 QualType UnionType, FieldDecl *Field) {
6150 // Build an initializer list that designates the appropriate member
6151 // of the transparent union.
Ted Kremenekac034612010-04-13 23:39:13 +00006152 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00006153 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006154 SourceLocation());
6155 Initializer->setType(UnionType);
6156 Initializer->setInitializedFieldInUnion(Field);
6157
6158 // Build a compound literal constructing a value of the transparent
6159 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00006160 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall5d7aa7f2010-01-19 22:33:45 +00006161 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCall7decc9e2010-11-18 06:31:45 +00006162 VK_RValue, Initializer, false);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006163}
6164
6165Sema::AssignConvertType
6166Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
6167 QualType FromType = rExpr->getType();
6168
Mike Stump11289f42009-09-09 15:08:12 +00006169 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006170 // transparent_union GCC extension.
6171 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006172 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006173 return Incompatible;
6174
6175 // The field to initialize within the transparent union.
6176 RecordDecl *UD = UT->getDecl();
6177 FieldDecl *InitField = 0;
6178 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006179 for (RecordDecl::field_iterator it = UD->field_begin(),
6180 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006181 it != itend; ++it) {
6182 if (it->getType()->isPointerType()) {
6183 // If the transparent union contains a pointer type, we allow:
6184 // 1) void pointer
6185 // 2) null pointer constant
6186 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006187 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John McCalle3027922010-08-25 11:45:40 +00006188 ImpCastExprToType(rExpr, it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006189 InitField = *it;
6190 break;
6191 }
Mike Stump11289f42009-09-09 15:08:12 +00006192
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006193 if (rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006194 Expr::NPC_ValueDependentIsNull)) {
John McCalle84af4e2010-11-13 01:35:44 +00006195 ImpCastExprToType(rExpr, it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006196 InitField = *it;
6197 break;
6198 }
6199 }
6200
John McCall29600e12010-11-16 02:32:08 +00006201 Expr *rhs = rExpr;
John McCall8cb679e2010-11-15 09:13:47 +00006202 CastKind Kind = CK_Invalid;
John McCall29600e12010-11-16 02:32:08 +00006203 if (CheckAssignmentConstraints(it->getType(), rhs, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006204 == Compatible) {
John McCall29600e12010-11-16 02:32:08 +00006205 ImpCastExprToType(rhs, it->getType(), Kind);
6206 rExpr = rhs;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006207 InitField = *it;
6208 break;
6209 }
6210 }
6211
6212 if (!InitField)
6213 return Incompatible;
6214
6215 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
6216 return Compatible;
6217}
6218
Chris Lattner9bad62c2008-01-04 18:04:52 +00006219Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006220Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00006221 if (getLangOptions().CPlusPlus) {
6222 if (!lhsType->isRecordType()) {
6223 // C++ 5.17p3: If the left operand is not of class type, the
6224 // expression is implicitly converted (C++ 4) to the
6225 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00006226 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006227 AA_Assigning))
Douglas Gregor9a657932008-10-21 23:43:52 +00006228 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00006229 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00006230 }
6231
6232 // FIXME: Currently, we fall through and treat C++ classes like C
6233 // structures.
John McCall34376a62010-12-04 03:47:34 +00006234 }
Douglas Gregor9a657932008-10-21 23:43:52 +00006235
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006236 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6237 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00006238 if ((lhsType->isPointerType() ||
6239 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00006240 lhsType->isBlockPointerType())
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006241 && rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006242 Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00006243 ImpCastExprToType(rExpr, lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006244 return Compatible;
6245 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006246
Chris Lattnere6dcd502007-10-16 02:55:40 +00006247 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006248 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00006249 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00006250 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00006251 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00006252 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00006253 if (!lhsType->isReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00006254 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006255
John McCall8cb679e2010-11-15 09:13:47 +00006256 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006257 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00006258 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006259
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006260 // C99 6.5.16.1p2: The value of the right operand is converted to the
6261 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00006262 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6263 // so that we can use references in built-in functions even in C.
6264 // The getNonReferenceType() call makes sure that the resulting expression
6265 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006266 if (result != Incompatible && rExpr->getType() != lhsType)
John McCall8cb679e2010-11-15 09:13:47 +00006267 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006268 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006269}
6270
Chris Lattner326f7572008-11-18 01:30:42 +00006271QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006272 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006273 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00006274 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00006275 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00006276}
6277
Chris Lattnerfaa54172010-01-12 21:23:57 +00006278QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00006279 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006280 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00006281 QualType lhsType =
6282 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
6283 QualType rhsType =
6284 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006285
Nate Begeman191a6b12008-07-14 18:02:46 +00006286 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006287 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00006288 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00006289
Nate Begeman191a6b12008-07-14 18:02:46 +00006290 // Handle the case of a vector & extvector type of the same size and element
6291 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006292 if (getLangOptions().LaxVectorConversions) {
John McCall9dd450b2009-09-21 23:43:11 +00006293 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006294 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006295 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006296 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006297 if (lhsType->isExtVectorType()) {
John McCalle3027922010-08-25 11:45:40 +00006298 ImpCastExprToType(rex, lhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006299 return lhsType;
6300 }
6301
John McCalle3027922010-08-25 11:45:40 +00006302 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006303 return rhsType;
Eric Christophera613f562010-08-26 00:42:16 +00006304 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6305 // If we are allowing lax vector conversions, and LHS and RHS are both
6306 // vectors, the total size only needs to be the same. This is a
6307 // bitcast; no bits are changed but the result type is different.
6308 ImpCastExprToType(rex, lhsType, CK_BitCast);
6309 return lhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006310 }
Eric Christophera613f562010-08-26 00:42:16 +00006311 }
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006312 }
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006313 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006314
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006315 // Handle the case of equivalent AltiVec and GCC vector types
6316 if (lhsType->isVectorType() && rhsType->isVectorType() &&
6317 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John McCalle3027922010-08-25 11:45:40 +00006318 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006319 return rhsType;
6320 }
6321
Nate Begemanbd956c42009-06-28 02:36:38 +00006322 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6323 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6324 bool swapped = false;
6325 if (rhsType->isExtVectorType()) {
6326 swapped = true;
6327 std::swap(rex, lex);
6328 std::swap(rhsType, lhsType);
6329 }
Mike Stump11289f42009-09-09 15:08:12 +00006330
Nate Begeman886448d2009-06-28 19:12:57 +00006331 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00006332 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006333 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00006334 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00006335 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6336 if (order > 0)
6337 ImpCastExprToType(rex, EltTy, CK_IntegralCast);
6338 if (order >= 0) {
6339 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006340 if (swapped) std::swap(rex, lex);
6341 return lhsType;
6342 }
6343 }
6344 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6345 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00006346 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6347 if (order > 0)
6348 ImpCastExprToType(rex, EltTy, CK_FloatingCast);
6349 if (order >= 0) {
6350 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006351 if (swapped) std::swap(rex, lex);
6352 return lhsType;
6353 }
Nate Begeman330aaa72007-12-30 02:59:45 +00006354 }
6355 }
Mike Stump11289f42009-09-09 15:08:12 +00006356
Nate Begeman886448d2009-06-28 19:12:57 +00006357 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00006358 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006359 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00006360 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00006361 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00006362}
6363
Chris Lattnerfaa54172010-01-12 21:23:57 +00006364QualType Sema::CheckMultiplyDivideOperands(
6365 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00006366 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006367 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006368
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006369 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006370
Chris Lattnerfaa54172010-01-12 21:23:57 +00006371 if (!lex->getType()->isArithmeticType() ||
6372 !rex->getType()->isArithmeticType())
6373 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006374
Chris Lattnerfaa54172010-01-12 21:23:57 +00006375 // Check for division by zero.
6376 if (isDiv &&
6377 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Ted Kremenek55ae3192011-02-23 01:51:43 +00006378 DiagRuntimeBehavior(Loc, rex, PDiag(diag::warn_division_by_zero)
6379 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006380
Chris Lattnerfaa54172010-01-12 21:23:57 +00006381 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006382}
6383
Chris Lattnerfaa54172010-01-12 21:23:57 +00006384QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00006385 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006386 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006387 if (lex->getType()->hasIntegerRepresentation() &&
6388 rex->getType()->hasIntegerRepresentation())
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006389 return CheckVectorOperands(Loc, lex, rex);
6390 return InvalidOperands(Loc, lex, rex);
6391 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006392
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006393 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006394
Chris Lattnerfaa54172010-01-12 21:23:57 +00006395 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
6396 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006397
Chris Lattnerfaa54172010-01-12 21:23:57 +00006398 // Check for remainder by zero.
6399 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Ted Kremenek55ae3192011-02-23 01:51:43 +00006400 DiagRuntimeBehavior(Loc, rex, PDiag(diag::warn_remainder_by_zero)
6401 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006402
Chris Lattnerfaa54172010-01-12 21:23:57 +00006403 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006404}
6405
Chris Lattnerfaa54172010-01-12 21:23:57 +00006406QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00006407 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006408 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6409 QualType compType = CheckVectorOperands(Loc, lex, rex);
6410 if (CompLHSTy) *CompLHSTy = compType;
6411 return compType;
6412 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006413
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006414 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006415
Steve Naroffe4718892007-04-27 18:30:00 +00006416 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006417 if (lex->getType()->isArithmeticType() &&
6418 rex->getType()->isArithmeticType()) {
6419 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006420 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006421 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006422
Eli Friedman8e122982008-05-18 18:08:51 +00006423 // Put any potential pointer into PExp
6424 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00006425 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006426 std::swap(PExp, IExp);
6427
Steve Naroff6b712a72009-07-14 18:25:06 +00006428 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006429
Eli Friedman8e122982008-05-18 18:08:51 +00006430 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006431 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006432
Chris Lattner12bdebb2009-04-24 23:50:08 +00006433 // Check for arithmetic on pointers to incomplete types.
6434 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006435 if (getLangOptions().CPlusPlus) {
6436 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00006437 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00006438 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006439 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006440
6441 // GNU extension: arithmetic on pointer to void
6442 Diag(Loc, diag::ext_gnu_void_ptr)
6443 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00006444 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006445 if (getLangOptions().CPlusPlus) {
6446 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6447 << lex->getType() << lex->getSourceRange();
6448 return QualType();
6449 }
6450
6451 // GNU extension: arithmetic on pointer to function
6452 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6453 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00006454 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006455 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00006456 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00006457 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006458 PExp->getType()->isObjCObjectPointerType()) &&
6459 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00006460 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6461 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006462 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006463 return QualType();
6464 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00006465 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006466 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006467 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6468 << PointeeTy << PExp->getSourceRange();
6469 return QualType();
6470 }
Mike Stump11289f42009-09-09 15:08:12 +00006471
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006472 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00006473 QualType LHSTy = Context.isPromotableBitField(lex);
6474 if (LHSTy.isNull()) {
6475 LHSTy = lex->getType();
6476 if (LHSTy->isPromotableIntegerType())
6477 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00006478 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006479 *CompLHSTy = LHSTy;
6480 }
Eli Friedman8e122982008-05-18 18:08:51 +00006481 return PExp->getType();
6482 }
6483 }
6484
Chris Lattner326f7572008-11-18 01:30:42 +00006485 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006486}
6487
Chris Lattner2a3569b2008-04-07 05:30:13 +00006488// C99 6.5.6
6489QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006490 SourceLocation Loc, QualType* CompLHSTy) {
6491 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6492 QualType compType = CheckVectorOperands(Loc, lex, rex);
6493 if (CompLHSTy) *CompLHSTy = compType;
6494 return compType;
6495 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006496
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006497 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006498
Chris Lattner4d62f422007-12-09 21:53:25 +00006499 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006500
Chris Lattner4d62f422007-12-09 21:53:25 +00006501 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00006502 if (lex->getType()->isArithmeticType()
6503 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006504 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006505 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006506 }
Mike Stump11289f42009-09-09 15:08:12 +00006507
Chris Lattner4d62f422007-12-09 21:53:25 +00006508 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00006509 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00006510 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006511
Douglas Gregorac1fb652009-03-24 19:52:54 +00006512 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006513
Douglas Gregorac1fb652009-03-24 19:52:54 +00006514 bool ComplainAboutVoid = false;
6515 Expr *ComplainAboutFunc = 0;
6516 if (lpointee->isVoidType()) {
6517 if (getLangOptions().CPlusPlus) {
6518 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6519 << lex->getSourceRange() << rex->getSourceRange();
6520 return QualType();
6521 }
6522
6523 // GNU C extension: arithmetic on pointer to void
6524 ComplainAboutVoid = true;
6525 } else if (lpointee->isFunctionType()) {
6526 if (getLangOptions().CPlusPlus) {
6527 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006528 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006529 return QualType();
6530 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006531
6532 // GNU C extension: arithmetic on pointer to function
6533 ComplainAboutFunc = lex;
6534 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00006535 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006536 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00006537 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006538 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006539 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006540
Chris Lattner12bdebb2009-04-24 23:50:08 +00006541 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006542 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006543 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6544 << lpointee << lex->getSourceRange();
6545 return QualType();
6546 }
Mike Stump11289f42009-09-09 15:08:12 +00006547
Chris Lattner4d62f422007-12-09 21:53:25 +00006548 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00006549 if (rex->getType()->isIntegerType()) {
6550 if (ComplainAboutVoid)
6551 Diag(Loc, diag::ext_gnu_void_ptr)
6552 << lex->getSourceRange() << rex->getSourceRange();
6553 if (ComplainAboutFunc)
6554 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006555 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006556 << ComplainAboutFunc->getSourceRange();
6557
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006558 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006559 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006560 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006561
Chris Lattner4d62f422007-12-09 21:53:25 +00006562 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006563 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006564 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006565
Douglas Gregorac1fb652009-03-24 19:52:54 +00006566 // RHS must be a completely-type object type.
6567 // Handle the GNU void* extension.
6568 if (rpointee->isVoidType()) {
6569 if (getLangOptions().CPlusPlus) {
6570 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6571 << lex->getSourceRange() << rex->getSourceRange();
6572 return QualType();
6573 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006574
Douglas Gregorac1fb652009-03-24 19:52:54 +00006575 ComplainAboutVoid = true;
6576 } else if (rpointee->isFunctionType()) {
6577 if (getLangOptions().CPlusPlus) {
6578 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006579 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006580 return QualType();
6581 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006582
6583 // GNU extension: arithmetic on pointer to function
6584 if (!ComplainAboutFunc)
6585 ComplainAboutFunc = rex;
6586 } else if (!rpointee->isDependentType() &&
6587 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006588 PDiag(diag::err_typecheck_sub_ptr_object)
6589 << rex->getSourceRange()
6590 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006591 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006592
Eli Friedman168fe152009-05-16 13:54:38 +00006593 if (getLangOptions().CPlusPlus) {
6594 // Pointee types must be the same: C++ [expr.add]
6595 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6596 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6597 << lex->getType() << rex->getType()
6598 << lex->getSourceRange() << rex->getSourceRange();
6599 return QualType();
6600 }
6601 } else {
6602 // Pointee types must be compatible C99 6.5.6p3
6603 if (!Context.typesAreCompatible(
6604 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6605 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6606 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6607 << lex->getType() << rex->getType()
6608 << lex->getSourceRange() << rex->getSourceRange();
6609 return QualType();
6610 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006611 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006612
Douglas Gregorac1fb652009-03-24 19:52:54 +00006613 if (ComplainAboutVoid)
6614 Diag(Loc, diag::ext_gnu_void_ptr)
6615 << lex->getSourceRange() << rex->getSourceRange();
6616 if (ComplainAboutFunc)
6617 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006618 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006619 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006620
6621 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006622 return Context.getPointerDiffType();
6623 }
6624 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006625
Chris Lattner326f7572008-11-18 01:30:42 +00006626 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006627}
6628
Douglas Gregor0bf31402010-10-08 23:50:27 +00006629static bool isScopedEnumerationType(QualType T) {
6630 if (const EnumType *ET = dyn_cast<EnumType>(T))
6631 return ET->getDecl()->isScoped();
6632 return false;
6633}
6634
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006635static void DiagnoseBadShiftValues(Sema& S, Expr *&lex, Expr *&rex,
6636 SourceLocation Loc, unsigned Opc,
6637 QualType LHSTy) {
6638 llvm::APSInt Right;
6639 // Check right/shifter operand
6640 if (rex->isValueDependent() || !rex->isIntegerConstantExpr(Right, S.Context))
6641 return;
6642
6643 if (Right.isNegative()) {
6644 S.Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
6645 return;
6646 }
6647 llvm::APInt LeftBits(Right.getBitWidth(),
6648 S.Context.getTypeSize(lex->getType()));
6649 if (Right.uge(LeftBits)) {
6650 S.Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
6651 return;
6652 }
6653 if (Opc != BO_Shl)
6654 return;
6655
6656 // When left shifting an ICE which is signed, we can check for overflow which
6657 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6658 // integers have defined behavior modulo one more than the maximum value
6659 // representable in the result type, so never warn for those.
6660 llvm::APSInt Left;
Chandler Carruth60ed89d2011-02-24 00:03:53 +00006661 if (lex->isValueDependent() || !lex->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006662 LHSTy->hasUnsignedIntegerRepresentation())
6663 return;
6664 llvm::APInt ResultBits =
6665 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6666 if (LeftBits.uge(ResultBits))
6667 return;
6668 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6669 Result = Result.shl(Right);
6670
6671 // If we are only missing a sign bit, this is less likely to result in actual
6672 // bugs -- if the result is cast back to an unsigned type, it will have the
6673 // expected value. Thus we place this behind a different warning that can be
6674 // turned off separately if needed.
6675 if (LeftBits == ResultBits - 1) {
6676 S.Diag(Loc, diag::warn_shift_result_overrides_sign_bit)
6677 << Result.toString(10) << LHSTy
6678 << lex->getSourceRange() << rex->getSourceRange();
6679 return;
6680 }
6681
6682 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
6683 << Result.toString(10) << Result.getMinSignedBits() << LHSTy
6684 << Left.getBitWidth() << lex->getSourceRange() << rex->getSourceRange();
6685}
6686
Chris Lattner2a3569b2008-04-07 05:30:13 +00006687// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00006688QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006689 unsigned Opc, bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00006690 // C99 6.5.7p2: Each of the operands shall have integer type.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006691 if (!lex->getType()->hasIntegerRepresentation() ||
6692 !rex->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006693 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006694
Douglas Gregor0bf31402010-10-08 23:50:27 +00006695 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6696 // hasIntegerRepresentation() above instead of this.
6697 if (isScopedEnumerationType(lex->getType()) ||
6698 isScopedEnumerationType(rex->getType())) {
6699 return InvalidOperands(Loc, lex, rex);
6700 }
6701
Nate Begemane46ee9a2009-10-25 02:26:48 +00006702 // Vector shifts promote their scalar inputs to vector type.
6703 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6704 return CheckVectorOperands(Loc, lex, rex);
6705
Chris Lattner5c11c412007-12-12 05:47:28 +00006706 // Shifts don't perform usual arithmetic conversions, they just do integer
6707 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006708
John McCall57cdd882010-12-16 19:28:59 +00006709 // For the LHS, do usual unary conversions, but then reset them away
6710 // if this is a compound assignment.
6711 Expr *old_lex = lex;
6712 UsualUnaryConversions(lex);
6713 QualType LHSTy = lex->getType();
6714 if (isCompAssign) lex = old_lex;
6715
6716 // The RHS is simpler.
Chris Lattner5c11c412007-12-12 05:47:28 +00006717 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006718
Ryan Flynnf53fab82009-08-07 16:20:20 +00006719 // Sanity-check shift operands
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006720 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006721
Chris Lattner5c11c412007-12-12 05:47:28 +00006722 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006723 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006724}
6725
Chandler Carruth17773fc2010-07-10 12:30:03 +00006726static bool IsWithinTemplateSpecialization(Decl *D) {
6727 if (DeclContext *DC = D->getDeclContext()) {
6728 if (isa<ClassTemplateSpecializationDecl>(DC))
6729 return true;
6730 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6731 return FD->isFunctionTemplateSpecialization();
6732 }
6733 return false;
6734}
6735
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006736// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00006737QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006738 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00006739 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006740
Chris Lattner9a152e22009-12-05 05:40:13 +00006741 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00006742 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006743 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006744
Steve Naroff31090012007-07-16 21:54:35 +00006745 QualType lType = lex->getType();
6746 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006747
Chandler Carruth712563b2011-02-17 08:37:06 +00006748 Expr *LHSStripped = lex->IgnoreParenImpCasts();
6749 Expr *RHSStripped = rex->IgnoreParenImpCasts();
6750 QualType LHSStrippedType = LHSStripped->getType();
6751 QualType RHSStrippedType = RHSStripped->getType();
6752
6753 // Two different enums will raise a warning when compared.
6754 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
6755 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
6756 if (LHSEnumType->getDecl()->getIdentifier() &&
6757 RHSEnumType->getDecl()->getIdentifier() &&
6758 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
6759 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6760 << LHSStrippedType << RHSStrippedType
6761 << lex->getSourceRange() << rex->getSourceRange();
6762 }
6763 }
6764 }
6765
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006766 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00006767 !(lType->isBlockPointerType() && isRelational) &&
6768 !lex->getLocStart().isMacroID() &&
6769 !rex->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006770 // For non-floating point types, check for self-comparisons of the form
6771 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6772 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006773 //
6774 // NOTE: Don't warn about comparison expressions resulting from macro
6775 // expansion. Also don't warn about comparisons which are only self
6776 // comparisons within a template specialization. The warnings should catch
6777 // obvious cases in the definition of the template anyways. The idea is to
6778 // warn when the typed comparison operator will always evaluate to the same
6779 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006780 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006781 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006782 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006783 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006784 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006785 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006786 << (Opc == BO_EQ
6787 || Opc == BO_LE
6788 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00006789 } else if (lType->isArrayType() && rType->isArrayType() &&
6790 !DRL->getDecl()->getType()->isReferenceType() &&
6791 !DRR->getDecl()->getType()->isReferenceType()) {
6792 // what is it always going to eval to?
6793 char always_evals_to;
6794 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006795 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006796 always_evals_to = 0; // false
6797 break;
John McCalle3027922010-08-25 11:45:40 +00006798 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006799 always_evals_to = 1; // true
6800 break;
6801 default:
6802 // best we can say is 'a constant'
6803 always_evals_to = 2; // e.g. array1 <= array2
6804 break;
6805 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006806 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006807 << 1 // array
6808 << always_evals_to);
6809 }
6810 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006811 }
Mike Stump11289f42009-09-09 15:08:12 +00006812
Chris Lattner222b8bd2009-03-08 19:39:53 +00006813 if (isa<CastExpr>(LHSStripped))
6814 LHSStripped = LHSStripped->IgnoreParenCasts();
6815 if (isa<CastExpr>(RHSStripped))
6816 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006817
Chris Lattner222b8bd2009-03-08 19:39:53 +00006818 // Warn about comparisons against a string constant (unless the other
6819 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006820 Expr *literalString = 0;
6821 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006822 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006823 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006824 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006825 literalString = lex;
6826 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006827 } else if ((isa<StringLiteral>(RHSStripped) ||
6828 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006829 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006830 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006831 literalString = rex;
6832 literalStringStripped = RHSStripped;
6833 }
6834
6835 if (literalString) {
6836 std::string resultComparison;
6837 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006838 case BO_LT: resultComparison = ") < 0"; break;
6839 case BO_GT: resultComparison = ") > 0"; break;
6840 case BO_LE: resultComparison = ") <= 0"; break;
6841 case BO_GE: resultComparison = ") >= 0"; break;
6842 case BO_EQ: resultComparison = ") == 0"; break;
6843 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006844 default: assert(false && "Invalid comparison operator");
6845 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006846
Ted Kremenek3427fac2011-02-23 01:52:04 +00006847 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006848 PDiag(diag::warn_stringcompare)
6849 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006850 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006851 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006852 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006853
Douglas Gregorec170db2010-06-08 19:50:34 +00006854 // C99 6.5.8p3 / C99 6.5.9p4
6855 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
6856 UsualArithmeticConversions(lex, rex);
6857 else {
6858 UsualUnaryConversions(lex);
6859 UsualUnaryConversions(rex);
6860 }
6861
6862 lType = lex->getType();
6863 rType = rex->getType();
6864
Douglas Gregorca63811b2008-11-19 03:25:36 +00006865 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006866 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006867
Chris Lattnerb620c342007-08-26 01:18:55 +00006868 if (isRelational) {
6869 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006870 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006871 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006872 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006873 if (lType->hasFloatingRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006874 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006875
Chris Lattnerb620c342007-08-26 01:18:55 +00006876 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006877 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006878 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006879
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006880 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006881 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006882 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006883 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006884
Douglas Gregorf267edd2010-06-15 21:38:40 +00006885 // All of the following pointer-related warnings are GCC extensions, except
6886 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00006887 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006888 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006889 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00006890 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006891 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006892
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006893 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006894 if (LCanPointeeTy == RCanPointeeTy)
6895 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006896 if (!isRelational &&
6897 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6898 // Valid unless comparison between non-null pointer and function pointer
6899 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006900 // In a SFINAE context, we treat this as a hard error to maintain
6901 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006902 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6903 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00006904 Diag(Loc,
6905 isSFINAEContext()?
6906 diag::err_typecheck_comparison_of_fptr_to_void
6907 : diag::ext_typecheck_comparison_of_fptr_to_void)
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006908 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006909
6910 if (isSFINAEContext())
6911 return QualType();
6912
John McCalle3027922010-08-25 11:45:40 +00006913 ImpCastExprToType(rex, lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006914 return ResultTy;
6915 }
6916 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006917
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006918 // C++ [expr.rel]p2:
6919 // [...] Pointer conversions (4.10) and qualification
6920 // conversions (4.4) are performed on pointer operands (or on
6921 // a pointer operand and a null pointer constant) to bring
6922 // them to their composite pointer type. [...]
6923 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006924 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006925 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006926 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006927 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006928 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006929 if (T.isNull()) {
6930 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6931 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6932 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006933 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006934 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006935 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006936 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006937 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006938 }
6939
John McCalle3027922010-08-25 11:45:40 +00006940 ImpCastExprToType(lex, T, CK_BitCast);
6941 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006942 return ResultTy;
6943 }
Eli Friedman16c209612009-08-23 00:27:47 +00006944 // C99 6.5.9p2 and C99 6.5.8p2
6945 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6946 RCanPointeeTy.getUnqualifiedType())) {
6947 // Valid unless a relational comparison of function pointers
6948 if (isRelational && LCanPointeeTy->isFunctionType()) {
6949 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
6950 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6951 }
6952 } else if (!isRelational &&
6953 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6954 // Valid unless comparison between non-null pointer and function pointer
6955 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6956 && !LHSIsNull && !RHSIsNull) {
6957 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
6958 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6959 }
6960 } else {
6961 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00006962 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006963 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00006964 }
Eli Friedman16c209612009-08-23 00:27:47 +00006965 if (LCanPointeeTy != RCanPointeeTy)
John McCalle3027922010-08-25 11:45:40 +00006966 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006967 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006968 }
Mike Stump11289f42009-09-09 15:08:12 +00006969
Sebastian Redl576fd422009-05-10 18:38:11 +00006970 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006971 // Comparison of nullptr_t with itself.
6972 if (lType->isNullPtrType() && rType->isNullPtrType())
6973 return ResultTy;
6974
Mike Stump11289f42009-09-09 15:08:12 +00006975 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006976 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006977 if (RHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00006978 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006979 (!isRelational && lType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00006980 ImpCastExprToType(rex, lType,
6981 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006982 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006983 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006984 return ResultTy;
6985 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006986 if (LHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00006987 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006988 (!isRelational && rType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00006989 ImpCastExprToType(lex, rType,
6990 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006991 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006992 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006993 return ResultTy;
6994 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006995
6996 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00006997 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006998 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6999 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00007000 // In addition, pointers to members can be compared, or a pointer to
7001 // member and a null pointer constant. Pointer to member conversions
7002 // (4.11) and qualification conversions (4.4) are performed to bring
7003 // them to a common type. If one operand is a null pointer constant,
7004 // the common type is the type of the other operand. Otherwise, the
7005 // common type is a pointer to member type similar (4.4) to the type
7006 // of one of the operands, with a cv-qualification signature (4.4)
7007 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007008 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007009 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00007010 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007011 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007012 if (T.isNull()) {
7013 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007014 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007015 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007016 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007017 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007018 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007019 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007020 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007021 }
Mike Stump11289f42009-09-09 15:08:12 +00007022
John McCalle3027922010-08-25 11:45:40 +00007023 ImpCastExprToType(lex, T, CK_BitCast);
7024 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007025 return ResultTy;
7026 }
Sebastian Redl576fd422009-05-10 18:38:11 +00007027 }
Mike Stump11289f42009-09-09 15:08:12 +00007028
Steve Naroff081c7422008-09-04 15:10:53 +00007029 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00007030 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007031 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
7032 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007033
Steve Naroff081c7422008-09-04 15:10:53 +00007034 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00007035 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007036 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007037 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00007038 }
John McCalle3027922010-08-25 11:45:40 +00007039 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007040 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00007041 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00007042 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00007043 if (!isRelational
7044 && ((lType->isBlockPointerType() && rType->isPointerType())
7045 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00007046 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007047 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007048 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007049 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007050 ->getPointeeType()->isVoidType())))
7051 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7052 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00007053 }
John McCalle3027922010-08-25 11:45:40 +00007054 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007055 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00007056 }
Steve Naroff081c7422008-09-04 15:10:53 +00007057
Steve Naroff7cae42b2009-07-10 23:34:53 +00007058 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007059 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007060 const PointerType *LPT = lType->getAs<PointerType>();
7061 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007062 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00007063 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007064 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00007065 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007066
Steve Naroff753567f2008-11-17 19:49:16 +00007067 if (!LPtrToVoid && !RPtrToVoid &&
7068 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007069 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007070 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007071 }
John McCalle3027922010-08-25 11:45:40 +00007072 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007073 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00007074 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007075 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007076 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007077 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
7078 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007079 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007080 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00007081 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00007082 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007083 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7084 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00007085 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007086 bool isError = false;
7087 if ((LHSIsNull && lType->isIntegerType()) ||
7088 (RHSIsNull && rType->isIntegerType())) {
7089 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007090 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007091 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007092 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007093 else if (getLangOptions().CPlusPlus) {
7094 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7095 isError = true;
7096 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00007097 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00007098
Chris Lattnerd99bd522009-08-23 00:03:44 +00007099 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007100 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00007101 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007102 if (isError)
7103 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00007104 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007105
7106 if (lType->isIntegerType())
John McCalle84af4e2010-11-13 01:35:44 +00007107 ImpCastExprToType(lex, rType,
7108 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00007109 else
John McCalle84af4e2010-11-13 01:35:44 +00007110 ImpCastExprToType(rex, lType,
7111 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007112 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00007113 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007114
Steve Naroff4b191572008-09-04 16:56:14 +00007115 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00007116 if (!isRelational && RHSIsNull
7117 && lType->isBlockPointerType() && rType->isIntegerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00007118 ImpCastExprToType(rex, lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007119 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007120 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00007121 if (!isRelational && LHSIsNull
7122 && lType->isIntegerType() && rType->isBlockPointerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00007123 ImpCastExprToType(lex, rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007124 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007125 }
Chris Lattner326f7572008-11-18 01:30:42 +00007126 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007127}
7128
Nate Begeman191a6b12008-07-14 18:02:46 +00007129/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00007130/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00007131/// like a scalar comparison, a vector comparison produces a vector of integer
7132/// types.
7133QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00007134 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00007135 bool isRelational) {
7136 // Check to make sure we're operating on vectors of the same type and width,
7137 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00007138 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00007139 if (vType.isNull())
7140 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007141
Anton Yartsev3f8f2882010-11-18 03:19:30 +00007142 // If AltiVec, the comparison results in a numeric type, i.e.
7143 // bool for C++, int for C
7144 if (getLangOptions().AltiVec)
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007145 return Context.getLogicalOperationType();
Anton Yartsev3f8f2882010-11-18 03:19:30 +00007146
Nate Begeman191a6b12008-07-14 18:02:46 +00007147 QualType lType = lex->getType();
7148 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007149
Nate Begeman191a6b12008-07-14 18:02:46 +00007150 // For non-floating point types, check for self-comparisons of the form
7151 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7152 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007153 if (!lType->hasFloatingRepresentation()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00007154 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
7155 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
7156 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007157 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007158 PDiag(diag::warn_comparison_always)
7159 << 0 // self-
7160 << 2 // "a constant"
7161 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007162 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007163
Nate Begeman191a6b12008-07-14 18:02:46 +00007164 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007165 if (!isRelational && lType->hasFloatingRepresentation()) {
7166 assert (rType->hasFloatingRepresentation());
Chris Lattner326f7572008-11-18 01:30:42 +00007167 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00007168 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007169
Nate Begeman191a6b12008-07-14 18:02:46 +00007170 // Return the type for the comparison, which is the same as vector type for
7171 // integer vectors, or an integer type of identical size and number of
7172 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007173 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00007174 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007175
John McCall9dd450b2009-09-21 23:43:11 +00007176 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00007177 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007178 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00007179 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00007180 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007181 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7182
Mike Stump4e1f26a2009-02-19 03:04:26 +00007183 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007184 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00007185 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7186}
7187
Steve Naroff218bc2b2007-05-04 21:54:46 +00007188inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00007189 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007190 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
7191 if (lex->getType()->hasIntegerRepresentation() &&
7192 rex->getType()->hasIntegerRepresentation())
7193 return CheckVectorOperands(Loc, lex, rex);
7194
7195 return InvalidOperands(Loc, lex, rex);
7196 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007197
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007198 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007199
Douglas Gregor0bf31402010-10-08 23:50:27 +00007200 if (lex->getType()->isIntegralOrUnscopedEnumerationType() &&
7201 rex->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007202 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00007203 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007204}
7205
Steve Naroff218bc2b2007-05-04 21:54:46 +00007206inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner8406c512010-07-13 19:41:32 +00007207 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
7208
7209 // Diagnose cases where the user write a logical and/or but probably meant a
7210 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7211 // is a constant.
7212 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
Eli Friedman6b197e02010-07-27 19:14:53 +00007213 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
Chris Lattnerdeee7a32010-07-15 00:26:43 +00007214 // Don't warn in macros.
Chris Lattner938533d2010-07-24 01:10:11 +00007215 !Loc.isMacroID()) {
7216 // If the RHS can be constant folded, and if it constant folds to something
7217 // that isn't 0 or 1 (which indicate a potential logical operation that
7218 // happened to fold to true/false) then warn.
7219 Expr::EvalResult Result;
7220 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
7221 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
7222 Diag(Loc, diag::warn_logical_instead_of_bitwise)
7223 << rex->getSourceRange()
John McCalle3027922010-08-25 11:45:40 +00007224 << (Opc == BO_LAnd ? "&&" : "||")
7225 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00007226 }
7227 }
Chris Lattner8406c512010-07-13 19:41:32 +00007228
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007229 if (!Context.getLangOptions().CPlusPlus) {
7230 UsualUnaryConversions(lex);
7231 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007232
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007233 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
7234 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007235
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007236 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007237 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007238
John McCall4a2429a2010-06-04 00:29:51 +00007239 // The following is safe because we only use this method for
7240 // non-overloadable operands.
7241
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007242 // C++ [expr.log.and]p1
7243 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007244 // The operands are both contextually converted to type bool.
7245 if (PerformContextuallyConvertToBool(lex) ||
7246 PerformContextuallyConvertToBool(rex))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007247 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007248
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007249 // C++ [expr.log.and]p2
7250 // C++ [expr.log.or]p2
7251 // The result is a bool.
7252 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007253}
7254
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007255/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7256/// is a read-only property; return true if so. A readonly property expression
7257/// depends on various declarations and thus must be treated specially.
7258///
Mike Stump11289f42009-09-09 15:08:12 +00007259static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007260 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7261 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00007262 if (PropExpr->isImplicitProperty()) return false;
7263
7264 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7265 QualType BaseType = PropExpr->isSuperReceiver() ?
7266 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007267 PropExpr->getBase()->getType();
7268
John McCallb7bd14f2010-12-02 01:19:52 +00007269 if (const ObjCObjectPointerType *OPT =
7270 BaseType->getAsObjCInterfacePointerType())
7271 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7272 if (S.isPropertyReadonly(PDecl, IFace))
7273 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007274 }
7275 return false;
7276}
7277
Chris Lattner30bd3272008-11-18 01:22:49 +00007278/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7279/// emit an error and return true. If so, return false.
7280static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007281 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007282 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007283 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007284 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7285 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00007286 if (IsLV == Expr::MLV_Valid)
7287 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007288
Chris Lattner30bd3272008-11-18 01:22:49 +00007289 unsigned Diag = 0;
7290 bool NeedType = false;
7291 switch (IsLV) { // C99 6.5.16p2
Chris Lattner30bd3272008-11-18 01:22:49 +00007292 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007293 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007294 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7295 NeedType = true;
7296 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007297 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007298 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7299 NeedType = true;
7300 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007301 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007302 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7303 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007304 case Expr::MLV_Valid:
7305 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007306 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007307 case Expr::MLV_MemberFunction:
7308 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007309 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7310 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007311 case Expr::MLV_IncompleteType:
7312 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007313 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007314 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00007315 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00007316 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007317 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7318 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00007319 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00007320 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7321 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007322 case Expr::MLV_ReadonlyProperty:
7323 Diag = diag::error_readonly_property_assignment;
7324 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007325 case Expr::MLV_NoSetterProperty:
7326 Diag = diag::error_nosetter_property_assignment;
7327 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007328 case Expr::MLV_SubObjCPropertySetting:
7329 Diag = diag::error_no_subobject_property_setting;
7330 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007331 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007332
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007333 SourceRange Assign;
7334 if (Loc != OrigLoc)
7335 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007336 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007337 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007338 else
Mike Stump11289f42009-09-09 15:08:12 +00007339 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007340 return true;
7341}
7342
7343
7344
7345// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00007346QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
7347 SourceLocation Loc,
7348 QualType CompoundType) {
7349 // Verify that LHS is a modifiable lvalue, and emit error if not.
7350 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007351 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007352
7353 QualType LHSType = LHS->getType();
7354 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007355 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007356 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007357 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007358 // Simple assignment "x = y".
John McCall34376a62010-12-04 03:47:34 +00007359 if (LHS->getObjectKind() == OK_ObjCProperty)
7360 ConvertPropertyForLValue(LHS, RHS, LHSTy);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007361 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007362 // Special case of NSObject attributes on c-style pointer types.
7363 if (ConvTy == IncompatiblePointer &&
7364 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007365 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007366 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007367 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007368 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007369
John McCall7decc9e2010-11-18 06:31:45 +00007370 if (ConvTy == Compatible &&
7371 getLangOptions().ObjCNonFragileABI &&
7372 LHSType->isObjCObjectType())
7373 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7374 << LHSType;
7375
Chris Lattnerea714382008-08-21 18:04:13 +00007376 // If the RHS is a unary plus or minus, check to see if they = and + are
7377 // right next to each other. If so, the user may have typo'd "x =+ 4"
7378 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00007379 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00007380 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7381 RHSCheck = ICE->getSubExpr();
7382 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007383 if ((UO->getOpcode() == UO_Plus ||
7384 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007385 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007386 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00007387 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7388 // And there is a space or other character before the subexpr of the
7389 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00007390 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7391 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007392 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007393 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007394 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007395 }
Chris Lattnerea714382008-08-21 18:04:13 +00007396 }
7397 } else {
7398 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007399 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007400 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007401
Chris Lattner326f7572008-11-18 01:30:42 +00007402 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007403 RHS, AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007404 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007405
Chris Lattner39561062010-07-07 06:14:23 +00007406
7407 // Check to see if the destination operand is a dereferenced null pointer. If
7408 // so, and if not volatile-qualified, this is undefined behavior that the
7409 // optimizer will delete, so warn about it. People sometimes try to use this
7410 // to get a deterministic trap and are surprised by clang's behavior. This
7411 // only handles the pattern "*null = whatever", which is a very syntactic
7412 // check.
7413 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
John McCalle3027922010-08-25 11:45:40 +00007414 if (UO->getOpcode() == UO_Deref &&
Chris Lattner39561062010-07-07 06:14:23 +00007415 UO->getSubExpr()->IgnoreParenCasts()->
7416 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
7417 !UO->getType().isVolatileQualified()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00007418 DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7419 PDiag(diag::warn_indirection_through_null)
7420 << UO->getSubExpr()->getSourceRange());
7421 DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7422 PDiag(diag::note_indirection_through_null));
Chris Lattner39561062010-07-07 06:14:23 +00007423 }
7424
Ted Kremenek64699be2011-02-16 01:57:07 +00007425 // Check for trivial buffer overflows.
7426 if (const ArraySubscriptExpr *ae
7427 = dyn_cast<ArraySubscriptExpr>(LHS->IgnoreParenCasts()))
7428 CheckArrayAccess(ae);
7429
Steve Naroff98cf3e92007-06-06 18:38:38 +00007430 // C99 6.5.16p3: The type of an assignment expression is the type of the
7431 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007432 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007433 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7434 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007435 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007436 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007437 return (getLangOptions().CPlusPlus
7438 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007439}
7440
Chris Lattner326f7572008-11-18 01:30:42 +00007441// C99 6.5.17
John McCall34376a62010-12-04 03:47:34 +00007442static QualType CheckCommaOperands(Sema &S, Expr *&LHS, Expr *&RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007443 SourceLocation Loc) {
7444 S.DiagnoseUnusedExprResult(LHS);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007445
John McCall4bc41ae2010-11-18 19:01:18 +00007446 ExprResult LHSResult = S.CheckPlaceholderExpr(LHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007447 if (LHSResult.isInvalid())
7448 return QualType();
7449
John McCall4bc41ae2010-11-18 19:01:18 +00007450 ExprResult RHSResult = S.CheckPlaceholderExpr(RHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007451 if (RHSResult.isInvalid())
7452 return QualType();
7453 RHS = RHSResult.take();
7454
John McCall73d36182010-10-12 07:14:40 +00007455 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7456 // operands, but not unary promotions.
7457 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007458
John McCall34376a62010-12-04 03:47:34 +00007459 // So we treat the LHS as a ignored value, and in C++ we allow the
7460 // containing site to determine what should be done with the RHS.
7461 S.IgnoredValueConversions(LHS);
7462
7463 if (!S.getLangOptions().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007464 S.DefaultFunctionArrayLvalueConversion(RHS);
John McCall73d36182010-10-12 07:14:40 +00007465 if (!RHS->getType()->isVoidType())
John McCall4bc41ae2010-11-18 19:01:18 +00007466 S.RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007467 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007468
Chris Lattner326f7572008-11-18 01:30:42 +00007469 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007470}
7471
Steve Naroff7a5af782007-07-13 16:58:59 +00007472/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7473/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007474static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7475 ExprValueKind &VK,
7476 SourceLocation OpLoc,
7477 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007478 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007479 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007480
Chris Lattner6b0cf142008-11-21 07:05:48 +00007481 QualType ResType = Op->getType();
7482 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007483
John McCall4bc41ae2010-11-18 19:01:18 +00007484 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007485 // Decrement of bool is not allowed.
7486 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007487 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007488 return QualType();
7489 }
7490 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007491 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007492 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007493 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007494 } else if (ResType->isAnyPointerType()) {
7495 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00007496
Chris Lattner6b0cf142008-11-21 07:05:48 +00007497 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00007498 if (PointeeTy->isVoidType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007499 if (S.getLangOptions().CPlusPlus) {
7500 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007501 << Op->getSourceRange();
7502 return QualType();
7503 }
7504
7505 // Pointer to void is a GNU extension in C.
John McCall4bc41ae2010-11-18 19:01:18 +00007506 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00007507 } else if (PointeeTy->isFunctionType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007508 if (S.getLangOptions().CPlusPlus) {
7509 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007510 << Op->getType() << Op->getSourceRange();
7511 return QualType();
7512 }
7513
John McCall4bc41ae2010-11-18 19:01:18 +00007514 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007515 << ResType << Op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007516 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
7517 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00007518 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00007519 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00007520 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007521 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00007522 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7523 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007524 << PointeeTy << Op->getSourceRange();
7525 return QualType();
7526 }
Eli Friedman090addd2010-01-03 00:20:48 +00007527 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007528 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007529 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007530 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007531 } else if (ResType->isPlaceholderType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007532 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007533 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007534 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7535 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00007536 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7537 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007538 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007539 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00007540 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007541 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007542 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007543 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007544 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007545 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007546 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007547 // In C++, a prefix increment is the same type as the operand. Otherwise
7548 // (in C or with postfix), the increment is the unqualified type of the
7549 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00007550 if (isPrefix && S.getLangOptions().CPlusPlus) {
7551 VK = VK_LValue;
7552 return ResType;
7553 } else {
7554 VK = VK_RValue;
7555 return ResType.getUnqualifiedType();
7556 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007557}
7558
John McCall34376a62010-12-04 03:47:34 +00007559void Sema::ConvertPropertyForRValue(Expr *&E) {
7560 assert(E->getValueKind() == VK_LValue &&
7561 E->getObjectKind() == OK_ObjCProperty);
7562 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7563
7564 ExprValueKind VK = VK_RValue;
7565 if (PRE->isImplicitProperty()) {
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007566 if (const ObjCMethodDecl *GetterMethod =
7567 PRE->getImplicitPropertyGetter()) {
7568 QualType Result = GetterMethod->getResultType();
7569 VK = Expr::getValueKindForType(Result);
7570 }
7571 else {
7572 Diag(PRE->getLocation(), diag::err_getter_not_found)
7573 << PRE->getBase()->getType();
7574 }
John McCall34376a62010-12-04 03:47:34 +00007575 }
7576
7577 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
7578 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007579
7580 ExprResult Result = MaybeBindToTemporary(E);
7581 if (!Result.isInvalid())
7582 E = Result.take();
John McCall34376a62010-12-04 03:47:34 +00007583}
7584
7585void Sema::ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType &LHSTy) {
7586 assert(LHS->getValueKind() == VK_LValue &&
7587 LHS->getObjectKind() == OK_ObjCProperty);
7588 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7589
7590 if (PRE->isImplicitProperty()) {
7591 // If using property-dot syntax notation for assignment, and there is a
7592 // setter, RHS expression is being passed to the setter argument. So,
7593 // type conversion (and comparison) is RHS to setter's argument type.
7594 if (const ObjCMethodDecl *SetterMD = PRE->getImplicitPropertySetter()) {
7595 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7596 LHSTy = (*P)->getType();
7597
7598 // Otherwise, if the getter returns an l-value, just call that.
7599 } else {
7600 QualType Result = PRE->getImplicitPropertyGetter()->getResultType();
7601 ExprValueKind VK = Expr::getValueKindForType(Result);
7602 if (VK == VK_LValue) {
7603 LHS = ImplicitCastExpr::Create(Context, LHS->getType(),
7604 CK_GetObjCProperty, LHS, 0, VK);
7605 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007606 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007607 }
John McCall34376a62010-12-04 03:47:34 +00007608 }
7609
7610 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007611 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007612 InitializedEntity::InitializeParameter(Context, LHSTy);
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007613 Expr *Arg = RHS;
7614 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(),
7615 Owned(Arg));
7616 if (!ArgE.isInvalid())
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007617 RHS = ArgE.takeAs<Expr>();
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007618 }
7619}
7620
7621
Anders Carlsson806700f2008-02-01 07:15:58 +00007622/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007623/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007624/// where the declaration is needed for type checking. We only need to
7625/// handle cases when the expression references a function designator
7626/// or is an lvalue. Here are some examples:
7627/// - &(x) => x
7628/// - &*****f => f for f a function designator.
7629/// - &s.xx => s
7630/// - &s.zz[1].yy -> s, if zz is an array
7631/// - *(x + 1) -> x, if x is an array
7632/// - &"123"[2] -> 0
7633/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007634static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007635 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007636 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007637 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007638 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007639 // If this is an arrow operator, the address is an offset from
7640 // the base's value, so the object the base refers to is
7641 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007642 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007643 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007644 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007645 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007646 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007647 // FIXME: This code shouldn't be necessary! We should catch the implicit
7648 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007649 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7650 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7651 if (ICE->getSubExpr()->getType()->isArrayType())
7652 return getPrimaryDecl(ICE->getSubExpr());
7653 }
7654 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007655 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007656 case Stmt::UnaryOperatorClass: {
7657 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007658
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007659 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007660 case UO_Real:
7661 case UO_Imag:
7662 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007663 return getPrimaryDecl(UO->getSubExpr());
7664 default:
7665 return 0;
7666 }
7667 }
Steve Naroff47500512007-04-19 23:00:49 +00007668 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007669 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007670 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007671 // If the result of an implicit cast is an l-value, we care about
7672 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007673 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007674 default:
7675 return 0;
7676 }
7677}
7678
7679/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007680/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007681/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007682/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007683/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007684/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007685/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007686static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7687 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007688 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007689 return S.Context.DependentTy;
7690 if (OrigOp->getType() == S.Context.OverloadTy)
7691 return S.Context.OverloadTy;
John McCall8d08b9b2010-08-27 09:08:28 +00007692
John McCall4bc41ae2010-11-18 19:01:18 +00007693 ExprResult PR = S.CheckPlaceholderExpr(OrigOp, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007694 if (PR.isInvalid()) return QualType();
7695 OrigOp = PR.take();
7696
John McCall8d08b9b2010-08-27 09:08:28 +00007697 // Make sure to ignore parentheses in subsequent checks
7698 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007699
John McCall4bc41ae2010-11-18 19:01:18 +00007700 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007701 // Implement C99-only parts of addressof rules.
7702 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007703 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007704 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7705 // (assuming the deref expression is valid).
7706 return uOp->getSubExpr()->getType();
7707 }
7708 // Technically, there should be a check for array subscript
7709 // expressions here, but the result of one is always an lvalue anyway.
7710 }
John McCallf3a88602011-02-03 08:15:49 +00007711 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007712 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00007713
Chris Lattner9156f1b2010-07-05 19:17:26 +00007714 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007715 bool sfinae = S.isSFINAEContext();
7716 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7717 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007718 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007719 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007720 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007721 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007722 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007723 } else if (lval == Expr::LV_MemberFunction) {
7724 // If it's an instance method, make a member pointer.
7725 // The expression must have exactly the form &A::foo.
7726
7727 // If the underlying expression isn't a decl ref, give up.
7728 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007729 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007730 << OrigOp->getSourceRange();
7731 return QualType();
7732 }
7733 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7734 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7735
7736 // The id-expression was parenthesized.
7737 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007738 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007739 << OrigOp->getSourceRange();
7740
7741 // The method was named without a qualifier.
7742 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007743 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007744 << op->getSourceRange();
7745 }
7746
John McCall4bc41ae2010-11-18 19:01:18 +00007747 return S.Context.getMemberPointerType(op->getType(),
7748 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007749 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007750 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007751 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007752 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007753 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007754 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007755 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007756 return QualType();
7757 }
John McCall086a4642010-11-24 05:12:34 +00007758 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007759 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00007760 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00007761 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00007762 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007763 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007764 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00007765 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00007766 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007767 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007768 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007769 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00007770 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00007771 << "property expression" << op->getSourceRange();
7772 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007773 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007774 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007775 // with the register storage-class specifier.
7776 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007777 // in C++ it is not error to take address of a register
7778 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007779 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007780 !S.getLangOptions().CPlusPlus) {
7781 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00007782 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007783 return QualType();
7784 }
John McCalld14a8642009-11-21 08:51:07 +00007785 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007786 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007787 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007788 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007789 // Could be a pointer to member, though, if there is an explicit
7790 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007791 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007792 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007793 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007794 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007795 S.Diag(OpLoc,
7796 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007797 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007798 return QualType();
7799 }
Mike Stump11289f42009-09-09 15:08:12 +00007800
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007801 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7802 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007803 return S.Context.getMemberPointerType(op->getType(),
7804 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007805 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007806 }
Anders Carlsson5b535762009-05-16 21:43:42 +00007807 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00007808 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007809 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007810
Eli Friedmance7f9002009-05-16 23:27:50 +00007811 if (lval == Expr::LV_IncompleteVoidType) {
7812 // Taking the address of a void variable is technically illegal, but we
7813 // allow it in cases which are otherwise valid.
7814 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007815 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007816 }
7817
Steve Naroff47500512007-04-19 23:00:49 +00007818 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007819 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007820 return S.Context.getObjCObjectPointerType(op->getType());
7821 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007822}
7823
Chris Lattner9156f1b2010-07-05 19:17:26 +00007824/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007825static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7826 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007827 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007828 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007829
John McCall4bc41ae2010-11-18 19:01:18 +00007830 S.UsualUnaryConversions(Op);
Chris Lattner9156f1b2010-07-05 19:17:26 +00007831 QualType OpTy = Op->getType();
7832 QualType Result;
7833
7834 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7835 // is an incomplete type or void. It would be possible to warn about
7836 // dereferencing a void pointer, but it's completely well-defined, and such a
7837 // warning is unlikely to catch any mistakes.
7838 if (const PointerType *PT = OpTy->getAs<PointerType>())
7839 Result = PT->getPointeeType();
7840 else if (const ObjCObjectPointerType *OPT =
7841 OpTy->getAs<ObjCObjectPointerType>())
7842 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007843 else {
John McCall4bc41ae2010-11-18 19:01:18 +00007844 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007845 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007846 if (PR.take() != Op)
7847 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007848 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007849
Chris Lattner9156f1b2010-07-05 19:17:26 +00007850 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007851 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007852 << OpTy << Op->getSourceRange();
7853 return QualType();
7854 }
John McCall4bc41ae2010-11-18 19:01:18 +00007855
7856 // Dereferences are usually l-values...
7857 VK = VK_LValue;
7858
7859 // ...except that certain expressions are never l-values in C.
7860 if (!S.getLangOptions().CPlusPlus &&
7861 IsCForbiddenLValueType(S.Context, Result))
7862 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007863
7864 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007865}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007866
John McCalle3027922010-08-25 11:45:40 +00007867static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007868 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007869 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007870 switch (Kind) {
7871 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007872 case tok::periodstar: Opc = BO_PtrMemD; break;
7873 case tok::arrowstar: Opc = BO_PtrMemI; break;
7874 case tok::star: Opc = BO_Mul; break;
7875 case tok::slash: Opc = BO_Div; break;
7876 case tok::percent: Opc = BO_Rem; break;
7877 case tok::plus: Opc = BO_Add; break;
7878 case tok::minus: Opc = BO_Sub; break;
7879 case tok::lessless: Opc = BO_Shl; break;
7880 case tok::greatergreater: Opc = BO_Shr; break;
7881 case tok::lessequal: Opc = BO_LE; break;
7882 case tok::less: Opc = BO_LT; break;
7883 case tok::greaterequal: Opc = BO_GE; break;
7884 case tok::greater: Opc = BO_GT; break;
7885 case tok::exclaimequal: Opc = BO_NE; break;
7886 case tok::equalequal: Opc = BO_EQ; break;
7887 case tok::amp: Opc = BO_And; break;
7888 case tok::caret: Opc = BO_Xor; break;
7889 case tok::pipe: Opc = BO_Or; break;
7890 case tok::ampamp: Opc = BO_LAnd; break;
7891 case tok::pipepipe: Opc = BO_LOr; break;
7892 case tok::equal: Opc = BO_Assign; break;
7893 case tok::starequal: Opc = BO_MulAssign; break;
7894 case tok::slashequal: Opc = BO_DivAssign; break;
7895 case tok::percentequal: Opc = BO_RemAssign; break;
7896 case tok::plusequal: Opc = BO_AddAssign; break;
7897 case tok::minusequal: Opc = BO_SubAssign; break;
7898 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7899 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7900 case tok::ampequal: Opc = BO_AndAssign; break;
7901 case tok::caretequal: Opc = BO_XorAssign; break;
7902 case tok::pipeequal: Opc = BO_OrAssign; break;
7903 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007904 }
7905 return Opc;
7906}
7907
John McCalle3027922010-08-25 11:45:40 +00007908static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007909 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007910 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007911 switch (Kind) {
7912 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007913 case tok::plusplus: Opc = UO_PreInc; break;
7914 case tok::minusminus: Opc = UO_PreDec; break;
7915 case tok::amp: Opc = UO_AddrOf; break;
7916 case tok::star: Opc = UO_Deref; break;
7917 case tok::plus: Opc = UO_Plus; break;
7918 case tok::minus: Opc = UO_Minus; break;
7919 case tok::tilde: Opc = UO_Not; break;
7920 case tok::exclaim: Opc = UO_LNot; break;
7921 case tok::kw___real: Opc = UO_Real; break;
7922 case tok::kw___imag: Opc = UO_Imag; break;
7923 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007924 }
7925 return Opc;
7926}
7927
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007928/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7929/// This warning is only emitted for builtin assignment operations. It is also
7930/// suppressed in the event of macro expansions.
7931static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7932 SourceLocation OpLoc) {
7933 if (!S.ActiveTemplateInstantiations.empty())
7934 return;
7935 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7936 return;
7937 lhs = lhs->IgnoreParenImpCasts();
7938 rhs = rhs->IgnoreParenImpCasts();
7939 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7940 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7941 if (!LeftDeclRef || !RightDeclRef ||
7942 LeftDeclRef->getLocation().isMacroID() ||
7943 RightDeclRef->getLocation().isMacroID())
7944 return;
7945 const ValueDecl *LeftDecl =
7946 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7947 const ValueDecl *RightDecl =
7948 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7949 if (LeftDecl != RightDecl)
7950 return;
7951 if (LeftDecl->getType().isVolatileQualified())
7952 return;
7953 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7954 if (RefTy->getPointeeType().isVolatileQualified())
7955 return;
7956
7957 S.Diag(OpLoc, diag::warn_self_assignment)
7958 << LeftDeclRef->getType()
7959 << lhs->getSourceRange() << rhs->getSourceRange();
7960}
7961
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007962/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7963/// operator @p Opc at location @c TokLoc. This routine only supports
7964/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007965ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007966 BinaryOperatorKind Opc,
John McCalle3027922010-08-25 11:45:40 +00007967 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007968 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007969 // The following two variables are used for compound assignment operators
7970 QualType CompLHSTy; // Type of LHS after promotions for computation
7971 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007972 ExprValueKind VK = VK_RValue;
7973 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007974
7975 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007976 case BO_Assign:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007977 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007978 if (getLangOptions().CPlusPlus &&
7979 lhs->getObjectKind() != OK_ObjCProperty) {
John McCall4bc41ae2010-11-18 19:01:18 +00007980 VK = lhs->getValueKind();
7981 OK = lhs->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007982 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007983 if (!ResultTy.isNull())
7984 DiagnoseSelfAssignment(*this, lhs, rhs, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007985 break;
John McCalle3027922010-08-25 11:45:40 +00007986 case BO_PtrMemD:
7987 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00007988 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007989 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007990 break;
John McCalle3027922010-08-25 11:45:40 +00007991 case BO_Mul:
7992 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007993 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007994 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007995 break;
John McCalle3027922010-08-25 11:45:40 +00007996 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007997 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7998 break;
John McCalle3027922010-08-25 11:45:40 +00007999 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008000 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
8001 break;
John McCalle3027922010-08-25 11:45:40 +00008002 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008003 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
8004 break;
John McCalle3027922010-08-25 11:45:40 +00008005 case BO_Shl:
8006 case BO_Shr:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008007 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008008 break;
John McCalle3027922010-08-25 11:45:40 +00008009 case BO_LE:
8010 case BO_LT:
8011 case BO_GE:
8012 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008013 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008014 break;
John McCalle3027922010-08-25 11:45:40 +00008015 case BO_EQ:
8016 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008017 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008018 break;
John McCalle3027922010-08-25 11:45:40 +00008019 case BO_And:
8020 case BO_Xor:
8021 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008022 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
8023 break;
John McCalle3027922010-08-25 11:45:40 +00008024 case BO_LAnd:
8025 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00008026 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008027 break;
John McCalle3027922010-08-25 11:45:40 +00008028 case BO_MulAssign:
8029 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00008030 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00008031 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008032 CompLHSTy = CompResultTy;
8033 if (!CompResultTy.isNull())
8034 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008035 break;
John McCalle3027922010-08-25 11:45:40 +00008036 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008037 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
8038 CompLHSTy = CompResultTy;
8039 if (!CompResultTy.isNull())
8040 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008041 break;
John McCalle3027922010-08-25 11:45:40 +00008042 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008043 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
8044 if (!CompResultTy.isNull())
8045 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008046 break;
John McCalle3027922010-08-25 11:45:40 +00008047 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008048 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
8049 if (!CompResultTy.isNull())
8050 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008051 break;
John McCalle3027922010-08-25 11:45:40 +00008052 case BO_ShlAssign:
8053 case BO_ShrAssign:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008054 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008055 CompLHSTy = CompResultTy;
8056 if (!CompResultTy.isNull())
8057 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008058 break;
John McCalle3027922010-08-25 11:45:40 +00008059 case BO_AndAssign:
8060 case BO_XorAssign:
8061 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008062 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
8063 CompLHSTy = CompResultTy;
8064 if (!CompResultTy.isNull())
8065 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008066 break;
John McCalle3027922010-08-25 11:45:40 +00008067 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00008068 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John McCall7decc9e2010-11-18 06:31:45 +00008069 if (getLangOptions().CPlusPlus) {
8070 VK = rhs->getValueKind();
8071 OK = rhs->getObjectKind();
8072 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008073 break;
8074 }
8075 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00008076 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008077 if (CompResultTy.isNull())
John McCall7decc9e2010-11-18 06:31:45 +00008078 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy,
8079 VK, OK, OpLoc));
8080
John McCall34376a62010-12-04 03:47:34 +00008081 if (getLangOptions().CPlusPlus && lhs->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00008082 VK = VK_LValue;
8083 OK = lhs->getObjectKind();
8084 }
8085 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
8086 VK, OK, CompLHSTy,
8087 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008088}
8089
Sebastian Redl44615072009-10-27 12:10:02 +00008090/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
8091/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008092static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8093 const PartialDiagnostic &PD,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008094 const PartialDiagnostic &FirstNote,
8095 SourceRange FirstParenRange,
8096 const PartialDiagnostic &SecondNote,
Douglas Gregor89336232010-03-29 23:34:08 +00008097 SourceRange SecondParenRange) {
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008098 Self.Diag(Loc, PD);
8099
8100 if (!FirstNote.getDiagID())
8101 return;
8102
8103 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
8104 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8105 // We can't display the parentheses, so just return.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008106 return;
8107 }
8108
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008109 Self.Diag(Loc, FirstNote)
8110 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregora771f462010-03-31 17:46:05 +00008111 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008112
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008113 if (!SecondNote.getDiagID())
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008114 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008115
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008116 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
8117 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8118 // We can't display the parentheses, so just dig the
8119 // warning/error and return.
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008120 Self.Diag(Loc, SecondNote);
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008121 return;
8122 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008123
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008124 Self.Diag(Loc, SecondNote)
Douglas Gregora771f462010-03-31 17:46:05 +00008125 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
8126 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008127}
8128
Sebastian Redl44615072009-10-27 12:10:02 +00008129/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8130/// operators are mixed in a way that suggests that the programmer forgot that
8131/// comparison operators have higher precedence. The most typical example of
8132/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00008133static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00008134 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00008135 typedef BinaryOperator BinOp;
8136 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
8137 rhsopc = static_cast<BinOp::Opcode>(-1);
8138 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008139 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00008140 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008141 rhsopc = BO->getOpcode();
8142
8143 // Subs are not binary operators.
8144 if (lhsopc == -1 && rhsopc == -1)
8145 return;
8146
8147 // Bitwise operations are sometimes used as eager logical ops.
8148 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00008149 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
8150 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00008151 return;
8152
Sebastian Redl44615072009-10-27 12:10:02 +00008153 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008154 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008155 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008156 << SourceRange(lhs->getLocStart(), OpLoc)
8157 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00008158 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008159 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008160 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
8161 Self.PDiag(diag::note_precedence_bitwise_silence)
8162 << BinOp::getOpcodeStr(lhsopc),
8163 lhs->getSourceRange());
Sebastian Redl44615072009-10-27 12:10:02 +00008164 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008165 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008166 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008167 << SourceRange(OpLoc, rhs->getLocEnd())
8168 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00008169 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008170 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008171 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
8172 Self.PDiag(diag::note_precedence_bitwise_silence)
8173 << BinOp::getOpcodeStr(rhsopc),
8174 rhs->getSourceRange());
Sebastian Redl43028242009-10-26 15:24:15 +00008175}
8176
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008177/// \brief It accepts a '&&' expr that is inside a '||' one.
8178/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8179/// in parentheses.
8180static void
8181EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8182 Expr *E) {
8183 assert(isa<BinaryOperator>(E) &&
8184 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
8185 SuggestParentheses(Self, OpLoc,
8186 Self.PDiag(diag::warn_logical_and_in_logical_or)
8187 << E->getSourceRange(),
8188 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
8189 E->getSourceRange(),
8190 Self.PDiag(0), SourceRange());
8191}
8192
8193/// \brief Returns true if the given expression can be evaluated as a constant
8194/// 'true'.
8195static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8196 bool Res;
8197 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8198}
8199
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008200/// \brief Returns true if the given expression can be evaluated as a constant
8201/// 'false'.
8202static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8203 bool Res;
8204 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8205}
8206
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008207/// \brief Look for '&&' in the left hand of a '||' expr.
8208static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008209 Expr *OrLHS, Expr *OrRHS) {
8210 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008211 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008212 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8213 if (EvaluatesAsFalse(S, OrRHS))
8214 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008215 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8216 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8217 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8218 } else if (Bop->getOpcode() == BO_LOr) {
8219 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8220 // If it's "a || b && 1 || c" we didn't warn earlier for
8221 // "a || b && 1", but warn now.
8222 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8223 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8224 }
8225 }
8226 }
8227}
8228
8229/// \brief Look for '&&' in the right hand of a '||' expr.
8230static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008231 Expr *OrLHS, Expr *OrRHS) {
8232 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008233 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008234 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8235 if (EvaluatesAsFalse(S, OrLHS))
8236 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008237 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8238 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8239 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008240 }
8241 }
8242}
8243
Sebastian Redl43028242009-10-26 15:24:15 +00008244/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008245/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008246static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00008247 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008248 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008249 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008250 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
8251
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008252 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8253 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008254 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008255 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
8256 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008257 }
Sebastian Redl43028242009-10-26 15:24:15 +00008258}
8259
Steve Naroff218bc2b2007-05-04 21:54:46 +00008260// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008261ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008262 tok::TokenKind Kind,
8263 Expr *lhs, Expr *rhs) {
8264 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00008265 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8266 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008267
Sebastian Redl43028242009-10-26 15:24:15 +00008268 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8269 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8270
Douglas Gregor5287f092009-11-05 00:51:44 +00008271 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8272}
8273
John McCalldadc5752010-08-24 06:29:42 +00008274ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008275 BinaryOperatorKind Opc,
8276 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00008277 if (getLangOptions().CPlusPlus) {
8278 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008279
John McCall622114c2010-12-06 05:26:58 +00008280 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8281 UseBuiltinOperator = false;
8282 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8283 UseBuiltinOperator = true;
8284 } else {
8285 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8286 !rhs->getType()->isOverloadableType();
8287 }
8288
8289 if (!UseBuiltinOperator) {
8290 // Find all of the overloaded operators visible from this
8291 // point. We perform both an operator-name lookup from the local
8292 // scope and an argument-dependent lookup based on the types of
8293 // the arguments.
8294 UnresolvedSet<16> Functions;
8295 OverloadedOperatorKind OverOp
8296 = BinaryOperator::getOverloadedOperator(Opc);
8297 if (S && OverOp != OO_None)
8298 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8299 Functions);
8300
8301 // Build the (potentially-overloaded, potentially-dependent)
8302 // binary operation.
8303 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8304 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00008305 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008306
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008307 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00008308 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008309}
8310
John McCalldadc5752010-08-24 06:29:42 +00008311ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008312 UnaryOperatorKind Opc,
John McCall36226622010-10-12 02:09:17 +00008313 Expr *Input) {
John McCall7decc9e2010-11-18 06:31:45 +00008314 ExprValueKind VK = VK_RValue;
8315 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008316 QualType resultType;
8317 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008318 case UO_PreInc:
8319 case UO_PreDec:
8320 case UO_PostInc:
8321 case UO_PostDec:
John McCall4bc41ae2010-11-18 19:01:18 +00008322 resultType = CheckIncrementDecrementOperand(*this, Input, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008323 Opc == UO_PreInc ||
8324 Opc == UO_PostInc,
8325 Opc == UO_PreInc ||
8326 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008327 break;
John McCalle3027922010-08-25 11:45:40 +00008328 case UO_AddrOf:
John McCall4bc41ae2010-11-18 19:01:18 +00008329 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008330 break;
John McCalle3027922010-08-25 11:45:40 +00008331 case UO_Deref:
Douglas Gregorb92a1562010-02-03 00:27:59 +00008332 DefaultFunctionArrayLvalueConversion(Input);
John McCall4bc41ae2010-11-18 19:01:18 +00008333 resultType = CheckIndirectionOperand(*this, Input, VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008334 break;
John McCalle3027922010-08-25 11:45:40 +00008335 case UO_Plus:
8336 case UO_Minus:
Steve Naroff31090012007-07-16 21:54:35 +00008337 UsualUnaryConversions(Input);
8338 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008339 if (resultType->isDependentType())
8340 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008341 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8342 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008343 break;
8344 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8345 resultType->isEnumeralType())
8346 break;
8347 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008348 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008349 resultType->isPointerType())
8350 break;
John McCall36226622010-10-12 02:09:17 +00008351 else if (resultType->isPlaceholderType()) {
8352 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8353 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008354 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00008355 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008356
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008357 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8358 << resultType << Input->getSourceRange());
John McCalle3027922010-08-25 11:45:40 +00008359 case UO_Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00008360 UsualUnaryConversions(Input);
8361 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008362 if (resultType->isDependentType())
8363 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008364 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8365 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8366 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008367 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008368 << resultType << Input->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008369 else if (resultType->hasIntegerRepresentation())
8370 break;
8371 else if (resultType->isPlaceholderType()) {
8372 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8373 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008374 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00008375 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008376 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8377 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008378 }
Steve Naroff35d85152007-05-07 00:24:15 +00008379 break;
John McCalle3027922010-08-25 11:45:40 +00008380 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008381 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregorb92a1562010-02-03 00:27:59 +00008382 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroff31090012007-07-16 21:54:35 +00008383 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008384 if (resultType->isDependentType())
8385 break;
John McCall36226622010-10-12 02:09:17 +00008386 if (resultType->isScalarType()) { // C99 6.5.3.3p1
8387 // ok, fallthrough
8388 } else if (resultType->isPlaceholderType()) {
8389 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8390 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008391 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00008392 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008393 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8394 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008395 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008396
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008397 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008398 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008399 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008400 break;
John McCalle3027922010-08-25 11:45:40 +00008401 case UO_Real:
8402 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008403 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00008404 // _Real and _Imag map ordinary l-values into ordinary l-values.
8405 if (Input->getValueKind() != VK_RValue &&
8406 Input->getObjectKind() == OK_Ordinary)
8407 VK = Input->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00008408 break;
John McCalle3027922010-08-25 11:45:40 +00008409 case UO_Extension:
Chris Lattner86554282007-06-08 22:32:33 +00008410 resultType = Input->getType();
John McCall7decc9e2010-11-18 06:31:45 +00008411 VK = Input->getValueKind();
8412 OK = Input->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008413 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008414 }
8415 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008416 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008417
John McCall7decc9e2010-11-18 06:31:45 +00008418 return Owned(new (Context) UnaryOperator(Input, Opc, resultType,
8419 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008420}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008421
John McCalldadc5752010-08-24 06:29:42 +00008422ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008423 UnaryOperatorKind Opc,
8424 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00008425 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00008426 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008427 // Find all of the overloaded operators visible from this
8428 // point. We perform both an operator-name lookup from the local
8429 // scope and an argument-dependent lookup based on the types of
8430 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008431 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008432 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008433 if (S && OverOp != OO_None)
8434 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8435 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008436
John McCallb268a282010-08-23 23:25:46 +00008437 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008438 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008439
John McCallb268a282010-08-23 23:25:46 +00008440 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008441}
8442
Douglas Gregor5287f092009-11-05 00:51:44 +00008443// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008444ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008445 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008446 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008447}
8448
Steve Naroff66356bd2007-09-16 14:56:35 +00008449/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008450ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008451 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008452 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008453 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008454 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008455 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008456}
8457
John McCalldadc5752010-08-24 06:29:42 +00008458ExprResult
John McCallb268a282010-08-23 23:25:46 +00008459Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008460 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008461 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8462 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8463
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008464 bool isFileScope
8465 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008466 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008467 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008468
Chris Lattner366727f2007-07-24 16:58:17 +00008469 // FIXME: there are a variety of strange constraints to enforce here, for
8470 // example, it is not possible to goto into a stmt expression apparently.
8471 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008472
Chris Lattner366727f2007-07-24 16:58:17 +00008473 // If there are sub stmts in the compound stmt, take the type of the last one
8474 // as the type of the stmtexpr.
8475 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008476 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008477 if (!Compound->body_empty()) {
8478 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008479 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008480 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008481 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8482 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008483 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008484 }
8485 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008486 // Do function/array conversion on the last expression, but not
8487 // lvalue-to-rvalue. However, initialize an unqualified type.
8488 DefaultFunctionArrayConversion(LastExpr);
8489 Ty = LastExpr->getType().getUnqualifiedType();
8490
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008491 if (!Ty->isDependentType() && !LastExpr->isTypeDependent()) {
8492 ExprResult Res = PerformCopyInitialization(
8493 InitializedEntity::InitializeResult(LPLoc,
8494 Ty,
8495 false),
8496 SourceLocation(),
8497 Owned(LastExpr));
8498 if (Res.isInvalid())
8499 return ExprError();
8500 if ((LastExpr = Res.takeAs<Expr>())) {
8501 if (!LastLabelStmt)
8502 Compound->setLastStmt(LastExpr);
8503 else
8504 LastLabelStmt->setSubStmt(LastExpr);
8505 StmtExprMayBindToTemp = true;
8506 }
8507 }
8508 }
Chris Lattner944d3062008-07-26 19:51:01 +00008509 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008510
Eli Friedmanba961a92009-03-23 00:24:07 +00008511 // FIXME: Check that expression type is complete/non-abstract; statement
8512 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008513 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8514 if (StmtExprMayBindToTemp)
8515 return MaybeBindToTemporary(ResStmtExpr);
8516 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008517}
Steve Naroff78864672007-08-01 22:05:33 +00008518
John McCalldadc5752010-08-24 06:29:42 +00008519ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008520 TypeSourceInfo *TInfo,
8521 OffsetOfComponent *CompPtr,
8522 unsigned NumComponents,
8523 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008524 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008525 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008526 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008527
Chris Lattnerf17bd422007-08-30 17:45:32 +00008528 // We must have at least one component that refers to the type, and the first
8529 // one is known to be a field designator. Verify that the ArgTy represents
8530 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008531 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008532 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8533 << ArgTy << TypeRange);
8534
8535 // Type must be complete per C99 7.17p3 because a declaring a variable
8536 // with an incomplete type would be ill-formed.
8537 if (!Dependent
8538 && RequireCompleteType(BuiltinLoc, ArgTy,
8539 PDiag(diag::err_offsetof_incomplete_type)
8540 << TypeRange))
8541 return ExprError();
8542
Chris Lattner78502cf2007-08-31 21:49:13 +00008543 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8544 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008545 // FIXME: This diagnostic isn't actually visible because the location is in
8546 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008547 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008548 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8549 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008550
8551 bool DidWarnAboutNonPOD = false;
8552 QualType CurrentType = ArgTy;
8553 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8554 llvm::SmallVector<OffsetOfNode, 4> Comps;
8555 llvm::SmallVector<Expr*, 4> Exprs;
8556 for (unsigned i = 0; i != NumComponents; ++i) {
8557 const OffsetOfComponent &OC = CompPtr[i];
8558 if (OC.isBrackets) {
8559 // Offset of an array sub-field. TODO: Should we allow vector elements?
8560 if (!CurrentType->isDependentType()) {
8561 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8562 if(!AT)
8563 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8564 << CurrentType);
8565 CurrentType = AT->getElementType();
8566 } else
8567 CurrentType = Context.DependentTy;
8568
8569 // The expression must be an integral expression.
8570 // FIXME: An integral constant expression?
8571 Expr *Idx = static_cast<Expr*>(OC.U.E);
8572 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8573 !Idx->getType()->isIntegerType())
8574 return ExprError(Diag(Idx->getLocStart(),
8575 diag::err_typecheck_subscript_not_integer)
8576 << Idx->getSourceRange());
8577
8578 // Record this array index.
8579 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8580 Exprs.push_back(Idx);
8581 continue;
8582 }
8583
8584 // Offset of a field.
8585 if (CurrentType->isDependentType()) {
8586 // We have the offset of a field, but we can't look into the dependent
8587 // type. Just record the identifier of the field.
8588 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8589 CurrentType = Context.DependentTy;
8590 continue;
8591 }
8592
8593 // We need to have a complete type to look into.
8594 if (RequireCompleteType(OC.LocStart, CurrentType,
8595 diag::err_offsetof_incomplete_type))
8596 return ExprError();
8597
8598 // Look for the designated field.
8599 const RecordType *RC = CurrentType->getAs<RecordType>();
8600 if (!RC)
8601 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8602 << CurrentType);
8603 RecordDecl *RD = RC->getDecl();
8604
8605 // C++ [lib.support.types]p5:
8606 // The macro offsetof accepts a restricted set of type arguments in this
8607 // International Standard. type shall be a POD structure or a POD union
8608 // (clause 9).
8609 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8610 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008611 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008612 PDiag(diag::warn_offsetof_non_pod_type)
8613 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8614 << CurrentType))
8615 DidWarnAboutNonPOD = true;
8616 }
8617
8618 // Look for the field.
8619 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8620 LookupQualifiedName(R, RD);
8621 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008622 IndirectFieldDecl *IndirectMemberDecl = 0;
8623 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008624 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008625 MemberDecl = IndirectMemberDecl->getAnonField();
8626 }
8627
Douglas Gregor882211c2010-04-28 22:16:22 +00008628 if (!MemberDecl)
8629 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8630 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8631 OC.LocEnd));
8632
Douglas Gregor10982ea2010-04-28 22:36:06 +00008633 // C99 7.17p3:
8634 // (If the specified member is a bit-field, the behavior is undefined.)
8635 //
8636 // We diagnose this as an error.
8637 if (MemberDecl->getBitWidth()) {
8638 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8639 << MemberDecl->getDeclName()
8640 << SourceRange(BuiltinLoc, RParenLoc);
8641 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8642 return ExprError();
8643 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008644
8645 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008646 if (IndirectMemberDecl)
8647 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008648
Douglas Gregord1702062010-04-29 00:18:15 +00008649 // If the member was found in a base class, introduce OffsetOfNodes for
8650 // the base class indirections.
8651 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8652 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008653 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008654 CXXBasePath &Path = Paths.front();
8655 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8656 B != BEnd; ++B)
8657 Comps.push_back(OffsetOfNode(B->Base));
8658 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008659
Francois Pichet783dd6e2010-11-21 06:08:52 +00008660 if (IndirectMemberDecl) {
8661 for (IndirectFieldDecl::chain_iterator FI =
8662 IndirectMemberDecl->chain_begin(),
8663 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8664 assert(isa<FieldDecl>(*FI));
8665 Comps.push_back(OffsetOfNode(OC.LocStart,
8666 cast<FieldDecl>(*FI), OC.LocEnd));
8667 }
8668 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008669 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008670
Douglas Gregor882211c2010-04-28 22:16:22 +00008671 CurrentType = MemberDecl->getType().getNonReferenceType();
8672 }
8673
8674 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8675 TInfo, Comps.data(), Comps.size(),
8676 Exprs.data(), Exprs.size(), RParenLoc));
8677}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008678
John McCalldadc5752010-08-24 06:29:42 +00008679ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008680 SourceLocation BuiltinLoc,
8681 SourceLocation TypeLoc,
8682 ParsedType argty,
8683 OffsetOfComponent *CompPtr,
8684 unsigned NumComponents,
8685 SourceLocation RPLoc) {
8686
Douglas Gregor882211c2010-04-28 22:16:22 +00008687 TypeSourceInfo *ArgTInfo;
8688 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8689 if (ArgTy.isNull())
8690 return ExprError();
8691
Eli Friedman06dcfd92010-08-05 10:15:45 +00008692 if (!ArgTInfo)
8693 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8694
8695 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8696 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008697}
8698
8699
John McCalldadc5752010-08-24 06:29:42 +00008700ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008701 Expr *CondExpr,
8702 Expr *LHSExpr, Expr *RHSExpr,
8703 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008704 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8705
John McCall7decc9e2010-11-18 06:31:45 +00008706 ExprValueKind VK = VK_RValue;
8707 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008708 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008709 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008710 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008711 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008712 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008713 } else {
8714 // The conditional expression is required to be a constant expression.
8715 llvm::APSInt condEval(32);
8716 SourceLocation ExpLoc;
8717 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008718 return ExprError(Diag(ExpLoc,
8719 diag::err_typecheck_choose_expr_requires_constant)
8720 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008721
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008722 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008723 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8724
8725 resType = ActiveExpr->getType();
8726 ValueDependent = ActiveExpr->isValueDependent();
8727 VK = ActiveExpr->getValueKind();
8728 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008729 }
8730
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008731 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008732 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008733 resType->isDependentType(),
8734 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008735}
8736
Steve Naroffc540d662008-09-03 18:15:37 +00008737//===----------------------------------------------------------------------===//
8738// Clang Extensions.
8739//===----------------------------------------------------------------------===//
8740
8741/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008742void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008743 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8744 PushBlockScope(BlockScope, Block);
8745 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008746 if (BlockScope)
8747 PushDeclContext(BlockScope, Block);
8748 else
8749 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008750}
8751
Mike Stump82f071f2009-02-04 22:31:32 +00008752void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008753 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008754 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008755 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008756
John McCall8cb7bdf2010-06-04 23:28:52 +00008757 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008758 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008759
John McCall3882ace2011-01-05 12:14:39 +00008760 // GetTypeForDeclarator always produces a function type for a block
8761 // literal signature. Furthermore, it is always a FunctionProtoType
8762 // unless the function was written with a typedef.
8763 assert(T->isFunctionType() &&
8764 "GetTypeForDeclarator made a non-function block signature");
8765
8766 // Look for an explicit signature in that function type.
8767 FunctionProtoTypeLoc ExplicitSignature;
8768
8769 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8770 if (isa<FunctionProtoTypeLoc>(tmp)) {
8771 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8772
8773 // Check whether that explicit signature was synthesized by
8774 // GetTypeForDeclarator. If so, don't save that as part of the
8775 // written signature.
8776 if (ExplicitSignature.getLParenLoc() ==
8777 ExplicitSignature.getRParenLoc()) {
8778 // This would be much cheaper if we stored TypeLocs instead of
8779 // TypeSourceInfos.
8780 TypeLoc Result = ExplicitSignature.getResultLoc();
8781 unsigned Size = Result.getFullDataSize();
8782 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8783 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8784
8785 ExplicitSignature = FunctionProtoTypeLoc();
8786 }
John McCalla3ccba02010-06-04 11:21:44 +00008787 }
Mike Stump11289f42009-09-09 15:08:12 +00008788
John McCall3882ace2011-01-05 12:14:39 +00008789 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8790 CurBlock->FunctionType = T;
8791
8792 const FunctionType *Fn = T->getAs<FunctionType>();
8793 QualType RetTy = Fn->getResultType();
8794 bool isVariadic =
8795 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8796
John McCall8e346702010-06-04 19:02:56 +00008797 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008798
John McCalla3ccba02010-06-04 11:21:44 +00008799 // Don't allow returning a objc interface by value.
8800 if (RetTy->isObjCObjectType()) {
8801 Diag(ParamInfo.getSourceRange().getBegin(),
8802 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8803 return;
8804 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008805
John McCalla3ccba02010-06-04 11:21:44 +00008806 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008807 // return type. TODO: what should we do with declarators like:
8808 // ^ * { ... }
8809 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008810 if (RetTy != Context.DependentTy)
8811 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008812
John McCalla3ccba02010-06-04 11:21:44 +00008813 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00008814 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008815 if (ExplicitSignature) {
8816 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8817 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008818 if (Param->getIdentifier() == 0 &&
8819 !Param->isImplicit() &&
8820 !Param->isInvalidDecl() &&
8821 !getLangOptions().CPlusPlus)
8822 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008823 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008824 }
John McCalla3ccba02010-06-04 11:21:44 +00008825
8826 // Fake up parameter variables if we have a typedef, like
8827 // ^ fntype { ... }
8828 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8829 for (FunctionProtoType::arg_type_iterator
8830 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8831 ParmVarDecl *Param =
8832 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8833 ParamInfo.getSourceRange().getBegin(),
8834 *I);
John McCall8e346702010-06-04 19:02:56 +00008835 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008836 }
Steve Naroffc540d662008-09-03 18:15:37 +00008837 }
John McCalla3ccba02010-06-04 11:21:44 +00008838
John McCall8e346702010-06-04 19:02:56 +00008839 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008840 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00008841 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00008842 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8843 CurBlock->TheDecl->param_end(),
8844 /*CheckParameterNames=*/false);
8845 }
8846
John McCalla3ccba02010-06-04 11:21:44 +00008847 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008848 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008849
John McCall8e346702010-06-04 19:02:56 +00008850 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008851 Diag(ParamInfo.getAttributes()->getLoc(),
8852 diag::warn_attribute_sentinel_not_variadic) << 1;
8853 // FIXME: remove the attribute.
8854 }
8855
8856 // Put the parameter variables in scope. We can bail out immediately
8857 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008858 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008859 return;
8860
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008861 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008862 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8863 (*AI)->setOwningFunction(CurBlock->TheDecl);
8864
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008865 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008866 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008867 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008868
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008869 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008870 }
John McCallf7b2fb52010-01-22 00:28:27 +00008871 }
Steve Naroffc540d662008-09-03 18:15:37 +00008872}
8873
8874/// ActOnBlockError - If there is an error parsing a block, this callback
8875/// is invoked to pop the information about the block from the action impl.
8876void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008877 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008878 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008879 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008880}
8881
8882/// ActOnBlockStmtExpr - This is called when the body of a block statement
8883/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008884ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008885 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008886 // If blocks are disabled, emit an error.
8887 if (!LangOpts.Blocks)
8888 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008889
Douglas Gregor9a28e842010-03-01 23:15:13 +00008890 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008891
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008892 PopDeclContext();
8893
Steve Naroffc540d662008-09-03 18:15:37 +00008894 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008895 if (!BSI->ReturnType.isNull())
8896 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008897
Mike Stump3bf1ab42009-07-28 22:04:01 +00008898 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008899 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008900
John McCallc63de662011-02-02 13:00:07 +00008901 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00008902 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8903 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00008904
John McCall8e346702010-06-04 19:02:56 +00008905 // If the user wrote a function type in some form, try to use that.
8906 if (!BSI->FunctionType.isNull()) {
8907 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8908
8909 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8910 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8911
8912 // Turn protoless block types into nullary block types.
8913 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008914 FunctionProtoType::ExtProtoInfo EPI;
8915 EPI.ExtInfo = Ext;
8916 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008917
8918 // Otherwise, if we don't need to change anything about the function type,
8919 // preserve its sugar structure.
8920 } else if (FTy->getResultType() == RetTy &&
8921 (!NoReturn || FTy->getNoReturnAttr())) {
8922 BlockTy = BSI->FunctionType;
8923
8924 // Otherwise, make the minimal modifications to the function type.
8925 } else {
8926 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008927 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8928 EPI.TypeQuals = 0; // FIXME: silently?
8929 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008930 BlockTy = Context.getFunctionType(RetTy,
8931 FPT->arg_type_begin(),
8932 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008933 EPI);
John McCall8e346702010-06-04 19:02:56 +00008934 }
8935
8936 // If we don't have a function type, just build one from nothing.
8937 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008938 FunctionProtoType::ExtProtoInfo EPI;
8939 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, 0, CC_Default);
8940 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008941 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008942
John McCall8e346702010-06-04 19:02:56 +00008943 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8944 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008945 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008946
Chris Lattner45542ea2009-04-19 05:28:12 +00008947 // If needed, diagnose invalid gotos and switches in the block.
John McCallaab3e412010-08-25 08:40:02 +00008948 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008949 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008950
Chris Lattner60f84492011-02-17 23:58:47 +00008951 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008952
John McCallc63de662011-02-02 13:00:07 +00008953 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCall1d570a72010-08-25 05:56:39 +00008954
Ted Kremenek1767a272011-02-23 01:51:48 +00008955 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8956 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008957 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008958}
8959
John McCalldadc5752010-08-24 06:29:42 +00008960ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00008961 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008962 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008963 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00008964 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00008965 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008966}
8967
John McCalldadc5752010-08-24 06:29:42 +00008968ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008969 Expr *E, TypeSourceInfo *TInfo,
8970 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008971 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008972
Eli Friedman121ba0c2008-08-09 23:32:40 +00008973 // Get the va_list type
8974 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008975 if (VaListType->isArrayType()) {
8976 // Deal with implicit array decay; for example, on x86-64,
8977 // va_list is an array, but it's supposed to decay to
8978 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008979 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008980 // Make sure the input expression also decays appropriately.
8981 UsualUnaryConversions(E);
8982 } else {
8983 // Otherwise, the va_list argument must be an l-value because
8984 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008985 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008986 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008987 return ExprError();
8988 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008989
Douglas Gregorad3150c2009-05-19 23:10:31 +00008990 if (!E->isTypeDependent() &&
8991 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008992 return ExprError(Diag(E->getLocStart(),
8993 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008994 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008995 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008996
Eli Friedmanba961a92009-03-23 00:24:07 +00008997 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008998 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008999
Abramo Bagnara27db2392010-08-10 10:06:15 +00009000 QualType T = TInfo->getType().getNonLValueExprType(Context);
9001 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009002}
9003
John McCalldadc5752010-08-24 06:29:42 +00009004ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009005 // The type of __null will be int or long, depending on the size of
9006 // pointers on the target.
9007 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009008 unsigned pw = Context.Target.getPointerWidth(0);
9009 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009010 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009011 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009012 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009013 else if (pw == Context.Target.getLongLongWidth())
9014 Ty = Context.LongLongTy;
9015 else {
9016 assert(!"I don't know size of pointer!");
9017 Ty = Context.IntTy;
9018 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009019
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009020 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009021}
9022
Alexis Huntc46382e2010-04-28 23:02:27 +00009023static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009024 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00009025 if (!SemaRef.getLangOptions().ObjC1)
9026 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009027
Anders Carlssonace5d072009-11-10 04:46:30 +00009028 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9029 if (!PT)
9030 return;
9031
9032 // Check if the destination is of type 'id'.
9033 if (!PT->isObjCIdType()) {
9034 // Check if the destination is the 'NSString' interface.
9035 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9036 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9037 return;
9038 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009039
Anders Carlssonace5d072009-11-10 04:46:30 +00009040 // Strip off any parens and casts.
9041 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
9042 if (!SL || SL->isWide())
9043 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009044
Douglas Gregora771f462010-03-31 17:46:05 +00009045 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009046}
9047
Chris Lattner9bad62c2008-01-04 18:04:52 +00009048bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9049 SourceLocation Loc,
9050 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009051 Expr *SrcExpr, AssignmentAction Action,
9052 bool *Complained) {
9053 if (Complained)
9054 *Complained = false;
9055
Chris Lattner9bad62c2008-01-04 18:04:52 +00009056 // Decode the result (notice that AST's are still created for extensions).
9057 bool isInvalid = false;
9058 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00009059 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009060
Chris Lattner9bad62c2008-01-04 18:04:52 +00009061 switch (ConvTy) {
9062 default: assert(0 && "Unknown conversion type");
9063 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009064 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009065 DiagKind = diag::ext_typecheck_convert_pointer_int;
9066 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009067 case IntToPointer:
9068 DiagKind = diag::ext_typecheck_convert_int_pointer;
9069 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009070 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009071 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009072 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9073 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009074 case IncompatiblePointerSign:
9075 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9076 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009077 case FunctionVoidPointer:
9078 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9079 break;
John McCall4fff8f62011-02-01 00:10:29 +00009080 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009081 // Perform array-to-pointer decay if necessary.
9082 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9083
John McCall4fff8f62011-02-01 00:10:29 +00009084 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9085 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9086 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9087 DiagKind = diag::err_typecheck_incompatible_address_space;
9088 break;
9089 }
9090
9091 llvm_unreachable("unknown error case for discarding qualifiers!");
9092 // fallthrough
9093 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009094 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009095 // If the qualifiers lost were because we were applying the
9096 // (deprecated) C++ conversion from a string literal to a char*
9097 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9098 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009099 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009100 // bit of refactoring (so that the second argument is an
9101 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009102 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009103 // C++ semantics.
9104 if (getLangOptions().CPlusPlus &&
9105 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9106 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009107 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9108 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009109 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009110 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009111 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009112 case IntToBlockPointer:
9113 DiagKind = diag::err_int_to_block_pointer;
9114 break;
9115 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009116 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009117 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009118 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009119 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009120 // it can give a more specific diagnostic.
9121 DiagKind = diag::warn_incompatible_qualified_id;
9122 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009123 case IncompatibleVectors:
9124 DiagKind = diag::warn_incompatible_vectors;
9125 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009126 case Incompatible:
9127 DiagKind = diag::err_typecheck_convert_incompatible;
9128 isInvalid = true;
9129 break;
9130 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009131
Douglas Gregorc68e1402010-04-09 00:35:39 +00009132 QualType FirstType, SecondType;
9133 switch (Action) {
9134 case AA_Assigning:
9135 case AA_Initializing:
9136 // The destination type comes first.
9137 FirstType = DstType;
9138 SecondType = SrcType;
9139 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009140
Douglas Gregorc68e1402010-04-09 00:35:39 +00009141 case AA_Returning:
9142 case AA_Passing:
9143 case AA_Converting:
9144 case AA_Sending:
9145 case AA_Casting:
9146 // The source type comes first.
9147 FirstType = SrcType;
9148 SecondType = DstType;
9149 break;
9150 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009151
Douglas Gregorc68e1402010-04-09 00:35:39 +00009152 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00009153 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009154 if (Complained)
9155 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009156 return isInvalid;
9157}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009158
Chris Lattnerc71d08b2009-04-25 21:59:05 +00009159bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009160 llvm::APSInt ICEResult;
9161 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9162 if (Result)
9163 *Result = ICEResult;
9164 return false;
9165 }
9166
Anders Carlssone54e8a12008-11-30 19:50:32 +00009167 Expr::EvalResult EvalResult;
9168
Mike Stump4e1f26a2009-02-19 03:04:26 +00009169 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00009170 EvalResult.HasSideEffects) {
9171 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9172
9173 if (EvalResult.Diag) {
9174 // We only show the note if it's not the usual "invalid subexpression"
9175 // or if it's actually in a subexpression.
9176 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9177 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9178 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9179 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009180
Anders Carlssone54e8a12008-11-30 19:50:32 +00009181 return true;
9182 }
9183
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009184 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9185 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009186
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009187 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009188 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9189 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009190 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009191
Anders Carlssone54e8a12008-11-30 19:50:32 +00009192 if (Result)
9193 *Result = EvalResult.Val.getInt();
9194 return false;
9195}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009196
Douglas Gregorff790f12009-11-26 00:44:06 +00009197void
Mike Stump11289f42009-09-09 15:08:12 +00009198Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009199 ExprEvalContexts.push_back(
9200 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009201}
9202
Mike Stump11289f42009-09-09 15:08:12 +00009203void
Douglas Gregorff790f12009-11-26 00:44:06 +00009204Sema::PopExpressionEvaluationContext() {
9205 // Pop the current expression evaluation context off the stack.
9206 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9207 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009208
Douglas Gregorfab31f42009-12-12 07:57:52 +00009209 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9210 if (Rec.PotentiallyReferenced) {
9211 // Mark any remaining declarations in the current position of the stack
9212 // as "referenced". If they were not meant to be referenced, semantic
9213 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009214 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00009215 I = Rec.PotentiallyReferenced->begin(),
9216 IEnd = Rec.PotentiallyReferenced->end();
9217 I != IEnd; ++I)
9218 MarkDeclarationReferenced(I->first, I->second);
9219 }
9220
9221 if (Rec.PotentiallyDiagnosed) {
9222 // Emit any pending diagnostics.
9223 for (PotentiallyEmittedDiagnostics::iterator
9224 I = Rec.PotentiallyDiagnosed->begin(),
9225 IEnd = Rec.PotentiallyDiagnosed->end();
9226 I != IEnd; ++I)
9227 Diag(I->first, I->second);
9228 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009229 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009230
9231 // When are coming out of an unevaluated context, clear out any
9232 // temporaries that we may have created as part of the evaluation of
9233 // the expression in that context: they aren't relevant because they
9234 // will never be constructed.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009235 if (Rec.Context == Unevaluated &&
Douglas Gregorff790f12009-11-26 00:44:06 +00009236 ExprTemporaries.size() > Rec.NumTemporaries)
9237 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9238 ExprTemporaries.end());
9239
9240 // Destroy the popped expression evaluation record.
9241 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009242}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009243
9244/// \brief Note that the given declaration was referenced in the source code.
9245///
9246/// This routine should be invoke whenever a given declaration is referenced
9247/// in the source code, and where that reference occurred. If this declaration
9248/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9249/// C99 6.9p3), then the declaration will be marked as used.
9250///
9251/// \param Loc the location where the declaration was referenced.
9252///
9253/// \param D the declaration that has been referenced by the source code.
9254void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9255 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009256
Douglas Gregorebada0772010-06-17 23:14:26 +00009257 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009258 return;
Mike Stump11289f42009-09-09 15:08:12 +00009259
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00009260 // Mark a parameter or variable declaration "used", regardless of whether we're in a
9261 // template or not. The reason for this is that unevaluated expressions
9262 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9263 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009264 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009265 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009266 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009267 return;
9268 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009269
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009270 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9271 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009272
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009273 // Do not mark anything as "used" within a dependent context; wait for
9274 // an instantiation.
9275 if (CurContext->isDependentContext())
9276 return;
Mike Stump11289f42009-09-09 15:08:12 +00009277
Douglas Gregorff790f12009-11-26 00:44:06 +00009278 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009279 case Unevaluated:
9280 // We are in an expression that is not potentially evaluated; do nothing.
9281 return;
Mike Stump11289f42009-09-09 15:08:12 +00009282
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009283 case PotentiallyEvaluated:
9284 // We are in a potentially-evaluated expression, so this declaration is
9285 // "used"; handle this below.
9286 break;
Mike Stump11289f42009-09-09 15:08:12 +00009287
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009288 case PotentiallyPotentiallyEvaluated:
9289 // We are in an expression that may be potentially evaluated; queue this
9290 // declaration reference until we know whether the expression is
9291 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009292 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009293 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009294
9295 case PotentiallyEvaluatedIfUsed:
9296 // Referenced declarations will only be used if the construct in the
9297 // containing expression is used.
9298 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009299 }
Mike Stump11289f42009-09-09 15:08:12 +00009300
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009301 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009302 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009303 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00009304 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruthc9262402010-08-23 07:55:51 +00009305 if (Constructor->getParent()->hasTrivialConstructor())
9306 return;
9307 if (!Constructor->isUsed(false))
9308 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00009309 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00009310 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009311 if (!Constructor->isUsed(false))
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009312 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
9313 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009314
Douglas Gregor88d292c2010-05-13 16:44:06 +00009315 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009316 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009317 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009318 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009319 if (Destructor->isVirtual())
9320 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009321 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9322 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
9323 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009324 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00009325 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009326 } else if (MethodDecl->isVirtual())
9327 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009328 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009329 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009330 // Recursive functions should be marked when used from another function.
9331 if (CurContext == Function) return;
9332
Mike Stump11289f42009-09-09 15:08:12 +00009333 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009334 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009335 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009336 bool AlreadyInstantiated = false;
9337 if (FunctionTemplateSpecializationInfo *SpecInfo
9338 = Function->getTemplateSpecializationInfo()) {
9339 if (SpecInfo->getPointOfInstantiation().isInvalid())
9340 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009341 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009342 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009343 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009344 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009345 = Function->getMemberSpecializationInfo()) {
9346 if (MSInfo->getPointOfInstantiation().isInvalid())
9347 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009348 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009349 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009350 AlreadyInstantiated = true;
9351 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009352
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009353 if (!AlreadyInstantiated) {
9354 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9355 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9356 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9357 Loc));
9358 else
Chandler Carruth54080172010-08-25 08:44:16 +00009359 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009360 }
John McCall83779672011-02-19 02:53:41 +00009361 } else {
9362 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009363 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9364 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009365 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009366 MarkDeclarationReferenced(Loc, *i);
9367 }
John McCall83779672011-02-19 02:53:41 +00009368 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009369
John McCall83779672011-02-19 02:53:41 +00009370 // Keep track of used but undefined functions.
9371 if (!Function->isPure() && !Function->hasBody() &&
9372 Function->getLinkage() != ExternalLinkage) {
9373 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9374 if (old.isInvalid()) old = Loc;
9375 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009376
John McCall83779672011-02-19 02:53:41 +00009377 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009378 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009379 }
Mike Stump11289f42009-09-09 15:08:12 +00009380
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009381 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009382 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009383 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009384 Var->getInstantiatedFromStaticDataMember()) {
9385 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9386 assert(MSInfo && "Missing member specialization information?");
9387 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9388 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9389 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth54080172010-08-25 08:44:16 +00009390 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009391 }
9392 }
Mike Stump11289f42009-09-09 15:08:12 +00009393
John McCall15dd4042011-02-21 19:25:48 +00009394 // Keep track of used but undefined variables. We make a hole in
9395 // the warning for static const data members with in-line
9396 // initializers.
John McCall83779672011-02-19 02:53:41 +00009397 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009398 && Var->getLinkage() != ExternalLinkage
9399 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009400 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9401 if (old.isInvalid()) old = Loc;
9402 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009403
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009404 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009405 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009406 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009407}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009408
Douglas Gregor5597ab42010-05-07 23:12:07 +00009409namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009410 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009411 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009412 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009413 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9414 Sema &S;
9415 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009416
Douglas Gregor5597ab42010-05-07 23:12:07 +00009417 public:
9418 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009419
Douglas Gregor5597ab42010-05-07 23:12:07 +00009420 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009421
9422 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9423 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009424 };
9425}
9426
Chandler Carruthaf80f662010-06-09 08:17:30 +00009427bool MarkReferencedDecls::TraverseTemplateArgument(
9428 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009429 if (Arg.getKind() == TemplateArgument::Declaration) {
9430 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9431 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009432
9433 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009434}
9435
Chandler Carruthaf80f662010-06-09 08:17:30 +00009436bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009437 if (ClassTemplateSpecializationDecl *Spec
9438 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9439 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009440 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009441 }
9442
Chandler Carruthc65667c2010-06-10 10:31:57 +00009443 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009444}
9445
9446void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9447 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009448 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009449}
9450
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009451namespace {
9452 /// \brief Helper class that marks all of the declarations referenced by
9453 /// potentially-evaluated subexpressions as "referenced".
9454 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9455 Sema &S;
9456
9457 public:
9458 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9459
9460 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9461
9462 void VisitDeclRefExpr(DeclRefExpr *E) {
9463 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9464 }
9465
9466 void VisitMemberExpr(MemberExpr *E) {
9467 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009468 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009469 }
9470
9471 void VisitCXXNewExpr(CXXNewExpr *E) {
9472 if (E->getConstructor())
9473 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9474 if (E->getOperatorNew())
9475 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9476 if (E->getOperatorDelete())
9477 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009478 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009479 }
9480
9481 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9482 if (E->getOperatorDelete())
9483 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009484 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9485 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9486 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9487 S.MarkDeclarationReferenced(E->getLocStart(),
9488 S.LookupDestructor(Record));
9489 }
9490
Douglas Gregor32b3de52010-09-11 23:32:50 +00009491 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009492 }
9493
9494 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9495 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009496 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009497 }
9498
9499 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9500 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9501 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009502
9503 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9504 Visit(E->getExpr());
9505 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009506 };
9507}
9508
9509/// \brief Mark any declarations that appear within this expression or any
9510/// potentially-evaluated subexpressions as "referenced".
9511void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9512 EvaluatedExprMarker(*this).Visit(E);
9513}
9514
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009515/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9516/// of the program being compiled.
9517///
9518/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009519/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009520/// possibility that the code will actually be executable. Code in sizeof()
9521/// expressions, code used only during overload resolution, etc., are not
9522/// potentially evaluated. This routine will suppress such diagnostics or,
9523/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009524/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009525/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009526///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009527/// This routine should be used for all diagnostics that describe the run-time
9528/// behavior of a program, such as passing a non-POD value through an ellipsis.
9529/// Failure to do so will likely result in spurious diagnostics or failures
9530/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek55ae3192011-02-23 01:51:43 +00009531bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009532 const PartialDiagnostic &PD) {
9533 switch (ExprEvalContexts.back().Context ) {
9534 case Unevaluated:
9535 // The argument will never be evaluated, so don't complain.
9536 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009537
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009538 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009539 case PotentiallyEvaluatedIfUsed:
Ted Kremenek3427fac2011-02-23 01:52:04 +00009540 if (stmt && getCurFunctionOrMethodDecl()) {
9541 FunctionScopes.back()->PossiblyUnreachableDiags.
9542 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9543 }
9544 else
9545 Diag(Loc, PD);
9546
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009547 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009548
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009549 case PotentiallyPotentiallyEvaluated:
9550 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9551 break;
9552 }
9553
9554 return false;
9555}
9556
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009557bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9558 CallExpr *CE, FunctionDecl *FD) {
9559 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9560 return false;
9561
9562 PartialDiagnostic Note =
9563 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9564 << FD->getDeclName() : PDiag();
9565 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009566
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009567 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009568 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009569 PDiag(diag::err_call_function_incomplete_return)
9570 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009571 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009572 << CE->getSourceRange(),
9573 std::make_pair(NoteLoc, Note)))
9574 return true;
9575
9576 return false;
9577}
9578
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009579// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009580// will prevent this condition from triggering, which is what we want.
9581void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9582 SourceLocation Loc;
9583
John McCall0506e4a2009-11-11 02:41:58 +00009584 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009585 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009586
John McCalld5707ab2009-10-12 21:59:07 +00009587 if (isa<BinaryOperator>(E)) {
9588 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009589 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009590 return;
9591
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009592 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9593
John McCallb0e419e2009-11-12 00:06:05 +00009594 // Greylist some idioms by putting them into a warning subcategory.
9595 if (ObjCMessageExpr *ME
9596 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9597 Selector Sel = ME->getSelector();
9598
John McCallb0e419e2009-11-12 00:06:05 +00009599 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009600 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +00009601 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9602
9603 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009604 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +00009605 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9606 }
John McCall0506e4a2009-11-11 02:41:58 +00009607
John McCalld5707ab2009-10-12 21:59:07 +00009608 Loc = Op->getOperatorLoc();
9609 } else if (isa<CXXOperatorCallExpr>(E)) {
9610 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009611 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009612 return;
9613
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009614 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009615 Loc = Op->getOperatorLoc();
9616 } else {
9617 // Not an assignment.
9618 return;
9619 }
9620
John McCalld5707ab2009-10-12 21:59:07 +00009621 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00009622 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009623
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009624 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009625
9626 if (IsOrAssign)
9627 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9628 << FixItHint::CreateReplacement(Loc, "!=");
9629 else
9630 Diag(Loc, diag::note_condition_assign_to_comparison)
9631 << FixItHint::CreateReplacement(Loc, "==");
9632
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009633 Diag(Loc, diag::note_condition_assign_silence)
9634 << FixItHint::CreateInsertion(Open, "(")
9635 << FixItHint::CreateInsertion(Close, ")");
John McCalld5707ab2009-10-12 21:59:07 +00009636}
9637
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009638/// \brief Redundant parentheses over an equality comparison can indicate
9639/// that the user intended an assignment used as condition.
9640void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009641 // Don't warn if the parens came from a macro.
9642 SourceLocation parenLoc = parenE->getLocStart();
9643 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9644 return;
9645
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009646 Expr *E = parenE->IgnoreParens();
9647
9648 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009649 if (opE->getOpcode() == BO_EQ &&
9650 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9651 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009652 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009653
Ted Kremenekae022092011-02-02 02:20:30 +00009654 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
9655 Diag(Loc, diag::note_equality_comparison_to_assign)
9656 << FixItHint::CreateReplacement(Loc, "=");
9657 Diag(Loc, diag::note_equality_comparison_silence)
9658 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9659 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009660 }
9661}
9662
John McCalld5707ab2009-10-12 21:59:07 +00009663bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
9664 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009665 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9666 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009667
9668 if (!E->isTypeDependent()) {
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009669 if (E->isBoundMemberFunction(Context))
9670 return Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9671 << E->getSourceRange();
9672
John McCall34376a62010-12-04 03:47:34 +00009673 if (getLangOptions().CPlusPlus)
9674 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9675
9676 DefaultFunctionArrayLvalueConversion(E);
John McCall29cb2fd2010-12-04 06:09:13 +00009677
9678 QualType T = E->getType();
John McCall34376a62010-12-04 03:47:34 +00009679 if (!T->isScalarType()) // C99 6.8.4.1p1
9680 return Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9681 << T << E->getSourceRange();
John McCalld5707ab2009-10-12 21:59:07 +00009682 }
9683
9684 return false;
9685}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009686
John McCalldadc5752010-08-24 06:29:42 +00009687ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9688 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00009689 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009690 return ExprError();
9691
Douglas Gregorb412e172010-07-25 18:17:45 +00009692 if (CheckBooleanCondition(Sub, Loc))
Douglas Gregore60e41a2010-05-06 17:25:47 +00009693 return ExprError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00009694
9695 return Owned(Sub);
9696}
John McCall36e7fe32010-10-12 00:20:44 +00009697
9698/// Check for operands with placeholder types and complain if found.
9699/// Returns true if there was an error and no recovery was possible.
9700ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) {
9701 const BuiltinType *BT = E->getType()->getAs<BuiltinType>();
9702 if (!BT || !BT->isPlaceholderType()) return Owned(E);
9703
9704 // If this is overload, check for a single overload.
Richard Smith30482bc2011-02-20 03:19:35 +00009705 assert(BT->getKind() == BuiltinType::Overload);
John McCall36e7fe32010-10-12 00:20:44 +00009706
Richard Smith30482bc2011-02-20 03:19:35 +00009707 if (FunctionDecl *Specialization
9708 = ResolveSingleFunctionTemplateSpecialization(E)) {
9709 // The access doesn't really matter in this case.
9710 DeclAccessPair Found = DeclAccessPair::make(Specialization,
9711 Specialization->getAccess());
9712 E = FixOverloadedFunctionReference(E, Found, Specialization);
9713 if (!E) return ExprError();
9714 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +00009715 }
9716
Richard Smith30482bc2011-02-20 03:19:35 +00009717 Diag(Loc, diag::err_ovl_unresolvable) << E->getSourceRange();
John McCall36e7fe32010-10-12 00:20:44 +00009718 return ExprError();
9719}