blob: a27864f673dbdf31c6552b8271da278a71899671 [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 Kremenekdf26df72011-03-01 18:41:00 +0000304 CheckArrayAccess(E);
Ted Kremenek64699be2011-02-16 01:57:07 +0000305
John McCall27584242010-12-06 20:48:59 +0000306 E = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
307 E, 0, VK_RValue);
308}
309
310void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
311 DefaultFunctionArrayConversion(E);
312 DefaultLvalueConversion(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000313}
314
315
Chris Lattner513165e2008-07-25 21:10:04 +0000316/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000317/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-07-25 21:10:04 +0000318/// sometimes surpressed. For example, the array->pointer conversion doesn't
319/// apply if the array is an argument to the sizeof or address (&) operators.
320/// In these instances, this routine should *not* be called.
John McCallf3735e02010-12-01 04:43:34 +0000321Expr *Sema::UsualUnaryConversions(Expr *&E) {
322 // First, convert to an r-value.
323 DefaultFunctionArrayLvalueConversion(E);
324
325 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000326 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000327
328 // Try to perform integral promotions if the object has a theoretically
329 // promotable type.
330 if (Ty->isIntegralOrUnscopedEnumerationType()) {
331 // C99 6.3.1.1p2:
332 //
333 // The following may be used in an expression wherever an int or
334 // unsigned int may be used:
335 // - an object or expression with an integer type whose integer
336 // conversion rank is less than or equal to the rank of int
337 // and unsigned int.
338 // - A bit-field of type _Bool, int, signed int, or unsigned int.
339 //
340 // If an int can represent all values of the original type, the
341 // value is converted to an int; otherwise, it is converted to an
342 // unsigned int. These are called the integer promotions. All
343 // other types are unchanged by the integer promotions.
344
345 QualType PTy = Context.isPromotableBitField(E);
346 if (!PTy.isNull()) {
347 ImpCastExprToType(E, PTy, CK_IntegralCast);
348 return E;
349 }
350 if (Ty->isPromotableIntegerType()) {
351 QualType PT = Context.getPromotedIntegerType(Ty);
352 ImpCastExprToType(E, PT, CK_IntegralCast);
353 return E;
354 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000355 }
356
John McCallf3735e02010-12-01 04:43:34 +0000357 return E;
Chris Lattner513165e2008-07-25 21:10:04 +0000358}
359
Chris Lattner2ce500f2008-07-25 22:25:12 +0000360/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000361/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000362/// double. All other argument types are converted by UsualUnaryConversions().
363void Sema::DefaultArgumentPromotion(Expr *&Expr) {
364 QualType Ty = Expr->getType();
365 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000366
John McCall9bc26772010-12-06 18:36:11 +0000367 UsualUnaryConversions(Expr);
368
Chris Lattner2ce500f2008-07-25 22:25:12 +0000369 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000370 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John McCall9bc26772010-12-06 18:36:11 +0000371 return ImpCastExprToType(Expr, Context.DoubleTy, CK_FloatingCast);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000372}
373
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000374/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
375/// will warn if the resulting type is not a POD type, and rejects ObjC
376/// interfaces passed by value. This returns true if the argument type is
377/// completely illegal.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000378bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
379 FunctionDecl *FDecl) {
Anders Carlssona7d069d2009-01-16 16:48:51 +0000380 DefaultArgumentPromotion(Expr);
Mike Stump11289f42009-09-09 15:08:12 +0000381
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000382 // __builtin_va_start takes the second argument as a "varargs" argument, but
383 // it doesn't actually do anything with it. It doesn't need to be non-pod
384 // etc.
385 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
386 return false;
387
John McCall8b07ec22010-05-15 11:32:37 +0000388 if (Expr->getType()->isObjCObjectType() &&
Ted Kremenek3427fac2011-02-23 01:52:04 +0000389 DiagRuntimeBehavior(Expr->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000390 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
391 << Expr->getType() << CT))
392 return true;
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000393
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000394 if (!Expr->getType()->isPODType() &&
Ted Kremenek3427fac2011-02-23 01:52:04 +0000395 DiagRuntimeBehavior(Expr->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000396 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
397 << Expr->getType() << CT))
398 return true;
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000399
400 return false;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000401}
402
Chris Lattner513165e2008-07-25 21:10:04 +0000403/// UsualArithmeticConversions - Performs various conversions that are common to
404/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000405/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000406/// responsible for emitting appropriate error diagnostics.
407/// FIXME: verify the conversion rules for "complex int" are consistent with
408/// GCC.
409QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
410 bool isCompAssign) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000411 if (!isCompAssign)
Chris Lattner513165e2008-07-25 21:10:04 +0000412 UsualUnaryConversions(lhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000413
414 UsualUnaryConversions(rhsExpr);
Douglas Gregora11693b2008-11-12 17:17:38 +0000415
Mike Stump11289f42009-09-09 15:08:12 +0000416 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000417 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000418 QualType lhs =
419 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000420 QualType rhs =
Chris Lattner574dee62008-07-26 22:17:49 +0000421 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000422
423 // If both types are identical, no conversion is needed.
424 if (lhs == rhs)
425 return lhs;
426
427 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
428 // The caller can deal with this (e.g. pointer + int).
429 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
430 return lhs;
431
John McCalld005ac92010-11-13 08:17:45 +0000432 // Apply unary and bitfield promotions to the LHS's type.
433 QualType lhs_unpromoted = lhs;
434 if (lhs->isPromotableIntegerType())
435 lhs = Context.getPromotedIntegerType(lhs);
Eli Friedman629ffb92009-08-20 04:21:42 +0000436 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000437 if (!LHSBitfieldPromoteTy.isNull())
438 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000439 if (lhs != lhs_unpromoted && !isCompAssign)
440 ImpCastExprToType(lhsExpr, lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000441
John McCalld005ac92010-11-13 08:17:45 +0000442 // If both types are identical, no conversion is needed.
443 if (lhs == rhs)
444 return lhs;
445
446 // At this point, we have two different arithmetic types.
447
448 // Handle complex types first (C99 6.3.1.8p1).
449 bool LHSComplexFloat = lhs->isComplexType();
450 bool RHSComplexFloat = rhs->isComplexType();
451 if (LHSComplexFloat || RHSComplexFloat) {
452 // if we have an integer operand, the result is the complex type.
453
John McCallc5e62b42010-11-13 09:02:35 +0000454 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
455 if (rhs->isIntegerType()) {
456 QualType fp = cast<ComplexType>(lhs)->getElementType();
457 ImpCastExprToType(rhsExpr, fp, CK_IntegralToFloating);
458 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
459 } else {
460 assert(rhs->isComplexIntegerType());
John McCalld7646252010-11-14 08:17:51 +0000461 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000462 }
John McCalld005ac92010-11-13 08:17:45 +0000463 return lhs;
464 }
465
John McCallc5e62b42010-11-13 09:02:35 +0000466 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
467 if (!isCompAssign) {
468 // int -> float -> _Complex float
469 if (lhs->isIntegerType()) {
470 QualType fp = cast<ComplexType>(rhs)->getElementType();
471 ImpCastExprToType(lhsExpr, fp, CK_IntegralToFloating);
472 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
473 } else {
474 assert(lhs->isComplexIntegerType());
John McCalld7646252010-11-14 08:17:51 +0000475 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000476 }
477 }
John McCalld005ac92010-11-13 08:17:45 +0000478 return rhs;
479 }
480
481 // This handles complex/complex, complex/float, or float/complex.
482 // When both operands are complex, the shorter operand is converted to the
483 // type of the longer, and that is the type of the result. This corresponds
484 // to what is done when combining two real floating-point operands.
485 // The fun begins when size promotion occur across type domains.
486 // From H&S 6.3.4: When one operand is complex and the other is a real
487 // floating-point type, the less precise type is converted, within it's
488 // real or complex domain, to the precision of the other type. For example,
489 // when combining a "long double" with a "double _Complex", the
490 // "double _Complex" is promoted to "long double _Complex".
491 int order = Context.getFloatingTypeOrder(lhs, rhs);
492
493 // If both are complex, just cast to the more precise type.
494 if (LHSComplexFloat && RHSComplexFloat) {
495 if (order > 0) {
496 // _Complex float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000497 ImpCastExprToType(rhsExpr, lhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000498 return lhs;
499
500 } else if (order < 0) {
501 // _Complex float -> _Complex double
502 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000503 ImpCastExprToType(lhsExpr, rhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000504 return rhs;
505 }
506 return lhs;
507 }
508
509 // If just the LHS is complex, the RHS needs to be converted,
510 // and the LHS might need to be promoted.
511 if (LHSComplexFloat) {
512 if (order > 0) { // LHS is wider
513 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000514 QualType fp = cast<ComplexType>(lhs)->getElementType();
515 ImpCastExprToType(rhsExpr, fp, CK_FloatingCast);
516 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000517 return lhs;
518 }
519
520 // RHS is at least as wide. Find its corresponding complex type.
521 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
522
523 // double -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000524 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000525
526 // _Complex float -> _Complex double
527 if (!isCompAssign && order < 0)
John McCallc5e62b42010-11-13 09:02:35 +0000528 ImpCastExprToType(lhsExpr, result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000529
530 return result;
531 }
532
533 // Just the RHS is complex, so the LHS needs to be converted
534 // and the RHS might need to be promoted.
535 assert(RHSComplexFloat);
536
537 if (order < 0) { // RHS is wider
538 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000539 if (!isCompAssign) {
Argyrios Kyrtzidise84389b2011-01-18 18:49:33 +0000540 QualType fp = cast<ComplexType>(rhs)->getElementType();
541 ImpCastExprToType(lhsExpr, fp, CK_FloatingCast);
John McCallc5e62b42010-11-13 09:02:35 +0000542 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
543 }
John McCalld005ac92010-11-13 08:17:45 +0000544 return rhs;
545 }
546
547 // LHS is at least as wide. Find its corresponding complex type.
548 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
549
550 // double -> _Complex double
551 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000552 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000553
554 // _Complex float -> _Complex double
555 if (order > 0)
John McCallc5e62b42010-11-13 09:02:35 +0000556 ImpCastExprToType(rhsExpr, result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000557
558 return result;
559 }
560
561 // Now handle "real" floating types (i.e. float, double, long double).
562 bool LHSFloat = lhs->isRealFloatingType();
563 bool RHSFloat = rhs->isRealFloatingType();
564 if (LHSFloat || RHSFloat) {
565 // If we have two real floating types, convert the smaller operand
566 // to the bigger result.
567 if (LHSFloat && RHSFloat) {
568 int order = Context.getFloatingTypeOrder(lhs, rhs);
569 if (order > 0) {
570 ImpCastExprToType(rhsExpr, lhs, CK_FloatingCast);
571 return lhs;
572 }
573
574 assert(order < 0 && "illegal float comparison");
575 if (!isCompAssign)
576 ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast);
577 return rhs;
578 }
579
580 // If we have an integer operand, the result is the real floating type.
581 if (LHSFloat) {
582 if (rhs->isIntegerType()) {
583 // Convert rhs to the lhs floating point type.
584 ImpCastExprToType(rhsExpr, lhs, CK_IntegralToFloating);
585 return lhs;
586 }
587
588 // Convert both sides to the appropriate complex float.
589 assert(rhs->isComplexIntegerType());
590 QualType result = Context.getComplexType(lhs);
591
592 // _Complex int -> _Complex float
John McCalld7646252010-11-14 08:17:51 +0000593 ImpCastExprToType(rhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000594
595 // float -> _Complex float
596 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000597 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000598
599 return result;
600 }
601
602 assert(RHSFloat);
603 if (lhs->isIntegerType()) {
604 // Convert lhs to the rhs floating point type.
605 if (!isCompAssign)
606 ImpCastExprToType(lhsExpr, rhs, CK_IntegralToFloating);
607 return rhs;
608 }
609
610 // Convert both sides to the appropriate complex float.
611 assert(lhs->isComplexIntegerType());
612 QualType result = Context.getComplexType(rhs);
613
614 // _Complex int -> _Complex float
615 if (!isCompAssign)
John McCalld7646252010-11-14 08:17:51 +0000616 ImpCastExprToType(lhsExpr, result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000617
618 // float -> _Complex float
John McCallc5e62b42010-11-13 09:02:35 +0000619 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000620
621 return result;
622 }
623
624 // Handle GCC complex int extension.
625 // FIXME: if the operands are (int, _Complex long), we currently
626 // don't promote the complex. Also, signedness?
627 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
628 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
629 if (lhsComplexInt && rhsComplexInt) {
630 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
631 rhsComplexInt->getElementType());
632 assert(order && "inequal types with equal element ordering");
633 if (order > 0) {
634 // _Complex int -> _Complex long
John McCallc5e62b42010-11-13 09:02:35 +0000635 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000636 return lhs;
637 }
638
639 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000640 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000641 return rhs;
642 } else if (lhsComplexInt) {
643 // int -> _Complex int
John McCallc5e62b42010-11-13 09:02:35 +0000644 ImpCastExprToType(rhsExpr, lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000645 return lhs;
646 } else if (rhsComplexInt) {
647 // int -> _Complex int
648 if (!isCompAssign)
John McCallc5e62b42010-11-13 09:02:35 +0000649 ImpCastExprToType(lhsExpr, rhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000650 return rhs;
651 }
652
653 // Finally, we have two differing integer types.
654 // The rules for this case are in C99 6.3.1.8
655 int compare = Context.getIntegerTypeOrder(lhs, rhs);
656 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
657 rhsSigned = rhs->hasSignedIntegerRepresentation();
658 if (lhsSigned == rhsSigned) {
659 // Same signedness; use the higher-ranked type
660 if (compare >= 0) {
661 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
662 return lhs;
663 } else if (!isCompAssign)
664 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
665 return rhs;
666 } else if (compare != (lhsSigned ? 1 : -1)) {
667 // The unsigned type has greater than or equal rank to the
668 // signed type, so use the unsigned type
669 if (rhsSigned) {
670 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
671 return lhs;
672 } else if (!isCompAssign)
673 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
674 return rhs;
675 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
676 // The two types are different widths; if we are here, that
677 // means the signed type is larger than the unsigned type, so
678 // use the signed type.
679 if (lhsSigned) {
680 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
681 return lhs;
682 } else if (!isCompAssign)
683 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
684 return rhs;
685 } else {
686 // The signed type is higher-ranked than the unsigned type,
687 // but isn't actually any bigger (like unsigned int and long
688 // on most 32-bit systems). Use the unsigned type corresponding
689 // to the signed type.
690 QualType result =
691 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
692 ImpCastExprToType(rhsExpr, result, CK_IntegralCast);
693 if (!isCompAssign)
694 ImpCastExprToType(lhsExpr, result, CK_IntegralCast);
695 return result;
696 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000697}
698
Chris Lattner513165e2008-07-25 21:10:04 +0000699//===----------------------------------------------------------------------===//
700// Semantic Analysis for various Expression Types
701//===----------------------------------------------------------------------===//
702
703
Steve Naroff83895f72007-09-16 03:34:24 +0000704/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000705/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
706/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
707/// multiple tokens. However, the common case is that StringToks points to one
708/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000709///
John McCalldadc5752010-08-24 06:29:42 +0000710ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +0000711Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000712 assert(NumStringToks && "Must have at least one string!");
713
Chris Lattner8a24e582009-01-16 18:51:42 +0000714 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000715 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000716 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000717
Chris Lattner23b7eb62007-06-15 23:05:46 +0000718 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000719 for (unsigned i = 0; i != NumStringToks; ++i)
720 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000721
Chris Lattner36fc8792008-02-11 00:02:17 +0000722 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidiscbad7252008-08-09 17:20:01 +0000723 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattner36fc8792008-02-11 00:02:17 +0000724 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000725
726 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +0000727 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000728 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000729
Chris Lattner36fc8792008-02-11 00:02:17 +0000730 // Get an array type for the string, according to C99 6.4.5. This includes
731 // the nul terminator character as well as the string length for pascal
732 // strings.
733 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000734 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000735 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000736
Chris Lattner5b183d82006-11-10 05:03:26 +0000737 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +0000738 return Owned(StringLiteral::Create(Context, Literal.GetString(),
739 Literal.GetStringLength(),
740 Literal.AnyWide, StrTy,
741 &StringTokLocs[0],
742 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000743}
744
John McCallc63de662011-02-02 13:00:07 +0000745enum CaptureResult {
746 /// No capture is required.
747 CR_NoCapture,
748
749 /// A capture is required.
750 CR_Capture,
751
John McCall351762c2011-02-07 10:33:21 +0000752 /// A by-ref capture is required.
753 CR_CaptureByRef,
754
John McCallc63de662011-02-02 13:00:07 +0000755 /// An error occurred when trying to capture the given variable.
756 CR_Error
757};
758
759/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +0000760///
John McCallc63de662011-02-02 13:00:07 +0000761/// \param var - the variable referenced
762/// \param DC - the context which we couldn't capture through
763static CaptureResult
John McCall351762c2011-02-07 10:33:21 +0000764diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +0000765 VarDecl *var, DeclContext *DC) {
766 switch (S.ExprEvalContexts.back().Context) {
767 case Sema::Unevaluated:
768 // The argument will never be evaluated, so don't complain.
769 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +0000770
John McCallc63de662011-02-02 13:00:07 +0000771 case Sema::PotentiallyEvaluated:
772 case Sema::PotentiallyEvaluatedIfUsed:
773 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +0000774
John McCallc63de662011-02-02 13:00:07 +0000775 case Sema::PotentiallyPotentiallyEvaluated:
776 // FIXME: delay these!
777 break;
Chris Lattner497d7b02009-04-21 22:26:47 +0000778 }
Mike Stump11289f42009-09-09 15:08:12 +0000779
John McCallc63de662011-02-02 13:00:07 +0000780 // Don't diagnose about capture if we're not actually in code right
781 // now; in general, there are more appropriate places that will
782 // diagnose this.
783 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
784
785 // This particular madness can happen in ill-formed default
786 // arguments; claim it's okay and let downstream code handle it.
787 if (isa<ParmVarDecl>(var) &&
788 S.CurContext == var->getDeclContext()->getParent())
789 return CR_NoCapture;
790
791 DeclarationName functionName;
792 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
793 functionName = fn->getDeclName();
794 // FIXME: variable from enclosing block that we couldn't capture from!
795
796 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
797 << var->getIdentifier() << functionName;
798 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
799 << var->getIdentifier();
800
801 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +0000802}
803
John McCall351762c2011-02-07 10:33:21 +0000804/// There is a well-formed capture at a particular scope level;
805/// propagate it through all the nested blocks.
806static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
807 const BlockDecl::Capture &capture) {
808 VarDecl *var = capture.getVariable();
809
810 // Update all the inner blocks with the capture information.
811 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
812 i != e; ++i) {
813 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
814 innerBlock->Captures.push_back(
815 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
816 /*nested*/ true, capture.getCopyExpr()));
817 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
818 }
819
820 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
821}
822
823/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +0000824/// given value in the current context requires a variable capture.
825///
826/// This also keeps the captures set in the BlockScopeInfo records
827/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +0000828static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +0000829 ValueDecl *value) {
830 // Only variables ever require capture.
831 VarDecl *var = dyn_cast<VarDecl>(value);
John McCallf4cd4f92011-02-09 01:13:10 +0000832 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +0000833
834 // Fast path: variables from the current context never require capture.
835 DeclContext *DC = S.CurContext;
836 if (var->getDeclContext() == DC) return CR_NoCapture;
837
838 // Only variables with local storage require capture.
839 // FIXME: What about 'const' variables in C++?
840 if (!var->hasLocalStorage()) return CR_NoCapture;
841
842 // Otherwise, we need to capture.
843
844 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +0000845 do {
846 // Only blocks (and eventually C++0x closures) can capture; other
847 // scopes don't work.
848 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +0000849 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +0000850
851 BlockScopeInfo *blockScope =
852 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
853 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
854
John McCall351762c2011-02-07 10:33:21 +0000855 // Check whether we've already captured it in this block. If so,
856 // we're done.
857 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
858 return propagateCapture(S, functionScopesIndex,
859 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +0000860
861 functionScopesIndex--;
862 DC = cast<BlockDecl>(DC)->getDeclContext();
863 } while (var->getDeclContext() != DC);
864
John McCall351762c2011-02-07 10:33:21 +0000865 // Okay, we descended all the way to the block that defines the variable.
866 // Actually try to capture it.
867 QualType type = var->getType();
868
869 // Prohibit variably-modified types.
870 if (type->isVariablyModifiedType()) {
871 S.Diag(loc, diag::err_ref_vm_type);
872 S.Diag(var->getLocation(), diag::note_declared_at);
873 return CR_Error;
874 }
875
876 // Prohibit arrays, even in __block variables, but not references to
877 // them.
878 if (type->isArrayType()) {
879 S.Diag(loc, diag::err_ref_array_type);
880 S.Diag(var->getLocation(), diag::note_declared_at);
881 return CR_Error;
882 }
883
884 S.MarkDeclarationReferenced(loc, var);
885
886 // The BlocksAttr indicates the variable is bound by-reference.
887 bool byRef = var->hasAttr<BlocksAttr>();
888
889 // Build a copy expression.
890 Expr *copyExpr = 0;
891 if (!byRef && S.getLangOptions().CPlusPlus &&
892 !type->isDependentType() && type->isStructureOrClassType()) {
893 // According to the blocks spec, the capture of a variable from
894 // the stack requires a const copy constructor. This is not true
895 // of the copy/move done to move a __block variable to the heap.
896 type.addConst();
897
898 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
899 ExprResult result =
900 S.PerformCopyInitialization(
901 InitializedEntity::InitializeBlock(var->getLocation(),
902 type, false),
903 loc, S.Owned(declRef));
904
905 // Build a full-expression copy expression if initialization
906 // succeeded and used a non-trivial constructor. Recover from
907 // errors by pretending that the copy isn't necessary.
908 if (!result.isInvalid() &&
909 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
910 result = S.MaybeCreateExprWithCleanups(result);
911 copyExpr = result.take();
912 }
913 }
914
915 // We're currently at the declarer; go back to the closure.
916 functionScopesIndex++;
917 BlockScopeInfo *blockScope =
918 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
919
920 // Build a valid capture in this scope.
921 blockScope->Captures.push_back(
922 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
923 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
924
925 // Propagate that to inner captures if necessary.
926 return propagateCapture(S, functionScopesIndex,
927 blockScope->Captures.back());
928}
929
930static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
931 const DeclarationNameInfo &NameInfo,
932 bool byRef) {
933 assert(isa<VarDecl>(vd) && "capturing non-variable");
934
935 VarDecl *var = cast<VarDecl>(vd);
936 assert(var->hasLocalStorage() && "capturing non-local");
937 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
938
939 QualType exprType = var->getType().getNonReferenceType();
940
941 BlockDeclRefExpr *BDRE;
942 if (!byRef) {
943 // The variable will be bound by copy; make it const within the
944 // closure, but record that this was done in the expression.
945 bool constAdded = !exprType.isConstQualified();
946 exprType.addConst();
947
948 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
949 NameInfo.getLoc(), false,
950 constAdded);
951 } else {
952 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
953 NameInfo.getLoc(), true);
954 }
955
956 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +0000957}
Chris Lattner2a9d9892008-10-20 05:16:36 +0000958
John McCalldadc5752010-08-24 06:29:42 +0000959ExprResult
John McCall7decc9e2010-11-18 06:31:45 +0000960Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +0000961 SourceLocation Loc,
962 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000963 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +0000964 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000965}
966
John McCallf4cd4f92011-02-09 01:13:10 +0000967/// BuildDeclRefExpr - Build an expression that references a
968/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +0000969ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +0000970Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000971 const DeclarationNameInfo &NameInfo,
972 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000973 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +0000974
John McCall086a4642010-11-24 05:12:34 +0000975 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000976 SS? SS->getWithLocInContext(Context)
977 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +0000978 D, NameInfo, Ty, VK);
979
980 // Just in case we're building an illegal pointer-to-member.
981 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
982 E->setObjectKind(OK_BitField);
983
984 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000985}
986
John McCallfeb624a2010-11-23 20:48:44 +0000987static ExprResult
988BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
989 const CXXScopeSpec &SS, FieldDecl *Field,
990 DeclAccessPair FoundDecl,
991 const DeclarationNameInfo &MemberNameInfo);
992
John McCalldadc5752010-08-24 06:29:42 +0000993ExprResult
John McCallf3a88602011-02-03 08:15:49 +0000994Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
995 SourceLocation loc,
996 IndirectFieldDecl *indirectField,
997 Expr *baseObjectExpr,
998 SourceLocation opLoc) {
999 // First, build the expression that refers to the base object.
1000
1001 bool baseObjectIsPointer = false;
1002 Qualifiers baseQuals;
1003
1004 // Case 1: the base of the indirect field is not a field.
1005 VarDecl *baseVariable = indirectField->getVarDecl();
Douglas Gregore10f36d2011-02-18 02:44:58 +00001006 CXXScopeSpec EmptySS;
John McCallf3a88602011-02-03 08:15:49 +00001007 if (baseVariable) {
1008 assert(baseVariable->getType()->isRecordType());
1009
1010 // In principle we could have a member access expression that
1011 // accesses an anonymous struct/union that's a static member of
1012 // the base object's class. However, under the current standard,
1013 // static data members cannot be anonymous structs or unions.
1014 // Supporting this is as easy as building a MemberExpr here.
1015 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1016
1017 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1018
1019 ExprResult result =
Douglas Gregore10f36d2011-02-18 02:44:58 +00001020 BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
John McCallf3a88602011-02-03 08:15:49 +00001021 if (result.isInvalid()) return ExprError();
1022
1023 baseObjectExpr = result.take();
1024 baseObjectIsPointer = false;
1025 baseQuals = baseObjectExpr->getType().getQualifiers();
1026
1027 // Case 2: the base of the indirect field is a field and the user
1028 // wrote a member expression.
1029 } else if (baseObjectExpr) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001030 // The caller provided the base object expression. Determine
1031 // whether its a pointer and whether it adds any qualifiers to the
1032 // anonymous struct/union fields we're looking into.
John McCallf3a88602011-02-03 08:15:49 +00001033 QualType objectType = baseObjectExpr->getType();
1034
1035 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1036 baseObjectIsPointer = true;
1037 objectType = ptr->getPointeeType();
1038 } else {
1039 baseObjectIsPointer = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001040 }
John McCallf3a88602011-02-03 08:15:49 +00001041 baseQuals = objectType.getQualifiers();
1042
1043 // Case 3: the base of the indirect field is a field and we should
1044 // build an implicit member access.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001045 } else {
1046 // We've found a member of an anonymous struct/union that is
1047 // inside a non-anonymous struct/union, so in a well-formed
1048 // program our base object expression is "this".
John McCallf3a88602011-02-03 08:15:49 +00001049 CXXMethodDecl *method = tryCaptureCXXThis();
1050 if (!method) {
1051 Diag(loc, diag::err_invalid_member_use_in_static_method)
1052 << indirectField->getDeclName();
1053 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001054 }
1055
John McCallf3a88602011-02-03 08:15:49 +00001056 // Our base object expression is "this".
1057 baseObjectExpr =
1058 new (Context) CXXThisExpr(loc, method->getThisType(Context),
1059 /*isImplicit=*/ true);
1060 baseObjectIsPointer = true;
1061 baseQuals = Qualifiers::fromCVRMask(method->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001062 }
1063
1064 // Build the implicit member references to the field of the
1065 // anonymous struct/union.
John McCallf3a88602011-02-03 08:15:49 +00001066 Expr *result = baseObjectExpr;
1067 IndirectFieldDecl::chain_iterator
1068 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCallfeb624a2010-11-23 20:48:44 +00001069
John McCallf3a88602011-02-03 08:15:49 +00001070 // Build the first member access in the chain with full information.
1071 if (!baseVariable) {
1072 FieldDecl *field = cast<FieldDecl>(*FI);
John McCallfeb624a2010-11-23 20:48:44 +00001073
John McCallf3a88602011-02-03 08:15:49 +00001074 // FIXME: use the real found-decl info!
1075 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall8ccfcb52009-09-24 19:53:00 +00001076
John McCallf3a88602011-02-03 08:15:49 +00001077 // Make a nameInfo that properly uses the anonymous name.
1078 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall8ccfcb52009-09-24 19:53:00 +00001079
John McCallf3a88602011-02-03 08:15:49 +00001080 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001081 EmptySS, field, foundDecl,
John McCallf3a88602011-02-03 08:15:49 +00001082 memberNameInfo).take();
1083 baseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +00001084
John McCallf3a88602011-02-03 08:15:49 +00001085 // FIXME: check qualified member access
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001086 }
1087
John McCallf3a88602011-02-03 08:15:49 +00001088 // In all cases, we should now skip the first declaration in the chain.
1089 ++FI;
1090
Douglas Gregore10f36d2011-02-18 02:44:58 +00001091 while (FI != FEnd) {
1092 FieldDecl *field = cast<FieldDecl>(*FI++);
John McCallf3a88602011-02-03 08:15:49 +00001093
1094 // FIXME: these are somewhat meaningless
1095 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1096 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCallf3a88602011-02-03 08:15:49 +00001097
1098 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001099 (FI == FEnd? SS : EmptySS), field,
1100 foundDecl, memberNameInfo)
John McCallf3a88602011-02-03 08:15:49 +00001101 .take();
1102 }
1103
1104 return Owned(result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001105}
1106
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001107/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001108/// possibly a list of template arguments.
1109///
1110/// If this produces template arguments, it is permitted to call
1111/// DecomposeTemplateName.
1112///
1113/// This actually loses a lot of source location information for
1114/// non-standard name kinds; we should consider preserving that in
1115/// some way.
1116static void DecomposeUnqualifiedId(Sema &SemaRef,
1117 const UnqualifiedId &Id,
1118 TemplateArgumentListInfo &Buffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001119 DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00001120 const TemplateArgumentListInfo *&TemplateArgs) {
1121 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1122 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1123 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1124
1125 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1126 Id.TemplateId->getTemplateArgs(),
1127 Id.TemplateId->NumArgs);
1128 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1129 TemplateArgsPtr.release();
1130
John McCall3e56fd42010-08-23 07:28:44 +00001131 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001132 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1133 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001134 TemplateArgs = &Buffer;
1135 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001136 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001137 TemplateArgs = 0;
1138 }
1139}
1140
John McCall2d74de92009-12-01 22:10:20 +00001141/// Determines if the given class is provably not derived from all of
1142/// the prospective base classes.
1143static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1144 CXXRecordDecl *Record,
1145 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +00001146 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +00001147 return false;
1148
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001149 RecordDecl *RD = Record->getDefinition();
John McCalla6d407c2009-12-01 22:28:41 +00001150 if (!RD) return false;
1151 Record = cast<CXXRecordDecl>(RD);
1152
John McCall2d74de92009-12-01 22:10:20 +00001153 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1154 E = Record->bases_end(); I != E; ++I) {
1155 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1156 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1157 if (!BaseRT) return false;
1158
1159 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +00001160 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1161 return false;
1162 }
1163
1164 return true;
1165}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001166
John McCall2d74de92009-12-01 22:10:20 +00001167enum IMAKind {
1168 /// The reference is definitely not an instance member access.
1169 IMA_Static,
1170
1171 /// The reference may be an implicit instance member access.
1172 IMA_Mixed,
1173
1174 /// The reference may be to an instance member, but it is invalid if
1175 /// so, because the context is not an instance method.
1176 IMA_Mixed_StaticContext,
1177
1178 /// The reference may be to an instance member, but it is invalid if
1179 /// so, because the context is from an unrelated class.
1180 IMA_Mixed_Unrelated,
1181
1182 /// The reference is definitely an implicit instance member access.
1183 IMA_Instance,
1184
1185 /// The reference may be to an unresolved using declaration.
1186 IMA_Unresolved,
1187
1188 /// The reference may be to an unresolved using declaration and the
1189 /// context is not an instance method.
1190 IMA_Unresolved_StaticContext,
1191
John McCall2d74de92009-12-01 22:10:20 +00001192 /// All possible referrents are instance members and the current
1193 /// context is not an instance method.
1194 IMA_Error_StaticContext,
1195
1196 /// All possible referrents are instance members of an unrelated
1197 /// class.
1198 IMA_Error_Unrelated
1199};
1200
1201/// The given lookup names class member(s) and is not being used for
1202/// an address-of-member expression. Classify the type of access
1203/// according to whether it's possible that this reference names an
1204/// instance member. This is best-effort; it is okay to
1205/// conservatively answer "yes", in which case some errors will simply
1206/// not be caught until template-instantiation.
1207static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1208 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +00001209 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +00001210
John McCall87fe5d52010-05-20 01:18:31 +00001211 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCall2d74de92009-12-01 22:10:20 +00001212 bool isStaticContext =
John McCall87fe5d52010-05-20 01:18:31 +00001213 (!isa<CXXMethodDecl>(DC) ||
1214 cast<CXXMethodDecl>(DC)->isStatic());
John McCall2d74de92009-12-01 22:10:20 +00001215
1216 if (R.isUnresolvableResult())
1217 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1218
1219 // Collect all the declaring classes of instance members we find.
1220 bool hasNonInstance = false;
Sebastian Redl34620312010-11-26 16:28:07 +00001221 bool hasField = false;
John McCall2d74de92009-12-01 22:10:20 +00001222 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1223 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCalla8ae2222010-04-06 21:38:20 +00001224 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00001225
John McCalla8ae2222010-04-06 21:38:20 +00001226 if (D->isCXXInstanceMember()) {
Sebastian Redl34620312010-11-26 16:28:07 +00001227 if (dyn_cast<FieldDecl>(D))
1228 hasField = true;
1229
John McCall2d74de92009-12-01 22:10:20 +00001230 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCall2d74de92009-12-01 22:10:20 +00001231 Classes.insert(R->getCanonicalDecl());
1232 }
1233 else
1234 hasNonInstance = true;
1235 }
1236
1237 // If we didn't find any instance members, it can't be an implicit
1238 // member reference.
1239 if (Classes.empty())
1240 return IMA_Static;
1241
1242 // If the current context is not an instance method, it can't be
1243 // an implicit member reference.
Sebastian Redl34620312010-11-26 16:28:07 +00001244 if (isStaticContext) {
1245 if (hasNonInstance)
1246 return IMA_Mixed_StaticContext;
1247
1248 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1249 // C++0x [expr.prim.general]p10:
1250 // An id-expression that denotes a non-static data member or non-static
1251 // member function of a class can only be used:
1252 // (...)
1253 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1254 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1255 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1256 if (isUnevaluatedExpression)
1257 return IMA_Mixed_StaticContext;
1258 }
1259
1260 return IMA_Error_StaticContext;
1261 }
John McCall2d74de92009-12-01 22:10:20 +00001262
1263 // If we can prove that the current context is unrelated to all the
1264 // declaring classes, it can't be an implicit member reference (in
1265 // which case it's an error if any of those members are selected).
1266 if (IsProvablyNotDerivedFrom(SemaRef,
John McCall87fe5d52010-05-20 01:18:31 +00001267 cast<CXXMethodDecl>(DC)->getParent(),
John McCall2d74de92009-12-01 22:10:20 +00001268 Classes))
1269 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1270
1271 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1272}
1273
1274/// Diagnose a reference to a field with no object available.
1275static void DiagnoseInstanceReference(Sema &SemaRef,
1276 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00001277 NamedDecl *rep,
1278 const DeclarationNameInfo &nameInfo) {
1279 SourceLocation Loc = nameInfo.getLoc();
John McCall2d74de92009-12-01 22:10:20 +00001280 SourceRange Range(Loc);
1281 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1282
John McCallf3a88602011-02-03 08:15:49 +00001283 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCall2d74de92009-12-01 22:10:20 +00001284 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1285 if (MD->isStatic()) {
1286 // "invalid use of member 'x' in static member function"
1287 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCallf3a88602011-02-03 08:15:49 +00001288 << Range << nameInfo.getName();
John McCall2d74de92009-12-01 22:10:20 +00001289 return;
1290 }
1291 }
1292
1293 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCallf3a88602011-02-03 08:15:49 +00001294 << nameInfo.getName() << Range;
John McCall2d74de92009-12-01 22:10:20 +00001295 return;
1296 }
1297
1298 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +00001299}
1300
John McCalld681c392009-12-16 08:11:27 +00001301/// Diagnose an empty lookup.
1302///
1303/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001304bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1305 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +00001306 DeclarationName Name = R.getLookupName();
1307
John McCalld681c392009-12-16 08:11:27 +00001308 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001309 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001310 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1311 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001312 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001313 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001314 diagnostic_suggest = diag::err_undeclared_use_suggest;
1315 }
John McCalld681c392009-12-16 08:11:27 +00001316
Douglas Gregor598b08f2009-12-31 05:20:13 +00001317 // If the original lookup was an unqualified lookup, fake an
1318 // unqualified lookup. This is useful when (for example) the
1319 // original lookup would not have found something because it was a
1320 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001321 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001322 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001323 if (isa<CXXRecordDecl>(DC)) {
1324 LookupQualifiedName(R, DC);
1325
1326 if (!R.empty()) {
1327 // Don't give errors about ambiguities in this lookup.
1328 R.suppressDiagnostics();
1329
1330 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1331 bool isInstance = CurMethod &&
1332 CurMethod->isInstance() &&
1333 DC == CurMethod->getParent();
1334
1335 // Give a code modification hint to insert 'this->'.
1336 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1337 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001338 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001339 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1340 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001341 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001342 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001343 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001344 Diag(R.getNameLoc(), diagnostic) << Name
1345 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1346 QualType DepThisType = DepMethod->getThisType(Context);
1347 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1348 R.getNameLoc(), DepThisType, false);
1349 TemplateArgumentListInfo TList;
1350 if (ULE->hasExplicitTemplateArgs())
1351 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001352
Douglas Gregore16af532011-02-28 18:50:33 +00001353 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001354 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001355 CXXDependentScopeMemberExpr *DepExpr =
1356 CXXDependentScopeMemberExpr::Create(
1357 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001358 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyfe712382010-08-20 20:54:15 +00001359 R.getLookupNameInfo(), &TList);
1360 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001361 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001362 // FIXME: we should be able to handle this case too. It is correct
1363 // to add this-> here. This is a workaround for PR7947.
1364 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001365 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001366 } else {
John McCalld681c392009-12-16 08:11:27 +00001367 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001368 }
John McCalld681c392009-12-16 08:11:27 +00001369
1370 // Do we really want to note all of these?
1371 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1372 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1373
1374 // Tell the callee to try to recover.
1375 return false;
1376 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001377
1378 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001379 }
1380 }
1381
Douglas Gregor598b08f2009-12-31 05:20:13 +00001382 // We didn't find anything, so try to correct for a typo.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001383 DeclarationName Corrected;
Daniel Dunbarf7ced252010-06-02 15:46:52 +00001384 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001385 if (!R.empty()) {
1386 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1387 if (SS.isEmpty())
1388 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1389 << FixItHint::CreateReplacement(R.getNameLoc(),
1390 R.getLookupName().getAsString());
1391 else
1392 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1393 << Name << computeDeclContext(SS, false) << R.getLookupName()
1394 << SS.getRange()
1395 << FixItHint::CreateReplacement(R.getNameLoc(),
1396 R.getLookupName().getAsString());
1397 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1398 Diag(ND->getLocation(), diag::note_previous_decl)
1399 << ND->getDeclName();
1400
1401 // Tell the callee to try to recover.
1402 return false;
1403 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001404
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001405 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1406 // FIXME: If we ended up with a typo for a type name or
1407 // Objective-C class name, we're in trouble because the parser
1408 // is in the wrong place to recover. Suggest the typo
1409 // correction, but don't make it a fix-it since we're not going
1410 // to recover well anyway.
1411 if (SS.isEmpty())
1412 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1413 else
1414 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1415 << Name << computeDeclContext(SS, false) << R.getLookupName()
1416 << SS.getRange();
1417
1418 // Don't try to recover; it won't work.
1419 return true;
1420 }
1421 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001422 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001423 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001424 if (SS.isEmpty())
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001425 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001426 else
Douglas Gregor25363982010-01-01 00:15:04 +00001427 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001428 << Name << computeDeclContext(SS, false) << Corrected
1429 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001430 return true;
1431 }
Douglas Gregor25363982010-01-01 00:15:04 +00001432 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001433 }
1434
1435 // Emit a special diagnostic for failed member lookups.
1436 // FIXME: computing the declaration context might fail here (?)
1437 if (!SS.isEmpty()) {
1438 Diag(R.getNameLoc(), diag::err_no_member)
1439 << Name << computeDeclContext(SS, false)
1440 << SS.getRange();
1441 return true;
1442 }
1443
John McCalld681c392009-12-16 08:11:27 +00001444 // Give up, we can't recover.
1445 Diag(R.getNameLoc(), diagnostic) << Name;
1446 return true;
1447}
1448
Douglas Gregor05fcf842010-11-02 20:36:02 +00001449ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1450 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001451 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1452 if (!IDecl)
1453 return 0;
1454 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1455 if (!ClassImpDecl)
1456 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001457 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001458 if (!property)
1459 return 0;
1460 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001461 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1462 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001463 return 0;
1464 return property;
1465}
1466
Douglas Gregor05fcf842010-11-02 20:36:02 +00001467bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1468 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1469 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1470 if (!IDecl)
1471 return false;
1472 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1473 if (!ClassImpDecl)
1474 return false;
1475 if (ObjCPropertyImplDecl *PIDecl
1476 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1477 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1478 PIDecl->getPropertyIvarDecl())
1479 return false;
1480
1481 return true;
1482}
1483
Fariborz Jahanian18722982010-07-17 00:59:30 +00001484static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001485 LookupResult &Lookup,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001486 IdentifierInfo *II,
1487 SourceLocation NameLoc) {
1488 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001489 bool LookForIvars;
1490 if (Lookup.empty())
1491 LookForIvars = true;
1492 else if (CurMeth->isClassMethod())
1493 LookForIvars = false;
1494 else
1495 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001496 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1497 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001498 if (!LookForIvars)
1499 return 0;
1500
Fariborz Jahanian18722982010-07-17 00:59:30 +00001501 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1502 if (!IDecl)
1503 return 0;
1504 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001505 if (!ClassImpDecl)
1506 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001507 bool DynamicImplSeen = false;
1508 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1509 if (!property)
1510 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001511 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001512 DynamicImplSeen =
1513 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001514 // property implementation has a designated ivar. No need to assume a new
1515 // one.
1516 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1517 return 0;
1518 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001519 if (!DynamicImplSeen) {
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001520 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1521 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001522 NameLoc, NameLoc,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001523 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001524 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001525 (Expr *)0, true);
1526 ClassImpDecl->addDecl(Ivar);
1527 IDecl->makeDeclVisibleInContext(Ivar, false);
1528 property->setPropertyIvarDecl(Ivar);
1529 return Ivar;
1530 }
1531 return 0;
1532}
1533
John McCalldadc5752010-08-24 06:29:42 +00001534ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001535 CXXScopeSpec &SS,
1536 UnqualifiedId &Id,
1537 bool HasTrailingLParen,
1538 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001539 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1540 "cannot be direct & operand and have a trailing lparen");
1541
1542 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001543 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001544
John McCall10eae182009-11-30 22:42:35 +00001545 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001546
1547 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001548 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001549 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001550 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001551
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001552 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001553 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001554 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001555
John McCalle66edc12009-11-24 19:00:30 +00001556 // C++ [temp.dep.expr]p3:
1557 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001558 // -- an identifier that was declared with a dependent type,
1559 // (note: handled after lookup)
1560 // -- a template-id that is dependent,
1561 // (note: handled in BuildTemplateIdExpr)
1562 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001563 // -- a nested-name-specifier that contains a class-name that
1564 // names a dependent type.
1565 // Determine whether this is a member of an unknown specialization;
1566 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001567 bool DependentID = false;
1568 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1569 Name.getCXXNameType()->isDependentType()) {
1570 DependentID = true;
1571 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001572 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001573 if (RequireCompleteDeclContext(SS, DC))
1574 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001575 } else {
1576 DependentID = true;
1577 }
1578 }
1579
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001580 if (DependentID)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001581 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001582 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001583
Fariborz Jahanian86151342010-07-22 23:33:21 +00001584 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001585 // Perform the required lookup.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001586 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001587 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001588 // Lookup the template name again to correctly establish the context in
1589 // which it was found. This is really unfortunate as we already did the
1590 // lookup to determine that it was a template name in the first place. If
1591 // this becomes a performance hit, we can work harder to preserve those
1592 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001593 bool MemberOfUnknownSpecialization;
1594 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1595 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001596
1597 if (MemberOfUnknownSpecialization ||
1598 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1599 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1600 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001601 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001602 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001603 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001604
Douglas Gregora5226932011-02-04 13:35:07 +00001605 // If the result might be in a dependent base class, this is a dependent
1606 // id-expression.
1607 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1608 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1609 TemplateArgs);
1610
John McCalle66edc12009-11-24 19:00:30 +00001611 // If this reference is in an Objective-C method, then we need to do
1612 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001613 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001614 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001615 if (E.isInvalid())
1616 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001617
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001618 if (Expr *Ex = E.takeAs<Expr>())
1619 return Owned(Ex);
1620
1621 // Synthesize ivars lazily.
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001622 if (getLangOptions().ObjCDefaultSynthProperties &&
1623 getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001624 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1625 if (const ObjCPropertyDecl *Property =
1626 canSynthesizeProvisionalIvar(II)) {
1627 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1628 Diag(Property->getLocation(), diag::note_property_declare);
1629 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001630 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1631 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001632 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001633 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001634 // for further use, this must be set to false if in class method.
1635 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001636 }
Chris Lattner59a25942008-03-31 00:36:02 +00001637 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001638
John McCalle66edc12009-11-24 19:00:30 +00001639 if (R.isAmbiguous())
1640 return ExprError();
1641
Douglas Gregor171c45a2009-02-18 21:56:37 +00001642 // Determine whether this name might be a candidate for
1643 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001644 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001645
John McCalle66edc12009-11-24 19:00:30 +00001646 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001647 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001648 // in C90, extension in C99, forbidden in C++).
1649 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1650 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1651 if (D) R.addDecl(D);
1652 }
1653
1654 // If this name wasn't predeclared and if this is not a function
1655 // call, diagnose the problem.
1656 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001657 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001658 return ExprError();
1659
1660 assert(!R.empty() &&
1661 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001662
1663 // If we found an Objective-C instance variable, let
1664 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001665 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001666 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1667 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001668 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001669 assert(E.isInvalid() || E.get());
1670 return move(E);
1671 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001672 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001673 }
Mike Stump11289f42009-09-09 15:08:12 +00001674
John McCalle66edc12009-11-24 19:00:30 +00001675 // This is guaranteed from this point on.
1676 assert(!R.empty() || ADL);
1677
John McCall2d74de92009-12-01 22:10:20 +00001678 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001679 // C++ [class.mfct.non-static]p3:
1680 // When an id-expression that is not part of a class member access
1681 // syntax and not used to form a pointer to member is used in the
1682 // body of a non-static member function of class X, if name lookup
1683 // resolves the name in the id-expression to a non-static non-type
1684 // member of some class C, the id-expression is transformed into a
1685 // class member access expression using (*this) as the
1686 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001687 //
1688 // But we don't actually need to do this for '&' operands if R
1689 // resolved to a function or overloaded function set, because the
1690 // expression is ill-formed if it actually works out to be a
1691 // non-static member function:
1692 //
1693 // C++ [expr.ref]p4:
1694 // Otherwise, if E1.E2 refers to a non-static member function. . .
1695 // [t]he expression can be used only as the left-hand operand of a
1696 // member function call.
1697 //
1698 // There are other safeguards against such uses, but it's important
1699 // to get this right here so that we don't end up making a
1700 // spuriously dependent expression if we're inside a dependent
1701 // instance method.
John McCall57500772009-12-16 12:17:52 +00001702 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001703 bool MightBeImplicitMember;
1704 if (!isAddressOfOperand)
1705 MightBeImplicitMember = true;
1706 else if (!SS.isEmpty())
1707 MightBeImplicitMember = false;
1708 else if (R.isOverloadedResult())
1709 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001710 else if (R.isUnresolvableResult())
1711 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001712 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001713 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1714 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001715
1716 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001717 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001718 }
1719
John McCalle66edc12009-11-24 19:00:30 +00001720 if (TemplateArgs)
1721 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001722
John McCalle66edc12009-11-24 19:00:30 +00001723 return BuildDeclarationNameExpr(SS, R, ADL);
1724}
1725
John McCall57500772009-12-16 12:17:52 +00001726/// Builds an expression which might be an implicit member expression.
John McCalldadc5752010-08-24 06:29:42 +00001727ExprResult
John McCall57500772009-12-16 12:17:52 +00001728Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1729 LookupResult &R,
1730 const TemplateArgumentListInfo *TemplateArgs) {
1731 switch (ClassifyImplicitMemberAccess(*this, R)) {
1732 case IMA_Instance:
1733 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1734
John McCall57500772009-12-16 12:17:52 +00001735 case IMA_Mixed:
1736 case IMA_Mixed_Unrelated:
1737 case IMA_Unresolved:
1738 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1739
1740 case IMA_Static:
1741 case IMA_Mixed_StaticContext:
1742 case IMA_Unresolved_StaticContext:
1743 if (TemplateArgs)
1744 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1745 return BuildDeclarationNameExpr(SS, R, false);
1746
1747 case IMA_Error_StaticContext:
1748 case IMA_Error_Unrelated:
John McCallf3a88602011-02-03 08:15:49 +00001749 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
1750 R.getLookupNameInfo());
John McCall57500772009-12-16 12:17:52 +00001751 return ExprError();
1752 }
1753
1754 llvm_unreachable("unexpected instance member access kind");
1755 return ExprError();
1756}
1757
John McCall10eae182009-11-30 22:42:35 +00001758/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1759/// declaration name, generally during template instantiation.
1760/// There's a large number of things which don't need to be done along
1761/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001762ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001763Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001764 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001765 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001766 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001767 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001768
John McCall0b66eb32010-05-01 00:40:08 +00001769 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001770 return ExprError();
1771
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001772 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001773 LookupQualifiedName(R, DC);
1774
1775 if (R.isAmbiguous())
1776 return ExprError();
1777
1778 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001779 Diag(NameInfo.getLoc(), diag::err_no_member)
1780 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001781 return ExprError();
1782 }
1783
1784 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1785}
1786
1787/// LookupInObjCMethod - The parser has read a name in, and Sema has
1788/// detected that we're currently inside an ObjC method. Perform some
1789/// additional lookup.
1790///
1791/// Ideally, most of this would be done by lookup, but there's
1792/// actually quite a lot of extra work involved.
1793///
1794/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001795ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001796Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001797 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001798 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001799 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001800
John McCalle66edc12009-11-24 19:00:30 +00001801 // There are two cases to handle here. 1) scoped lookup could have failed,
1802 // in which case we should look for an ivar. 2) scoped lookup could have
1803 // found a decl, but that decl is outside the current instance method (i.e.
1804 // a global variable). In these two cases, we do a lookup for an ivar with
1805 // this name, if the lookup sucedes, we replace it our current decl.
1806
1807 // If we're in a class method, we don't normally want to look for
1808 // ivars. But if we don't find anything else, and there's an
1809 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001810 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001811
1812 bool LookForIvars;
1813 if (Lookup.empty())
1814 LookForIvars = true;
1815 else if (IsClassMethod)
1816 LookForIvars = false;
1817 else
1818 LookForIvars = (Lookup.isSingleResult() &&
1819 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001820 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001821 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001822 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001823 ObjCInterfaceDecl *ClassDeclared;
1824 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1825 // Diagnose using an ivar in a class method.
1826 if (IsClassMethod)
1827 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1828 << IV->getDeclName());
1829
1830 // If we're referencing an invalid decl, just return this as a silent
1831 // error node. The error diagnostic was already emitted on the decl.
1832 if (IV->isInvalidDecl())
1833 return ExprError();
1834
1835 // Check if referencing a field with __attribute__((deprecated)).
1836 if (DiagnoseUseOfDecl(IV, Loc))
1837 return ExprError();
1838
1839 // Diagnose the use of an ivar outside of the declaring class.
1840 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1841 ClassDeclared != IFace)
1842 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1843
1844 // FIXME: This should use a new expr for a direct reference, don't
1845 // turn this into Self->ivar, just return a BareIVarExpr or something.
1846 IdentifierInfo &II = Context.Idents.get("self");
1847 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001848 SelfName.setIdentifier(&II, SourceLocation());
John McCalle66edc12009-11-24 19:00:30 +00001849 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001850 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001851 SelfName, false, false);
1852 if (SelfExpr.isInvalid())
1853 return ExprError();
1854
John McCall27584242010-12-06 20:48:59 +00001855 Expr *SelfE = SelfExpr.take();
1856 DefaultLvalueConversion(SelfE);
1857
John McCalle66edc12009-11-24 19:00:30 +00001858 MarkDeclarationReferenced(Loc, IV);
1859 return Owned(new (Context)
1860 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John McCall27584242010-12-06 20:48:59 +00001861 SelfE, true, true));
John McCalle66edc12009-11-24 19:00:30 +00001862 }
Chris Lattner87313662010-04-12 05:10:17 +00001863 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001864 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001865 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001866 ObjCInterfaceDecl *ClassDeclared;
1867 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1868 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1869 IFace == ClassDeclared)
1870 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1871 }
1872 }
1873
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001874 if (Lookup.empty() && II && AllowBuiltinCreation) {
1875 // FIXME. Consolidate this with similar code in LookupName.
1876 if (unsigned BuiltinID = II->getBuiltinID()) {
1877 if (!(getLangOptions().CPlusPlus &&
1878 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1879 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1880 S, Lookup.isForRedeclaration(),
1881 Lookup.getNameLoc());
1882 if (D) Lookup.addDecl(D);
1883 }
1884 }
1885 }
John McCalle66edc12009-11-24 19:00:30 +00001886 // Sentinel value saying that we didn't do anything special.
1887 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001888}
John McCalld14a8642009-11-21 08:51:07 +00001889
John McCall16df1e52010-03-30 21:47:33 +00001890/// \brief Cast a base object to a member's actual type.
1891///
1892/// Logically this happens in three phases:
1893///
1894/// * First we cast from the base type to the naming class.
1895/// The naming class is the class into which we were looking
1896/// when we found the member; it's the qualifier type if a
1897/// qualifier was provided, and otherwise it's the base type.
1898///
1899/// * Next we cast from the naming class to the declaring class.
1900/// If the member we found was brought into a class's scope by
1901/// a using declaration, this is that class; otherwise it's
1902/// the class declaring the member.
1903///
1904/// * Finally we cast from the declaring class to the "true"
1905/// declaring class of the member. This conversion does not
1906/// obey access control.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001907bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001908Sema::PerformObjectMemberConversion(Expr *&From,
1909 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001910 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001911 NamedDecl *Member) {
1912 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1913 if (!RD)
1914 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001915
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001916 QualType DestRecordType;
1917 QualType DestType;
1918 QualType FromRecordType;
1919 QualType FromType = From->getType();
1920 bool PointerConversions = false;
1921 if (isa<FieldDecl>(Member)) {
1922 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001923
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001924 if (FromType->getAs<PointerType>()) {
1925 DestType = Context.getPointerType(DestRecordType);
1926 FromRecordType = FromType->getPointeeType();
1927 PointerConversions = true;
1928 } else {
1929 DestType = DestRecordType;
1930 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001931 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001932 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1933 if (Method->isStatic())
1934 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001935
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001936 DestType = Method->getThisType(Context);
1937 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001938
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001939 if (FromType->getAs<PointerType>()) {
1940 FromRecordType = FromType->getPointeeType();
1941 PointerConversions = true;
1942 } else {
1943 FromRecordType = FromType;
1944 DestType = DestRecordType;
1945 }
1946 } else {
1947 // No conversion necessary.
1948 return false;
1949 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001950
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001951 if (DestType->isDependentType() || FromType->isDependentType())
1952 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001953
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001954 // If the unqualified types are the same, no conversion is necessary.
1955 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1956 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001957
John McCall16df1e52010-03-30 21:47:33 +00001958 SourceRange FromRange = From->getSourceRange();
1959 SourceLocation FromLoc = FromRange.getBegin();
1960
John McCall2536c6d2010-08-25 10:28:54 +00001961 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001962
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001963 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001964 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001965 // class name.
1966 //
1967 // If the member was a qualified name and the qualified referred to a
1968 // specific base subobject type, we'll cast to that intermediate type
1969 // first and then to the object in which the member is declared. That allows
1970 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1971 //
1972 // class Base { public: int x; };
1973 // class Derived1 : public Base { };
1974 // class Derived2 : public Base { };
1975 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1976 //
1977 // void VeryDerived::f() {
1978 // x = 17; // error: ambiguous base subobjects
1979 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1980 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001981 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00001982 QualType QType = QualType(Qualifier->getAsType(), 0);
1983 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1984 assert(QType->isRecordType() && "lookup done with non-record type");
1985
1986 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1987
1988 // In C++98, the qualifier type doesn't actually have to be a base
1989 // type of the object type, in which case we just ignore it.
1990 // Otherwise build the appropriate casts.
1991 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00001992 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001993 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001994 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00001995 return true;
1996
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001997 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00001998 QType = Context.getPointerType(QType);
John McCall2536c6d2010-08-25 10:28:54 +00001999 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2000 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00002001
2002 FromType = QType;
2003 FromRecordType = QRecordType;
2004
2005 // If the qualifier type was the same as the destination type,
2006 // we're done.
2007 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2008 return false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002009 }
2010 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002011
John McCall16df1e52010-03-30 21:47:33 +00002012 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002013
John McCall16df1e52010-03-30 21:47:33 +00002014 // If we actually found the member through a using declaration, cast
2015 // down to the using declaration's type.
2016 //
2017 // Pointer equality is fine here because only one declaration of a
2018 // class ever has member declarations.
2019 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2020 assert(isa<UsingShadowDecl>(FoundDecl));
2021 QualType URecordType = Context.getTypeDeclType(
2022 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2023
2024 // We only need to do this if the naming-class to declaring-class
2025 // conversion is non-trivial.
2026 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2027 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002028 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002029 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002030 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00002031 return true;
Alexis Huntc46382e2010-04-28 23:02:27 +00002032
John McCall16df1e52010-03-30 21:47:33 +00002033 QualType UType = URecordType;
2034 if (PointerConversions)
2035 UType = Context.getPointerType(UType);
John McCalle3027922010-08-25 11:45:40 +00002036 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00002037 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00002038 FromType = UType;
2039 FromRecordType = URecordType;
2040 }
2041
2042 // We don't do access control for the conversion from the
2043 // declaring class to the true declaring class.
2044 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002045 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002046
John McCallcf142162010-08-07 06:22:56 +00002047 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002048 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2049 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002050 IgnoreAccess))
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002051 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002052
John McCalle3027922010-08-25 11:45:40 +00002053 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00002054 VK, &BasePath);
Fariborz Jahanian3f150832009-07-29 19:40:11 +00002055 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002056}
Douglas Gregor3256d042009-06-30 15:47:41 +00002057
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002058/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00002059static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00002060 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalla8ae2222010-04-06 21:38:20 +00002061 DeclAccessPair FoundDecl,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002062 const DeclarationNameInfo &MemberNameInfo,
2063 QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +00002064 ExprValueKind VK, ExprObjectKind OK,
John McCalle66edc12009-11-24 19:00:30 +00002065 const TemplateArgumentListInfo *TemplateArgs = 0) {
Douglas Gregorea972d32011-02-28 21:54:11 +00002066 return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002067 Member, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002068 TemplateArgs, Ty, VK, OK);
Douglas Gregorc1905232009-08-26 22:36:53 +00002069}
2070
John McCallfeb624a2010-11-23 20:48:44 +00002071static ExprResult
2072BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2073 const CXXScopeSpec &SS, FieldDecl *Field,
2074 DeclAccessPair FoundDecl,
2075 const DeclarationNameInfo &MemberNameInfo) {
2076 // x.a is an l-value if 'a' has a reference type. Otherwise:
2077 // x.a is an l-value/x-value/pr-value if the base is (and note
2078 // that *x is always an l-value), except that if the base isn't
2079 // an ordinary object then we must have an rvalue.
2080 ExprValueKind VK = VK_LValue;
2081 ExprObjectKind OK = OK_Ordinary;
2082 if (!IsArrow) {
2083 if (BaseExpr->getObjectKind() == OK_Ordinary)
2084 VK = BaseExpr->getValueKind();
2085 else
2086 VK = VK_RValue;
2087 }
2088 if (VK != VK_RValue && Field->isBitField())
2089 OK = OK_BitField;
2090
2091 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2092 QualType MemberType = Field->getType();
2093 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2094 MemberType = Ref->getPointeeType();
2095 VK = VK_LValue;
2096 } else {
2097 QualType BaseType = BaseExpr->getType();
2098 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2099
2100 Qualifiers BaseQuals = BaseType.getQualifiers();
2101
2102 // GC attributes are never picked up by members.
2103 BaseQuals.removeObjCGCAttr();
2104
2105 // CVR attributes from the base are picked up by members,
2106 // except that 'mutable' members don't pick up 'const'.
2107 if (Field->isMutable()) BaseQuals.removeConst();
2108
2109 Qualifiers MemberQuals
2110 = S.Context.getCanonicalType(MemberType).getQualifiers();
2111
2112 // TR 18037 does not allow fields to be declared with address spaces.
2113 assert(!MemberQuals.hasAddressSpace());
2114
2115 Qualifiers Combined = BaseQuals + MemberQuals;
2116 if (Combined != MemberQuals)
2117 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2118 }
2119
2120 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
2121 if (S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2122 FoundDecl, Field))
2123 return ExprError();
2124 return S.Owned(BuildMemberExpr(S.Context, BaseExpr, IsArrow, SS,
2125 Field, FoundDecl, MemberNameInfo,
2126 MemberType, VK, OK));
2127}
2128
John McCall2d74de92009-12-01 22:10:20 +00002129/// Builds an implicit member access expression. The current context
2130/// is known to be an instance method, and the given unqualified lookup
2131/// set is known to contain only instance members, at least one of which
2132/// is from an appropriate type.
John McCalldadc5752010-08-24 06:29:42 +00002133ExprResult
John McCall2d74de92009-12-01 22:10:20 +00002134Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2135 LookupResult &R,
2136 const TemplateArgumentListInfo *TemplateArgs,
2137 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00002138 assert(!R.empty() && !R.isAmbiguous());
2139
John McCallf3a88602011-02-03 08:15:49 +00002140 SourceLocation loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00002141
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002142 // We may have found a field within an anonymous union or struct
2143 // (C++ [class.union]).
John McCalle66edc12009-11-24 19:00:30 +00002144 // FIXME: template-ids inside anonymous structs?
Francois Pichet783dd6e2010-11-21 06:08:52 +00002145 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCallf3a88602011-02-03 08:15:49 +00002146 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002147
John McCallf3a88602011-02-03 08:15:49 +00002148 // If this is known to be an instance access, go ahead and build an
2149 // implicit 'this' expression now.
John McCall2d74de92009-12-01 22:10:20 +00002150 // 'this' expression now.
John McCallf3a88602011-02-03 08:15:49 +00002151 CXXMethodDecl *method = tryCaptureCXXThis();
2152 assert(method && "didn't correctly pre-flight capture of 'this'");
2153
2154 QualType thisType = method->getThisType(Context);
2155 Expr *baseExpr = 0; // null signifies implicit access
John McCall2d74de92009-12-01 22:10:20 +00002156 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00002157 SourceLocation Loc = R.getNameLoc();
2158 if (SS.getRange().isValid())
2159 Loc = SS.getRange().getBegin();
John McCallf3a88602011-02-03 08:15:49 +00002160 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002161 }
2162
John McCallf3a88602011-02-03 08:15:49 +00002163 return BuildMemberReferenceExpr(baseExpr, thisType,
John McCall2d74de92009-12-01 22:10:20 +00002164 /*OpLoc*/ SourceLocation(),
2165 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00002166 SS,
2167 /*FirstQualifierInScope*/ 0,
2168 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00002169}
2170
John McCalle66edc12009-11-24 19:00:30 +00002171bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002172 const LookupResult &R,
2173 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002174 // Only when used directly as the postfix-expression of a call.
2175 if (!HasTrailingLParen)
2176 return false;
2177
2178 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002179 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002180 return false;
2181
2182 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002183 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002184 return false;
2185
2186 // Turn off ADL when we find certain kinds of declarations during
2187 // normal lookup:
2188 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2189 NamedDecl *D = *I;
2190
2191 // C++0x [basic.lookup.argdep]p3:
2192 // -- a declaration of a class member
2193 // Since using decls preserve this property, we check this on the
2194 // original decl.
John McCall57500772009-12-16 12:17:52 +00002195 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002196 return false;
2197
2198 // C++0x [basic.lookup.argdep]p3:
2199 // -- a block-scope function declaration that is not a
2200 // using-declaration
2201 // NOTE: we also trigger this for function templates (in fact, we
2202 // don't check the decl type at all, since all other decl types
2203 // turn off ADL anyway).
2204 if (isa<UsingShadowDecl>(D))
2205 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2206 else if (D->getDeclContext()->isFunctionOrMethod())
2207 return false;
2208
2209 // C++0x [basic.lookup.argdep]p3:
2210 // -- a declaration that is neither a function or a function
2211 // template
2212 // And also for builtin functions.
2213 if (isa<FunctionDecl>(D)) {
2214 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2215
2216 // But also builtin functions.
2217 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2218 return false;
2219 } else if (!isa<FunctionTemplateDecl>(D))
2220 return false;
2221 }
2222
2223 return true;
2224}
2225
2226
John McCalld14a8642009-11-21 08:51:07 +00002227/// Diagnoses obvious problems with the use of the given declaration
2228/// as an expression. This is only actually called for lookups that
2229/// were not overloaded, and it doesn't promise that the declaration
2230/// will in fact be used.
2231static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2232 if (isa<TypedefDecl>(D)) {
2233 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2234 return true;
2235 }
2236
2237 if (isa<ObjCInterfaceDecl>(D)) {
2238 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2239 return true;
2240 }
2241
2242 if (isa<NamespaceDecl>(D)) {
2243 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2244 return true;
2245 }
2246
2247 return false;
2248}
2249
John McCalldadc5752010-08-24 06:29:42 +00002250ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002251Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002252 LookupResult &R,
2253 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002254 // If this is a single, fully-resolved result and we don't need ADL,
2255 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002256 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002257 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2258 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002259
2260 // We only need to check the declaration if there's exactly one
2261 // result, because in the overloaded case the results can only be
2262 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002263 if (R.isSingleResult() &&
2264 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002265 return ExprError();
2266
John McCall58cc69d2010-01-27 01:50:18 +00002267 // Otherwise, just build an unresolved lookup expression. Suppress
2268 // any lookup-related diagnostics; we'll hash these out later, when
2269 // we've picked a target.
2270 R.suppressDiagnostics();
2271
John McCalld14a8642009-11-21 08:51:07 +00002272 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002273 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002274 SS.getWithLocInContext(Context),
2275 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002276 NeedsADL, R.isOverloadedResult(),
2277 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002278
2279 return Owned(ULE);
2280}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002281
John McCalld14a8642009-11-21 08:51:07 +00002282/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002283ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002284Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002285 const DeclarationNameInfo &NameInfo,
2286 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002287 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002288 assert(!isa<FunctionTemplateDecl>(D) &&
2289 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002290
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002291 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002292 if (CheckDeclInExpr(*this, Loc, D))
2293 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002294
Douglas Gregore7488b92009-12-01 16:58:18 +00002295 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2296 // Specifically diagnose references to class templates that are missing
2297 // a template argument list.
2298 Diag(Loc, diag::err_template_decl_ref)
2299 << Template << SS.getRange();
2300 Diag(Template->getLocation(), diag::note_template_decl_here);
2301 return ExprError();
2302 }
2303
2304 // Make sure that we're referring to a value.
2305 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2306 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002307 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002308 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002309 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002310 return ExprError();
2311 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002312
Douglas Gregor171c45a2009-02-18 21:56:37 +00002313 // Check whether this declaration can be used. Note that we suppress
2314 // this check when we're going to perform argument-dependent lookup
2315 // on this function name, because this might not be the function
2316 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002317 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002318 return ExprError();
2319
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002320 // Only create DeclRefExpr's for valid Decl's.
2321 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002322 return ExprError();
2323
John McCallf3a88602011-02-03 08:15:49 +00002324 // Handle members of anonymous structs and unions. If we got here,
2325 // and the reference is to a class member indirect field, then this
2326 // must be the subject of a pointer-to-member expression.
2327 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2328 if (!indirectField->isCXXClassMember())
2329 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2330 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002331
Chris Lattner2a9d9892008-10-20 05:16:36 +00002332 // If the identifier reference is inside a block, and it refers to a value
2333 // that is outside the block, create a BlockDeclRefExpr instead of a
2334 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2335 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002336 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002337 // We do not do this for things like enum constants, global variables, etc,
2338 // as they do not get snapshotted.
2339 //
John McCall351762c2011-02-07 10:33:21 +00002340 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002341 case CR_Error:
2342 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002343
John McCallc63de662011-02-02 13:00:07 +00002344 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002345 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2346 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2347
2348 case CR_CaptureByRef:
2349 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2350 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002351
2352 case CR_NoCapture: {
2353 // If this reference is not in a block or if the referenced
2354 // variable is within the block, create a normal DeclRefExpr.
2355
2356 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002357 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002358
2359 switch (D->getKind()) {
2360 // Ignore all the non-ValueDecl kinds.
2361#define ABSTRACT_DECL(kind)
2362#define VALUE(type, base)
2363#define DECL(type, base) \
2364 case Decl::type:
2365#include "clang/AST/DeclNodes.inc"
2366 llvm_unreachable("invalid value decl kind");
2367 return ExprError();
2368
2369 // These shouldn't make it here.
2370 case Decl::ObjCAtDefsField:
2371 case Decl::ObjCIvar:
2372 llvm_unreachable("forming non-member reference to ivar?");
2373 return ExprError();
2374
2375 // Enum constants are always r-values and never references.
2376 // Unresolved using declarations are dependent.
2377 case Decl::EnumConstant:
2378 case Decl::UnresolvedUsingValue:
2379 valueKind = VK_RValue;
2380 break;
2381
2382 // Fields and indirect fields that got here must be for
2383 // pointer-to-member expressions; we just call them l-values for
2384 // internal consistency, because this subexpression doesn't really
2385 // exist in the high-level semantics.
2386 case Decl::Field:
2387 case Decl::IndirectField:
2388 assert(getLangOptions().CPlusPlus &&
2389 "building reference to field in C?");
2390
2391 // These can't have reference type in well-formed programs, but
2392 // for internal consistency we do this anyway.
2393 type = type.getNonReferenceType();
2394 valueKind = VK_LValue;
2395 break;
2396
2397 // Non-type template parameters are either l-values or r-values
2398 // depending on the type.
2399 case Decl::NonTypeTemplateParm: {
2400 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2401 type = reftype->getPointeeType();
2402 valueKind = VK_LValue; // even if the parameter is an r-value reference
2403 break;
2404 }
2405
2406 // For non-references, we need to strip qualifiers just in case
2407 // the template parameter was declared as 'const int' or whatever.
2408 valueKind = VK_RValue;
2409 type = type.getUnqualifiedType();
2410 break;
2411 }
2412
2413 case Decl::Var:
2414 // In C, "extern void blah;" is valid and is an r-value.
2415 if (!getLangOptions().CPlusPlus &&
2416 !type.hasQualifiers() &&
2417 type->isVoidType()) {
2418 valueKind = VK_RValue;
2419 break;
2420 }
2421 // fallthrough
2422
2423 case Decl::ImplicitParam:
2424 case Decl::ParmVar:
2425 // These are always l-values.
2426 valueKind = VK_LValue;
2427 type = type.getNonReferenceType();
2428 break;
2429
2430 case Decl::Function: {
2431 // Functions are l-values in C++.
2432 if (getLangOptions().CPlusPlus) {
2433 valueKind = VK_LValue;
2434 break;
2435 }
2436
2437 // C99 DR 316 says that, if a function type comes from a
2438 // function definition (without a prototype), that type is only
2439 // used for checking compatibility. Therefore, when referencing
2440 // the function, we pretend that we don't have the full function
2441 // type.
2442 if (!cast<FunctionDecl>(VD)->hasPrototype())
2443 if (const FunctionProtoType *proto = type->getAs<FunctionProtoType>())
2444 type = Context.getFunctionNoProtoType(proto->getResultType(),
2445 proto->getExtInfo());
2446
2447 // Functions are r-values in C.
2448 valueKind = VK_RValue;
2449 break;
2450 }
2451
2452 case Decl::CXXMethod:
2453 // C++ methods are l-values if static, r-values if non-static.
2454 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2455 valueKind = VK_LValue;
2456 break;
2457 }
2458 // fallthrough
2459
2460 case Decl::CXXConversion:
2461 case Decl::CXXDestructor:
2462 case Decl::CXXConstructor:
2463 valueKind = VK_RValue;
2464 break;
2465 }
2466
2467 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2468 }
2469
John McCallc63de662011-02-02 13:00:07 +00002470 }
John McCall7decc9e2010-11-18 06:31:45 +00002471
John McCall351762c2011-02-07 10:33:21 +00002472 llvm_unreachable("unknown capture result");
2473 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002474}
Chris Lattnere168f762006-11-10 05:29:30 +00002475
John McCalldadc5752010-08-24 06:29:42 +00002476ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Sebastian Redlffbcf962009-01-18 18:53:16 +00002477 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002478 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002479
Chris Lattnere168f762006-11-10 05:29:30 +00002480 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002481 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002482 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2483 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2484 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002485 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002486
Chris Lattnera81a0272008-01-12 08:14:25 +00002487 // Pre-defined identifiers are of type char[x], where x is the length of the
2488 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002489
Anders Carlsson2fb08242009-09-08 18:24:21 +00002490 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002491 if (!currentDecl && getCurBlock())
2492 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002493 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002494 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002495 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002496 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002497
Anders Carlsson0b209a82009-09-11 01:22:35 +00002498 QualType ResTy;
2499 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2500 ResTy = Context.DependentTy;
2501 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002502 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002503
Anders Carlsson0b209a82009-09-11 01:22:35 +00002504 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002505 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002506 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2507 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002508 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002509}
2510
John McCalldadc5752010-08-24 06:29:42 +00002511ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002512 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002513 bool Invalid = false;
2514 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2515 if (Invalid)
2516 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002517
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002518 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2519 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00002520 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002521 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002522
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002523 QualType Ty;
2524 if (!getLangOptions().CPlusPlus)
2525 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2526 else if (Literal.isWide())
2527 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002528 else if (Literal.isMultiChar())
2529 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002530 else
2531 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002532
Sebastian Redl20614a72009-01-20 22:23:13 +00002533 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2534 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002535 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002536}
2537
John McCalldadc5752010-08-24 06:29:42 +00002538ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002539 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002540 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2541 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002542 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002543 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002544 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002545 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002546 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002547
Chris Lattner23b7eb62007-06-15 23:05:46 +00002548 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002549 // Add padding so that NumericLiteralParser can overread by one character.
2550 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002551 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002552
Chris Lattner67ca9252007-05-21 01:08:44 +00002553 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002554 bool Invalid = false;
2555 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2556 if (Invalid)
2557 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002558
Mike Stump11289f42009-09-09 15:08:12 +00002559 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002560 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002561 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002562 return ExprError();
2563
Chris Lattner1c20a172007-08-26 03:42:43 +00002564 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002565
Chris Lattner1c20a172007-08-26 03:42:43 +00002566 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002567 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002568 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002569 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002570 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002571 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002572 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002573 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002574
2575 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2576
John McCall53b93a02009-12-24 09:08:04 +00002577 using llvm::APFloat;
2578 APFloat Val(Format);
2579
2580 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002581
2582 // Overflow is always an error, but underflow is only an error if
2583 // we underflowed to zero (APFloat reports denormals as underflow).
2584 if ((result & APFloat::opOverflow) ||
2585 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002586 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002587 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002588 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002589 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002590 APFloat::getLargest(Format).toString(buffer);
2591 } else {
John McCall62abc942010-02-26 23:35:57 +00002592 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002593 APFloat::getSmallest(Format).toString(buffer);
2594 }
2595
2596 Diag(Tok.getLocation(), diagnostic)
2597 << Ty
2598 << llvm::StringRef(buffer.data(), buffer.size());
2599 }
2600
2601 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002602 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002603
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002604 if (Ty == Context.DoubleTy) {
2605 if (getLangOptions().SinglePrecisionConstants) {
2606 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2607 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2608 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
2609 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2610 }
2611 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002612 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002613 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002614 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002615 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002616
Neil Boothac582c52007-08-29 22:00:19 +00002617 // long long is a C99 feature.
2618 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002619 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002620 Diag(Tok.getLocation(), diag::ext_longlong);
2621
Chris Lattner67ca9252007-05-21 01:08:44 +00002622 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002623 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002624
Chris Lattner67ca9252007-05-21 01:08:44 +00002625 if (Literal.GetIntegerValue(ResultVal)) {
2626 // If this value didn't fit into uintmax_t, warn and force to ull.
2627 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002628 Ty = Context.UnsignedLongLongTy;
2629 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002630 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002631 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002632 // If this value fits into a ULL, try to figure out what else it fits into
2633 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002634
Chris Lattner67ca9252007-05-21 01:08:44 +00002635 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2636 // be an unsigned int.
2637 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2638
2639 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002640 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002641 if (!Literal.isLong && !Literal.isLongLong) {
2642 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002643 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002644
Chris Lattner67ca9252007-05-21 01:08:44 +00002645 // Does it fit in a unsigned int?
2646 if (ResultVal.isIntN(IntSize)) {
2647 // Does it fit in a signed int?
2648 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002649 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002650 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002651 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002652 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002653 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002654 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002655
Chris Lattner67ca9252007-05-21 01:08:44 +00002656 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002657 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002658 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002659
Chris Lattner67ca9252007-05-21 01:08:44 +00002660 // Does it fit in a unsigned long?
2661 if (ResultVal.isIntN(LongSize)) {
2662 // Does it fit in a signed long?
2663 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002664 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002665 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002666 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002667 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002668 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002669 }
2670
Chris Lattner67ca9252007-05-21 01:08:44 +00002671 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002672 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002673 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002674
Chris Lattner67ca9252007-05-21 01:08:44 +00002675 // Does it fit in a unsigned long long?
2676 if (ResultVal.isIntN(LongLongSize)) {
2677 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002678 // To be compatible with MSVC, hex integer literals ending with the
2679 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002680 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2681 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002682 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002683 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002684 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002685 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002686 }
2687 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002688
Chris Lattner67ca9252007-05-21 01:08:44 +00002689 // If we still couldn't decide a type, we probably have something that
2690 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002691 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002692 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002693 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002694 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002695 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002696
Chris Lattner55258cf2008-05-09 05:59:00 +00002697 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002698 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002699 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002700 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002701 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002702
Chris Lattner1c20a172007-08-26 03:42:43 +00002703 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2704 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002705 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002706 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002707
2708 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002709}
2710
John McCalldadc5752010-08-24 06:29:42 +00002711ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002712 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002713 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002714 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002715}
2716
Steve Naroff71b59a92007-06-04 22:22:31 +00002717/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00002718/// See C99 6.3.2.1p[2-4] for more details.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002719bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2720 SourceLocation OpLoc,
2721 SourceRange ExprRange,
2722 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002723 if (exprType->isDependentType())
2724 return false;
2725
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002726 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2727 // the result is the size of the referenced type."
2728 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2729 // result shall be the alignment of the referenced type."
2730 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2731 exprType = Ref->getPointeeType();
2732
Peter Collingbournee190dee2011-03-11 19:24:49 +00002733 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2734 // scalar or vector data type argument..."
2735 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2736 // type (C99 6.2.5p18) or void.
2737 if (ExprKind == UETT_VecStep) {
2738 if (!(exprType->isArithmeticType() || exprType->isVoidType() ||
2739 exprType->isVectorType())) {
2740 Diag(OpLoc, diag::err_vecstep_non_scalar_vector_type)
2741 << exprType << ExprRange;
2742 return true;
2743 }
2744 }
2745
Steve Naroff043d45d2007-05-15 02:32:35 +00002746 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00002747 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002748 // alignof(function) is allowed as an extension.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002749 if (ExprKind == UETT_SizeOf)
2750 Diag(OpLoc, diag::ext_sizeof_function_type)
2751 << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00002752 return false;
2753 }
Mike Stump11289f42009-09-09 15:08:12 +00002754
Peter Collingbournee190dee2011-03-11 19:24:49 +00002755 // Allow sizeof(void)/alignof(void) as an extension. vec_step(void) is not
2756 // an extension, as void is a built-in scalar type (OpenCL 1.1 6.1.1).
Chris Lattnerb1355b12009-01-24 19:46:37 +00002757 if (exprType->isVoidType()) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002758 if (ExprKind != UETT_VecStep)
2759 Diag(OpLoc, diag::ext_sizeof_void_type)
2760 << ExprKind << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00002761 return false;
2762 }
Mike Stump11289f42009-09-09 15:08:12 +00002763
Chris Lattner62975a72009-04-24 00:30:45 +00002764 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002765 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002766 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002767 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002768
Chris Lattner62975a72009-04-24 00:30:45 +00002769 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCall8b07ec22010-05-15 11:32:37 +00002770 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002771 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002772 << exprType << (ExprKind == UETT_SizeOf)
2773 << ExprRange;
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002774 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00002775 }
Mike Stump11289f42009-09-09 15:08:12 +00002776
Chris Lattner62975a72009-04-24 00:30:45 +00002777 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002778}
2779
John McCall36e7fe32010-10-12 00:20:44 +00002780static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2781 SourceRange ExprRange) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002782 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002783
Mike Stump11289f42009-09-09 15:08:12 +00002784 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002785 if (isa<DeclRefExpr>(E))
2786 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002787
2788 // Cannot know anything else if the expression is dependent.
2789 if (E->isTypeDependent())
2790 return false;
2791
Douglas Gregor71235ec2009-05-02 02:18:30 +00002792 if (E->getBitField()) {
John McCall36e7fe32010-10-12 00:20:44 +00002793 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor71235ec2009-05-02 02:18:30 +00002794 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002795 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002796
2797 // Alignment of a field access is always okay, so long as it isn't a
2798 // bit-field.
2799 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002800 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002801 return false;
2802
Peter Collingbournee190dee2011-03-11 19:24:49 +00002803 return S.CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
2804 UETT_AlignOf);
2805}
2806
2807bool Sema::CheckVecStepExpr(Expr *E, SourceLocation OpLoc,
2808 SourceRange ExprRange) {
2809 E = E->IgnoreParens();
2810
2811 // Cannot know anything else if the expression is dependent.
2812 if (E->isTypeDependent())
2813 return false;
2814
2815 return CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
2816 UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002817}
2818
Douglas Gregor0950e412009-03-13 21:01:28 +00002819/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002820ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002821Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2822 SourceLocation OpLoc,
2823 UnaryExprOrTypeTrait ExprKind,
2824 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002825 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002826 return ExprError();
2827
John McCallbcd03502009-12-07 02:54:59 +00002828 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002829
Douglas Gregor0950e412009-03-13 21:01:28 +00002830 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002831 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002832 return ExprError();
2833
2834 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002835 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2836 Context.getSizeType(),
2837 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002838}
2839
2840/// \brief Build a sizeof or alignof expression given an expression
2841/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002842ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002843Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2844 UnaryExprOrTypeTrait ExprKind,
2845 SourceRange R) {
Douglas Gregor0950e412009-03-13 21:01:28 +00002846 // Verify that the operand is valid.
2847 bool isInvalid = false;
2848 if (E->isTypeDependent()) {
2849 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002850 } else if (ExprKind == UETT_AlignOf) {
John McCall36e7fe32010-10-12 00:20:44 +00002851 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002852 } else if (ExprKind == UETT_VecStep) {
2853 isInvalid = CheckVecStepExpr(E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002854 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00002855 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2856 isInvalid = true;
John McCall36226622010-10-12 02:09:17 +00002857 } else if (E->getType()->isPlaceholderType()) {
2858 ExprResult PE = CheckPlaceholderExpr(E, OpLoc);
2859 if (PE.isInvalid()) return ExprError();
Peter Collingbournee190dee2011-03-11 19:24:49 +00002860 return CreateUnaryExprOrTypeTraitExpr(PE.take(), OpLoc, ExprKind, R);
Douglas Gregor0950e412009-03-13 21:01:28 +00002861 } else {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002862 isInvalid = CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, R,
2863 UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00002864 }
2865
2866 if (isInvalid)
2867 return ExprError();
2868
2869 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002870 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, E,
2871 Context.getSizeType(),
2872 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002873}
2874
Peter Collingbournee190dee2011-03-11 19:24:49 +00002875/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2876/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00002877/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002878ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002879Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2880 UnaryExprOrTypeTrait ExprKind, bool isType,
2881 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002882 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002883 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002884
Sebastian Redl6f282892008-11-11 17:56:53 +00002885 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002886 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002887 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002888 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002889 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002890
Douglas Gregor0950e412009-03-13 21:01:28 +00002891 Expr *ArgEx = (Expr *)TyOrEx;
John McCalldadc5752010-08-24 06:29:42 +00002892 ExprResult Result
Peter Collingbournee190dee2011-03-11 19:24:49 +00002893 = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind,
2894 ArgEx->getSourceRange());
Douglas Gregor0950e412009-03-13 21:01:28 +00002895
Douglas Gregor0950e412009-03-13 21:01:28 +00002896 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002897}
2898
John McCall4bc41ae2010-11-18 19:01:18 +00002899static QualType CheckRealImagOperand(Sema &S, Expr *&V, SourceLocation Loc,
2900 bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002901 if (V->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002902 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002903
John McCall34376a62010-12-04 03:47:34 +00002904 // _Real and _Imag are only l-values for normal l-values.
2905 if (V->getObjectKind() != OK_Ordinary)
John McCall27584242010-12-06 20:48:59 +00002906 S.DefaultLvalueConversion(V);
John McCall34376a62010-12-04 03:47:34 +00002907
Chris Lattnere267f5d2007-08-26 05:39:26 +00002908 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00002909 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002910 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002911
Chris Lattnere267f5d2007-08-26 05:39:26 +00002912 // Otherwise they pass through real integer and floating point types here.
2913 if (V->getType()->isArithmeticType())
2914 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002915
John McCall36226622010-10-12 02:09:17 +00002916 // Test for placeholders.
John McCall4bc41ae2010-11-18 19:01:18 +00002917 ExprResult PR = S.CheckPlaceholderExpr(V, Loc);
John McCall36226622010-10-12 02:09:17 +00002918 if (PR.isInvalid()) return QualType();
2919 if (PR.take() != V) {
2920 V = PR.take();
John McCall4bc41ae2010-11-18 19:01:18 +00002921 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00002922 }
2923
Chris Lattnere267f5d2007-08-26 05:39:26 +00002924 // Reject anything else.
John McCall4bc41ae2010-11-18 19:01:18 +00002925 S.Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00002926 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002927 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002928}
2929
2930
Chris Lattnere168f762006-11-10 05:29:30 +00002931
John McCalldadc5752010-08-24 06:29:42 +00002932ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002933Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002934 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002935 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002936 switch (Kind) {
2937 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002938 case tok::plusplus: Opc = UO_PostInc; break;
2939 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002940 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002941
John McCallb268a282010-08-23 23:25:46 +00002942 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002943}
2944
John McCall4bc41ae2010-11-18 19:01:18 +00002945/// Expressions of certain arbitrary types are forbidden by C from
2946/// having l-value type. These are:
2947/// - 'void', but not qualified void
2948/// - function types
2949///
2950/// The exact rule here is C99 6.3.2.1:
2951/// An lvalue is an expression with an object type or an incomplete
2952/// type other than void.
2953static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
2954 return ((T->isVoidType() && !T.hasQualifiers()) ||
2955 T->isFunctionType());
2956}
2957
John McCalldadc5752010-08-24 06:29:42 +00002958ExprResult
John McCallb268a282010-08-23 23:25:46 +00002959Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2960 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002961 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002962 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002963 if (Result.isInvalid()) return ExprError();
2964 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002965
John McCallb268a282010-08-23 23:25:46 +00002966 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00002967
Douglas Gregor40412ac2008-11-19 17:17:41 +00002968 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002969 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002970 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002971 Context.DependentTy,
2972 VK_LValue, OK_Ordinary,
2973 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002974 }
2975
Mike Stump11289f42009-09-09 15:08:12 +00002976 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002977 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002978 LHSExp->getType()->isEnumeralType() ||
2979 RHSExp->getType()->isRecordType() ||
2980 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00002981 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00002982 }
2983
John McCallb268a282010-08-23 23:25:46 +00002984 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00002985}
2986
2987
John McCalldadc5752010-08-24 06:29:42 +00002988ExprResult
John McCallb268a282010-08-23 23:25:46 +00002989Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2990 Expr *Idx, SourceLocation RLoc) {
2991 Expr *LHSExp = Base;
2992 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00002993
Chris Lattner36d572b2007-07-16 00:14:47 +00002994 // Perform default conversions.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002995 if (!LHSExp->getType()->getAs<VectorType>())
2996 DefaultFunctionArrayLvalueConversion(LHSExp);
2997 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002998
Chris Lattner36d572b2007-07-16 00:14:47 +00002999 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003000 ExprValueKind VK = VK_LValue;
3001 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003002
Steve Naroffc1aadb12007-03-28 21:49:40 +00003003 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003004 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003005 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003006 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003007 Expr *BaseExpr, *IndexExpr;
3008 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003009 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3010 BaseExpr = LHSExp;
3011 IndexExpr = RHSExp;
3012 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003013 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003014 BaseExpr = LHSExp;
3015 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003016 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003017 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003018 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003019 BaseExpr = RHSExp;
3020 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003021 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003022 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003023 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003024 BaseExpr = LHSExp;
3025 IndexExpr = RHSExp;
3026 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003027 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003028 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003029 // Handle the uncommon case of "123[Ptr]".
3030 BaseExpr = RHSExp;
3031 IndexExpr = LHSExp;
3032 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003033 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003034 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003035 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003036 VK = LHSExp->getValueKind();
3037 if (VK != VK_RValue)
3038 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003039
Chris Lattner36d572b2007-07-16 00:14:47 +00003040 // FIXME: need to deal with const...
3041 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003042 } else if (LHSTy->isArrayType()) {
3043 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003044 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003045 // wasn't promoted because of the C90 rule that doesn't
3046 // allow promoting non-lvalue arrays. Warn, then
3047 // force the promotion here.
3048 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3049 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003050 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
John McCalle3027922010-08-25 11:45:40 +00003051 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00003052 LHSTy = LHSExp->getType();
3053
3054 BaseExpr = LHSExp;
3055 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003056 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003057 } else if (RHSTy->isArrayType()) {
3058 // Same as previous, except for 123[f().a] case
3059 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3060 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003061 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
John McCalle3027922010-08-25 11:45:40 +00003062 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00003063 RHSTy = RHSExp->getType();
3064
3065 BaseExpr = RHSExp;
3066 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003067 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003068 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003069 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3070 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003071 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003072 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003073 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003074 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3075 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003076
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003077 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003078 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3079 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003080 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3081
Douglas Gregorac1fb652009-03-24 19:52:54 +00003082 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003083 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3084 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003085 // incomplete types are not object types.
3086 if (ResultType->isFunctionType()) {
3087 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3088 << ResultType << BaseExpr->getSourceRange();
3089 return ExprError();
3090 }
Mike Stump11289f42009-09-09 15:08:12 +00003091
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003092 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3093 // GNU extension: subscripting on pointer to void
3094 Diag(LLoc, diag::ext_gnu_void_ptr)
3095 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003096
3097 // C forbids expressions of unqualified void type from being l-values.
3098 // See IsCForbiddenLValueType.
3099 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003100 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003101 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003102 PDiag(diag::err_subscript_incomplete_type)
3103 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003104 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003105
Chris Lattner62975a72009-04-24 00:30:45 +00003106 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003107 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003108 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3109 << ResultType << BaseExpr->getSourceRange();
3110 return ExprError();
3111 }
Mike Stump11289f42009-09-09 15:08:12 +00003112
John McCall4bc41ae2010-11-18 19:01:18 +00003113 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3114 !IsCForbiddenLValueType(Context, ResultType));
3115
Mike Stump4e1f26a2009-02-19 03:04:26 +00003116 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003117 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003118}
3119
John McCall4bc41ae2010-11-18 19:01:18 +00003120/// Check an ext-vector component access expression.
3121///
3122/// VK should be set in advance to the value kind of the base
3123/// expression.
3124static QualType
3125CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3126 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00003127 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00003128 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3129 // see FIXME there.
3130 //
3131 // FIXME: This logic can be greatly simplified by splitting it along
3132 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00003133 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00003134
Steve Narofff8fd09e2007-07-27 22:15:19 +00003135 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003136 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003137
Mike Stump4e1f26a2009-02-19 03:04:26 +00003138 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00003139 // special names that indicate a subset of exactly half the elements are
3140 // to be selected.
3141 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003142
Nate Begemanbb70bf62009-01-18 01:47:54 +00003143 // This flag determines whether or not CompName has an 's' char prefix,
3144 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00003145 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00003146
John McCall4bc41ae2010-11-18 19:01:18 +00003147 bool HasRepeated = false;
3148 bool HasIndex[16] = {};
3149
3150 int Idx;
3151
Nate Begemanf322eab2008-05-09 06:41:27 +00003152 // Check that we've found one of the special components, or that the component
3153 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003154 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00003155 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3156 HalvingSwizzle = true;
John McCall4bc41ae2010-11-18 19:01:18 +00003157 } else if (!HexSwizzle &&
3158 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3159 do {
3160 if (HasIndex[Idx]) HasRepeated = true;
3161 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003162 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003163 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3164 } else {
3165 if (HexSwizzle) compStr++;
3166 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3167 if (HasIndex[Idx]) HasRepeated = true;
3168 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003169 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003170 }
Chris Lattner7e152db2007-08-02 22:33:49 +00003171 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00003172
Mike Stump4e1f26a2009-02-19 03:04:26 +00003173 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00003174 // We didn't get to the end of the string. This means the component names
3175 // didn't come from the same set *or* we encountered an illegal name.
John McCall4bc41ae2010-11-18 19:01:18 +00003176 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramere8394df2010-08-11 14:47:12 +00003177 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00003178 return QualType();
3179 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003180
Nate Begemanbb70bf62009-01-18 01:47:54 +00003181 // Ensure no component accessor exceeds the width of the vector type it
3182 // operates on.
3183 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003184 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003185
3186 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00003187 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00003188
3189 while (*compStr) {
3190 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall4bc41ae2010-11-18 19:01:18 +00003191 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begemanbb70bf62009-01-18 01:47:54 +00003192 << baseType << SourceRange(CompLoc);
3193 return QualType();
3194 }
3195 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00003196 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003197
Steve Narofff8fd09e2007-07-27 22:15:19 +00003198 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003199 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00003200 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00003201 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00003202 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00003203 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00003204 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003205 if (HexSwizzle)
3206 CompSize--;
3207
Steve Narofff8fd09e2007-07-27 22:15:19 +00003208 if (CompSize == 1)
3209 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003210
John McCall4bc41ae2010-11-18 19:01:18 +00003211 if (HasRepeated) VK = VK_RValue;
3212
3213 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003214 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00003215 // diagostics look bad. We want extended vector types to appear built-in.
John McCall4bc41ae2010-11-18 19:01:18 +00003216 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3217 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3218 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00003219 }
3220 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00003221}
3222
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003223static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00003224 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003225 const Selector &Sel,
3226 ASTContext &Context) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003227 if (Member)
3228 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3229 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003230 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003231 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00003232
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003233 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3234 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003235 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3236 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003237 return D;
3238 }
3239 return 0;
3240}
3241
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003242static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3243 IdentifierInfo *Member,
3244 const Selector &Sel,
3245 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003246 // Check protocols on qualified interfaces.
3247 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00003248 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003249 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003250 if (Member)
3251 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3252 GDecl = PD;
3253 break;
3254 }
3255 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003256 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003257 GDecl = OMD;
3258 break;
3259 }
3260 }
3261 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00003262 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003263 E = QIdTy->qual_end(); I != E; ++I) {
3264 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003265 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3266 Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003267 if (GDecl)
3268 return GDecl;
3269 }
3270 }
3271 return GDecl;
3272}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00003273
John McCalldadc5752010-08-24 06:29:42 +00003274ExprResult
John McCallb268a282010-08-23 23:25:46 +00003275Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCall2d74de92009-12-01 22:10:20 +00003276 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003277 const CXXScopeSpec &SS,
3278 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003279 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003280 const TemplateArgumentListInfo *TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00003281 // Even in dependent contexts, try to diagnose base expressions with
3282 // obviously wrong types, e.g.:
3283 //
3284 // T* t;
3285 // t.f;
3286 //
3287 // In Obj-C++, however, the above expression is valid, since it could be
3288 // accessing the 'f' property if T is an Obj-C interface. The extra check
3289 // allows this, while still reporting an error if T is a struct pointer.
3290 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00003291 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00003292 if (PT && (!getLangOptions().ObjC1 ||
3293 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00003294 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003295 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00003296 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00003297 return ExprError();
3298 }
3299 }
3300
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003301 assert(BaseType->isDependentType() ||
3302 NameInfo.getName().isDependentName() ||
Douglas Gregor41f90302010-04-12 20:54:26 +00003303 isDependentScopeSpecifier(SS));
John McCall10eae182009-11-30 22:42:35 +00003304
3305 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3306 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00003307 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003308 IsArrow, OpLoc,
Douglas Gregore16af532011-02-28 18:50:33 +00003309 SS.getWithLocInContext(Context),
John McCall10eae182009-11-30 22:42:35 +00003310 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003311 NameInfo, TemplateArgs));
John McCall10eae182009-11-30 22:42:35 +00003312}
3313
3314/// We know that the given qualified member reference points only to
3315/// declarations which do not belong to the static type of the base
3316/// expression. Diagnose the problem.
3317static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3318 Expr *BaseExpr,
3319 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003320 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00003321 NamedDecl *rep,
3322 const DeclarationNameInfo &nameInfo) {
John McCallcd4b4772009-12-02 03:53:29 +00003323 // If this is an implicit member access, use a different set of
3324 // diagnostics.
3325 if (!BaseExpr)
John McCallf3a88602011-02-03 08:15:49 +00003326 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall10eae182009-11-30 22:42:35 +00003327
John McCallf3a88602011-02-03 08:15:49 +00003328 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3329 << SS.getRange() << rep << BaseType;
John McCall10eae182009-11-30 22:42:35 +00003330}
3331
3332// Check whether the declarations we found through a nested-name
3333// specifier in a member expression are actually members of the base
3334// type. The restriction here is:
3335//
3336// C++ [expr.ref]p2:
3337// ... In these cases, the id-expression shall name a
3338// member of the class or of one of its base classes.
3339//
3340// So it's perfectly legitimate for the nested-name specifier to name
3341// an unrelated class, and for us to find an overload set including
3342// decls from classes which are not superclasses, as long as the decl
3343// we actually pick through overload resolution is from a superclass.
3344bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3345 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003346 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003347 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00003348 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3349 if (!BaseRT) {
3350 // We can't check this yet because the base type is still
3351 // dependent.
3352 assert(BaseType->isDependentType());
3353 return false;
3354 }
3355 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00003356
3357 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00003358 // If this is an implicit member reference and we find a
3359 // non-instance member, it's not an error.
John McCalla8ae2222010-04-06 21:38:20 +00003360 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCall2d74de92009-12-01 22:10:20 +00003361 return false;
John McCall10eae182009-11-30 22:42:35 +00003362
John McCall2d74de92009-12-01 22:10:20 +00003363 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman75300492010-07-27 20:51:02 +00003364 DeclContext *DC = (*I)->getDeclContext();
3365 while (DC->isTransparentContext())
3366 DC = DC->getParent();
John McCall2d74de92009-12-01 22:10:20 +00003367
Douglas Gregora9c3e822010-07-28 22:27:52 +00003368 if (!DC->isRecord())
3369 continue;
3370
John McCall2d74de92009-12-01 22:10:20 +00003371 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman75300492010-07-27 20:51:02 +00003372 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCall2d74de92009-12-01 22:10:20 +00003373
3374 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3375 return false;
3376 }
3377
John McCallf3a88602011-02-03 08:15:49 +00003378 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3379 R.getRepresentativeDecl(),
3380 R.getLookupNameInfo());
John McCall2d74de92009-12-01 22:10:20 +00003381 return true;
3382}
3383
3384static bool
3385LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3386 SourceRange BaseRange, const RecordType *RTy,
John McCalle9cccd82010-06-16 08:42:20 +00003387 SourceLocation OpLoc, CXXScopeSpec &SS,
3388 bool HasTemplateArgs) {
John McCall2d74de92009-12-01 22:10:20 +00003389 RecordDecl *RDecl = RTy->getDecl();
3390 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor89336232010-03-29 23:34:08 +00003391 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCall2d74de92009-12-01 22:10:20 +00003392 << BaseRange))
3393 return true;
3394
John McCalle9cccd82010-06-16 08:42:20 +00003395 if (HasTemplateArgs) {
3396 // LookupTemplateName doesn't expect these both to exist simultaneously.
3397 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3398
3399 bool MOUS;
3400 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3401 return false;
3402 }
3403
John McCall2d74de92009-12-01 22:10:20 +00003404 DeclContext *DC = RDecl;
3405 if (SS.isSet()) {
3406 // If the member name was a qualified-id, look into the
3407 // nested-name-specifier.
3408 DC = SemaRef.computeDeclContext(SS, false);
3409
John McCall0b66eb32010-05-01 00:40:08 +00003410 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCallcd4b4772009-12-02 03:53:29 +00003411 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3412 << SS.getRange() << DC;
3413 return true;
3414 }
3415
John McCall2d74de92009-12-01 22:10:20 +00003416 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003417
John McCall2d74de92009-12-01 22:10:20 +00003418 if (!isa<TypeDecl>(DC)) {
3419 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3420 << DC << SS.getRange();
3421 return true;
John McCall10eae182009-11-30 22:42:35 +00003422 }
3423 }
3424
John McCall2d74de92009-12-01 22:10:20 +00003425 // The record definition is complete, now look up the member.
3426 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00003427
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003428 if (!R.empty())
3429 return false;
3430
3431 // We didn't find anything with the given name, so try to correct
3432 // for typos.
3433 DeclarationName Name = R.getLookupName();
Alexis Huntc46382e2010-04-28 23:02:27 +00003434 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003435 !R.empty() &&
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003436 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3437 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3438 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003439 << FixItHint::CreateReplacement(R.getNameLoc(),
3440 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003441 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3442 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3443 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003444 return false;
3445 } else {
3446 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003447 R.setLookupName(Name);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003448 }
3449
John McCall10eae182009-11-30 22:42:35 +00003450 return false;
3451}
3452
John McCalldadc5752010-08-24 06:29:42 +00003453ExprResult
John McCallb268a282010-08-23 23:25:46 +00003454Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00003455 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003456 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003457 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003458 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003459 const TemplateArgumentListInfo *TemplateArgs) {
John McCallcd4b4772009-12-02 03:53:29 +00003460 if (BaseType->isDependentType() ||
3461 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallb268a282010-08-23 23:25:46 +00003462 return ActOnDependentMemberExpr(Base, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003463 IsArrow, OpLoc,
3464 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003465 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003466
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003467 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00003468
John McCall2d74de92009-12-01 22:10:20 +00003469 // Implicit member accesses.
3470 if (!Base) {
3471 QualType RecordTy = BaseType;
3472 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3473 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3474 RecordTy->getAs<RecordType>(),
John McCalle9cccd82010-06-16 08:42:20 +00003475 OpLoc, SS, TemplateArgs != 0))
John McCall2d74de92009-12-01 22:10:20 +00003476 return ExprError();
3477
3478 // Explicit member accesses.
3479 } else {
John McCalldadc5752010-08-24 06:29:42 +00003480 ExprResult Result =
John McCall2d74de92009-12-01 22:10:20 +00003481 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCall48871652010-08-21 09:40:31 +00003482 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCall2d74de92009-12-01 22:10:20 +00003483
3484 if (Result.isInvalid()) {
3485 Owned(Base);
3486 return ExprError();
3487 }
3488
3489 if (Result.get())
3490 return move(Result);
Sebastian Redlfa1f70f2010-05-07 09:25:11 +00003491
3492 // LookupMemberExpr can modify Base, and thus change BaseType
3493 BaseType = Base->getType();
John McCall10eae182009-11-30 22:42:35 +00003494 }
3495
John McCallb268a282010-08-23 23:25:46 +00003496 return BuildMemberReferenceExpr(Base, BaseType,
John McCall38836f02010-01-15 08:34:02 +00003497 OpLoc, IsArrow, SS, FirstQualifierInScope,
3498 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003499}
3500
John McCalldadc5752010-08-24 06:29:42 +00003501ExprResult
John McCallb268a282010-08-23 23:25:46 +00003502Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCall2d74de92009-12-01 22:10:20 +00003503 SourceLocation OpLoc, bool IsArrow,
3504 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00003505 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00003506 LookupResult &R,
Douglas Gregorb139cd52010-05-01 20:49:11 +00003507 const TemplateArgumentListInfo *TemplateArgs,
3508 bool SuppressQualifierCheck) {
John McCall2d74de92009-12-01 22:10:20 +00003509 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00003510 if (IsArrow) {
3511 assert(BaseType->isPointerType());
3512 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3513 }
John McCalla8ae2222010-04-06 21:38:20 +00003514 R.setBaseObjectType(BaseType);
John McCall10eae182009-11-30 22:42:35 +00003515
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003516 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3517 DeclarationName MemberName = MemberNameInfo.getName();
3518 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall10eae182009-11-30 22:42:35 +00003519
3520 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00003521 return ExprError();
3522
John McCall10eae182009-11-30 22:42:35 +00003523 if (R.empty()) {
3524 // Rederive where we looked up.
3525 DeclContext *DC = (SS.isSet()
3526 ? computeDeclContext(SS, false)
3527 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00003528
John McCall10eae182009-11-30 22:42:35 +00003529 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00003530 << MemberName << DC
3531 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00003532 return ExprError();
3533 }
3534
John McCall38836f02010-01-15 08:34:02 +00003535 // Diagnose lookups that find only declarations from a non-base
3536 // type. This is possible for either qualified lookups (which may
3537 // have been qualified with an unrelated type) or implicit member
3538 // expressions (which were found with unqualified lookup and thus
3539 // may have come from an enclosing scope). Note that it's okay for
3540 // lookup to find declarations from a non-base type as long as those
3541 // aren't the ones picked by overload resolution.
3542 if ((SS.isSet() || !BaseExpr ||
3543 (isa<CXXThisExpr>(BaseExpr) &&
3544 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00003545 !SuppressQualifierCheck &&
John McCall38836f02010-01-15 08:34:02 +00003546 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00003547 return ExprError();
3548
3549 // Construct an unresolved result if we in fact got an unresolved
3550 // result.
3551 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall58cc69d2010-01-27 01:50:18 +00003552 // Suppress any lookup-related diagnostics; we'll do these when we
3553 // pick a member.
3554 R.suppressDiagnostics();
3555
John McCall10eae182009-11-30 22:42:35 +00003556 UnresolvedMemberExpr *MemExpr
Douglas Gregora6e053e2010-12-15 01:34:56 +00003557 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00003558 BaseExpr, BaseExprType,
3559 IsArrow, OpLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00003560 SS.getWithLocInContext(Context),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003561 MemberNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003562 TemplateArgs, R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00003563
3564 return Owned(MemExpr);
3565 }
3566
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003567 assert(R.isSingleResult());
John McCalla8ae2222010-04-06 21:38:20 +00003568 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall10eae182009-11-30 22:42:35 +00003569 NamedDecl *MemberDecl = R.getFoundDecl();
3570
3571 // FIXME: diagnose the presence of template arguments now.
3572
3573 // If the decl being referenced had an error, return an error for this
3574 // sub-expr without emitting another error, in order to avoid cascading
3575 // error cases.
3576 if (MemberDecl->isInvalidDecl())
3577 return ExprError();
3578
John McCall2d74de92009-12-01 22:10:20 +00003579 // Handle the implicit-member-access case.
3580 if (!BaseExpr) {
3581 // If this is not an instance member, convert to a non-member access.
John McCalla8ae2222010-04-06 21:38:20 +00003582 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003583 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCall2d74de92009-12-01 22:10:20 +00003584
Douglas Gregorb15af892010-01-07 23:12:05 +00003585 SourceLocation Loc = R.getNameLoc();
3586 if (SS.getRange().isValid())
3587 Loc = SS.getRange().getBegin();
3588 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003589 }
3590
John McCall10eae182009-11-30 22:42:35 +00003591 bool ShouldCheckUse = true;
3592 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3593 // Don't diagnose the use of a virtual member function unless it's
3594 // explicitly qualified.
3595 if (MD->isVirtual() && !SS.isSet())
3596 ShouldCheckUse = false;
3597 }
3598
3599 // Check the use of this member.
3600 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3601 Owned(BaseExpr);
3602 return ExprError();
3603 }
3604
John McCall34376a62010-12-04 03:47:34 +00003605 // Perform a property load on the base regardless of whether we
3606 // actually need it for the declaration.
3607 if (BaseExpr->getObjectKind() == OK_ObjCProperty)
3608 ConvertPropertyForRValue(BaseExpr);
3609
John McCallfeb624a2010-11-23 20:48:44 +00003610 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3611 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3612 SS, FD, FoundDecl, MemberNameInfo);
John McCall10eae182009-11-30 22:42:35 +00003613
Francois Pichet783dd6e2010-11-21 06:08:52 +00003614 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3615 // We may have found a field within an anonymous union or struct
3616 // (C++ [class.union]).
John McCallf3a88602011-02-03 08:15:49 +00003617 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCall34376a62010-12-04 03:47:34 +00003618 BaseExpr, OpLoc);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003619
John McCall10eae182009-11-30 22:42:35 +00003620 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3621 MarkDeclarationReferenced(MemberLoc, Var);
3622 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003623 Var, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003624 Var->getType().getNonReferenceType(),
John McCall4bc41ae2010-11-18 19:01:18 +00003625 VK_LValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003626 }
3627
John McCall7decc9e2010-11-18 06:31:45 +00003628 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall10eae182009-11-30 22:42:35 +00003629 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3630 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003631 MemberFn, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003632 MemberFn->getType(),
3633 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3634 OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003635 }
John McCall7decc9e2010-11-18 06:31:45 +00003636 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall10eae182009-11-30 22:42:35 +00003637
3638 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3639 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3640 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003641 Enum, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003642 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003643 }
3644
3645 Owned(BaseExpr);
3646
Douglas Gregor861eb802010-04-25 20:55:08 +00003647 // We found something that we didn't expect. Complain.
John McCall10eae182009-11-30 22:42:35 +00003648 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003649 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregor861eb802010-04-25 20:55:08 +00003650 << MemberName << BaseType << int(IsArrow);
3651 else
3652 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3653 << MemberName << BaseType << int(IsArrow);
John McCall10eae182009-11-30 22:42:35 +00003654
Douglas Gregor861eb802010-04-25 20:55:08 +00003655 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3656 << MemberName;
Douglas Gregor516d6722010-04-25 21:15:30 +00003657 R.suppressDiagnostics();
Douglas Gregor861eb802010-04-25 20:55:08 +00003658 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00003659}
3660
John McCall68fc88ec2010-12-15 16:46:44 +00003661/// Given that normal member access failed on the given expression,
3662/// and given that the expression's type involves builtin-id or
3663/// builtin-Class, decide whether substituting in the redefinition
3664/// types would be profitable. The redefinition type is whatever
3665/// this translation unit tried to typedef to id/Class; we store
3666/// it to the side and then re-use it in places like this.
3667static bool ShouldTryAgainWithRedefinitionType(Sema &S, Expr *&base) {
3668 const ObjCObjectPointerType *opty
3669 = base->getType()->getAs<ObjCObjectPointerType>();
3670 if (!opty) return false;
3671
3672 const ObjCObjectType *ty = opty->getObjectType();
3673
3674 QualType redef;
3675 if (ty->isObjCId()) {
3676 redef = S.Context.ObjCIdRedefinitionType;
3677 } else if (ty->isObjCClass()) {
3678 redef = S.Context.ObjCClassRedefinitionType;
3679 } else {
3680 return false;
3681 }
3682
3683 // Do the substitution as long as the redefinition type isn't just a
3684 // possibly-qualified pointer to builtin-id or builtin-Class again.
3685 opty = redef->getAs<ObjCObjectPointerType>();
3686 if (opty && !opty->getObjectType()->getInterface() != 0)
3687 return false;
3688
3689 S.ImpCastExprToType(base, redef, CK_BitCast);
3690 return true;
3691}
3692
John McCall10eae182009-11-30 22:42:35 +00003693/// Look up the given member of the given non-type-dependent
3694/// expression. This can return in one of two ways:
3695/// * If it returns a sentinel null-but-valid result, the caller will
3696/// assume that lookup was performed and the results written into
3697/// the provided structure. It will take over from there.
3698/// * Otherwise, the returned expression will be produced in place of
3699/// an ordinary member expression.
3700///
3701/// The ObjCImpDecl bit is a gross hack that will need to be properly
3702/// fixed for ObjC++.
John McCalldadc5752010-08-24 06:29:42 +00003703ExprResult
John McCall10eae182009-11-30 22:42:35 +00003704Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00003705 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003706 CXXScopeSpec &SS,
John McCall48871652010-08-21 09:40:31 +00003707 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003708 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00003709
Steve Naroffeaaae462007-12-16 21:42:28 +00003710 // Perform default conversions.
3711 DefaultFunctionArrayConversion(BaseExpr);
John McCall15317a22010-12-15 04:42:30 +00003712 if (IsArrow) DefaultLvalueConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003713
Steve Naroff185616f2007-07-26 03:11:44 +00003714 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00003715 assert(!BaseType->isDependentType());
3716
3717 DeclarationName MemberName = R.getLookupName();
3718 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00003719
John McCall68fc88ec2010-12-15 16:46:44 +00003720 // For later type-checking purposes, turn arrow accesses into dot
3721 // accesses. The only access type we support that doesn't follow
3722 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
3723 // and those never use arrows, so this is unaffected.
3724 if (IsArrow) {
3725 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3726 BaseType = Ptr->getPointeeType();
3727 else if (const ObjCObjectPointerType *Ptr
3728 = BaseType->getAs<ObjCObjectPointerType>())
3729 BaseType = Ptr->getPointeeType();
3730 else if (BaseType->isRecordType()) {
3731 // Recover from arrow accesses to records, e.g.:
3732 // struct MyRecord foo;
3733 // foo->bar
3734 // This is actually well-formed in C++ if MyRecord has an
3735 // overloaded operator->, but that should have been dealt with
3736 // by now.
3737 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3738 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3739 << FixItHint::CreateReplacement(OpLoc, ".");
3740 IsArrow = false;
3741 } else {
3742 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3743 << BaseType << BaseExpr->getSourceRange();
3744 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00003745 }
3746 }
3747
John McCall68fc88ec2010-12-15 16:46:44 +00003748 // Handle field access to simple records.
3749 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
3750 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
3751 RTy, OpLoc, SS, HasTemplateArgs))
3752 return ExprError();
3753
3754 // Returning valid-but-null is how we indicate to the caller that
3755 // the lookup result was filled in.
3756 return Owned((Expr*) 0);
David Chisnall9f57c292009-08-17 16:35:33 +00003757 }
John McCall10eae182009-11-30 22:42:35 +00003758
John McCall68fc88ec2010-12-15 16:46:44 +00003759 // Handle ivar access to Objective-C objects.
3760 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003761 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall68fc88ec2010-12-15 16:46:44 +00003762
3763 // There are three cases for the base type:
3764 // - builtin id (qualified or unqualified)
3765 // - builtin Class (qualified or unqualified)
3766 // - an interface
3767 ObjCInterfaceDecl *IDecl = OTy->getInterface();
3768 if (!IDecl) {
3769 // There's an implicit 'isa' ivar on all objects.
3770 // But we only actually find it this way on objects of type 'id',
3771 // apparently.
3772 if (OTy->isObjCId() && Member->isStr("isa"))
3773 return Owned(new (Context) ObjCIsaExpr(BaseExpr, IsArrow, MemberLoc,
3774 Context.getObjCClassType()));
3775
3776 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3777 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3778 ObjCImpDecl, HasTemplateArgs);
3779 goto fail;
3780 }
3781
3782 ObjCInterfaceDecl *ClassDeclared;
3783 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
3784
3785 if (!IV) {
3786 // Attempt to correct for typos in ivar names.
3787 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3788 LookupMemberName);
3789 if (CorrectTypo(Res, 0, 0, IDecl, false,
3790 IsArrow ? CTC_ObjCIvarLookup
3791 : CTC_ObjCPropertyLookup) &&
3792 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
3793 Diag(R.getNameLoc(),
3794 diag::err_typecheck_member_reference_ivar_suggest)
3795 << IDecl->getDeclName() << MemberName << IV->getDeclName()
3796 << FixItHint::CreateReplacement(R.getNameLoc(),
3797 IV->getNameAsString());
3798 Diag(IV->getLocation(), diag::note_previous_decl)
3799 << IV->getDeclName();
3800 } else {
3801 Res.clear();
3802 Res.setLookupName(Member);
3803
3804 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
3805 << IDecl->getDeclName() << MemberName
3806 << BaseExpr->getSourceRange();
3807 return ExprError();
3808 }
3809 }
3810
3811 // If the decl being referenced had an error, return an error for this
3812 // sub-expr without emitting another error, in order to avoid cascading
3813 // error cases.
3814 if (IV->isInvalidDecl())
3815 return ExprError();
3816
3817 // Check whether we can reference this field.
3818 if (DiagnoseUseOfDecl(IV, MemberLoc))
3819 return ExprError();
3820 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3821 IV->getAccessControl() != ObjCIvarDecl::Package) {
3822 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3823 if (ObjCMethodDecl *MD = getCurMethodDecl())
3824 ClassOfMethodDecl = MD->getClassInterface();
3825 else if (ObjCImpDecl && getCurFunctionDecl()) {
3826 // Case of a c-function declared inside an objc implementation.
3827 // FIXME: For a c-style function nested inside an objc implementation
3828 // class, there is no implementation context available, so we pass
3829 // down the context as argument to this routine. Ideally, this context
3830 // need be passed down in the AST node and somehow calculated from the
3831 // AST for a function decl.
3832 if (ObjCImplementationDecl *IMPD =
3833 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
3834 ClassOfMethodDecl = IMPD->getClassInterface();
3835 else if (ObjCCategoryImplDecl* CatImplClass =
3836 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
3837 ClassOfMethodDecl = CatImplClass->getClassInterface();
3838 }
3839
3840 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3841 if (ClassDeclared != IDecl ||
3842 ClassOfMethodDecl != ClassDeclared)
3843 Diag(MemberLoc, diag::error_private_ivar_access)
3844 << IV->getDeclName();
3845 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3846 // @protected
3847 Diag(MemberLoc, diag::error_protected_ivar_access)
3848 << IV->getDeclName();
3849 }
3850
3851 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3852 MemberLoc, BaseExpr,
3853 IsArrow));
3854 }
3855
3856 // Objective-C property access.
3857 const ObjCObjectPointerType *OPT;
3858 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
3859 // This actually uses the base as an r-value.
3860 DefaultLvalueConversion(BaseExpr);
3861 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr->getType()));
3862
3863 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3864
3865 const ObjCObjectType *OT = OPT->getObjectType();
3866
3867 // id, with and without qualifiers.
3868 if (OT->isObjCId()) {
3869 // Check protocols on qualified interfaces.
3870 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3871 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
3872 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3873 // Check the use of this declaration
3874 if (DiagnoseUseOfDecl(PD, MemberLoc))
3875 return ExprError();
3876
3877 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3878 VK_LValue,
3879 OK_ObjCProperty,
3880 MemberLoc,
3881 BaseExpr));
3882 }
3883
3884 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3885 // Check the use of this method.
3886 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3887 return ExprError();
3888 Selector SetterSel =
3889 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3890 PP.getSelectorTable(), Member);
3891 ObjCMethodDecl *SMD = 0;
3892 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
3893 SetterSel, Context))
3894 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3895 QualType PType = OMD->getSendResultType();
3896
3897 ExprValueKind VK = VK_LValue;
3898 if (!getLangOptions().CPlusPlus &&
3899 IsCForbiddenLValueType(Context, PType))
3900 VK = VK_RValue;
3901 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3902
3903 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
3904 VK, OK,
3905 MemberLoc, BaseExpr));
3906 }
3907 }
Fariborz Jahanianb03a4c22011-03-15 17:27:48 +00003908 // Use of id.member can only be for a property reference. Do not
3909 // use the 'id' redefinition in this case.
3910 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
John McCall68fc88ec2010-12-15 16:46:44 +00003911 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3912 ObjCImpDecl, HasTemplateArgs);
3913
3914 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3915 << MemberName << BaseType);
3916 }
3917
3918 // 'Class', unqualified only.
3919 if (OT->isObjCClass()) {
3920 // Only works in a method declaration (??!).
3921 ObjCMethodDecl *MD = getCurMethodDecl();
3922 if (!MD) {
3923 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3924 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3925 ObjCImpDecl, HasTemplateArgs);
3926
3927 goto fail;
3928 }
3929
3930 // Also must look for a getter name which uses property syntax.
3931 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003932 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3933 ObjCMethodDecl *Getter;
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003934 if ((Getter = IFace->lookupClassMethod(Sel))) {
3935 // Check the use of this method.
3936 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3937 return ExprError();
John McCall68fc88ec2010-12-15 16:46:44 +00003938 } else
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00003939 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003940 // If we found a getter then this may be a valid dot-reference, we
3941 // will look for the matching setter, in case it is needed.
3942 Selector SetterSel =
John McCall68fc88ec2010-12-15 16:46:44 +00003943 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3944 PP.getSelectorTable(), Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003945 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3946 if (!Setter) {
3947 // If this reference is in an @implementation, also check for 'private'
3948 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00003949 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003950 }
3951 // Look through local category implementations associated with the class.
3952 if (!Setter)
3953 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003954
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003955 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3956 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003957
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003958 if (Getter || Setter) {
3959 QualType PType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003960
John McCall4bc41ae2010-11-18 19:01:18 +00003961 ExprValueKind VK = VK_LValue;
3962 if (Getter) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00003963 PType = Getter->getSendResultType();
John McCall4bc41ae2010-11-18 19:01:18 +00003964 if (!getLangOptions().CPlusPlus &&
3965 IsCForbiddenLValueType(Context, PType))
3966 VK = VK_RValue;
3967 } else {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003968 // Get the expression type from Setter's incoming parameter.
3969 PType = (*(Setter->param_end() -1))->getType();
John McCall4bc41ae2010-11-18 19:01:18 +00003970 }
3971 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3972
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003973 // FIXME: we must check that the setter has property type.
John McCallb7bd14f2010-12-02 01:19:52 +00003974 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
3975 PType, VK, OK,
3976 MemberLoc, BaseExpr));
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003977 }
John McCall68fc88ec2010-12-15 16:46:44 +00003978
3979 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3980 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3981 ObjCImpDecl, HasTemplateArgs);
3982
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003983 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall68fc88ec2010-12-15 16:46:44 +00003984 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003985 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003986
John McCall68fc88ec2010-12-15 16:46:44 +00003987 // Normal property access.
3988 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc,
3989 SourceLocation(), QualType(), false);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003990 }
Alexis Huntc46382e2010-04-28 23:02:27 +00003991
Chris Lattnerb63a7452008-07-21 04:28:12 +00003992 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003993 if (BaseType->isExtVectorType()) {
John McCall15317a22010-12-15 04:42:30 +00003994 // FIXME: this expr should store IsArrow.
Anders Carlssonf571c112009-08-26 18:25:21 +00003995 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall15317a22010-12-15 04:42:30 +00003996 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr->getValueKind());
John McCall4bc41ae2010-11-18 19:01:18 +00003997 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
3998 Member, MemberLoc);
Chris Lattnerb63a7452008-07-21 04:28:12 +00003999 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004000 return ExprError();
John McCall4bc41ae2010-11-18 19:01:18 +00004001
4002 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr,
4003 *Member, MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00004004 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004005
John McCall68fc88ec2010-12-15 16:46:44 +00004006 // Adjust builtin-sel to the appropriate redefinition type if that's
4007 // not just a pointer to builtin-sel again.
4008 if (IsArrow &&
4009 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
4010 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
4011 ImpCastExprToType(BaseExpr, Context.ObjCSelRedefinitionType, CK_BitCast);
4012 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4013 ObjCImpDecl, HasTemplateArgs);
4014 }
4015
4016 // Failure cases.
4017 fail:
4018
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004019 // Recover from dot accesses to pointers, e.g.:
4020 // type *foo;
4021 // foo.bar
4022 // This is actually well-formed in two cases:
4023 // - 'type' is an Objective C type
4024 // - 'bar' is a pseudo-destructor name which happens to refer to
4025 // the appropriate pointer type
John McCall68fc88ec2010-12-15 16:46:44 +00004026 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004027 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
4028 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
John McCall68fc88ec2010-12-15 16:46:44 +00004029 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004030 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
4031 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall68fc88ec2010-12-15 16:46:44 +00004032
4033 // Recurse as an -> access.
4034 IsArrow = true;
4035 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4036 ObjCImpDecl, HasTemplateArgs);
4037 }
John McCall68fc88ec2010-12-15 16:46:44 +00004038 }
4039
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004040 // If the user is trying to apply -> or . to a function name, it's probably
4041 // because they forgot parentheses to call that function.
4042 bool TryCall = false;
4043 bool Overloaded = false;
4044 UnresolvedSet<8> AllOverloads;
4045 if (const OverloadExpr *Overloads = dyn_cast<OverloadExpr>(BaseExpr)) {
4046 AllOverloads.append(Overloads->decls_begin(), Overloads->decls_end());
4047 TryCall = true;
4048 Overloaded = true;
4049 } else if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(BaseExpr)) {
4050 if (FunctionDecl* Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
4051 AllOverloads.addDecl(Fun);
4052 TryCall = true;
4053 }
4054 }
John McCall68fc88ec2010-12-15 16:46:44 +00004055
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004056 if (TryCall) {
4057 // Plunder the overload set for something that would make the member
4058 // expression valid.
4059 UnresolvedSet<4> ViableOverloads;
4060 bool HasViableZeroArgOverload = false;
4061 for (OverloadExpr::decls_iterator it = AllOverloads.begin(),
4062 DeclsEnd = AllOverloads.end(); it != DeclsEnd; ++it) {
Matt Beaumont-Gayf8bb45f2011-03-05 02:42:30 +00004063 // Our overload set may include TemplateDecls, which we'll ignore for the
4064 // purposes of determining whether we can issue a '()' fixit.
4065 if (const FunctionDecl *OverloadDecl = dyn_cast<FunctionDecl>(*it)) {
4066 QualType ResultTy = OverloadDecl->getResultType();
4067 if ((!IsArrow && ResultTy->isRecordType()) ||
4068 (IsArrow && ResultTy->isPointerType() &&
4069 ResultTy->getPointeeType()->isRecordType())) {
4070 ViableOverloads.addDecl(*it);
4071 if (OverloadDecl->getMinRequiredArguments() == 0) {
4072 HasViableZeroArgOverload = true;
4073 }
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004074 }
John McCall68fc88ec2010-12-15 16:46:44 +00004075 }
4076 }
4077
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004078 if (!HasViableZeroArgOverload || ViableOverloads.size() != 1) {
4079 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gayf8bb45f2011-03-05 02:42:30 +00004080 << (AllOverloads.size() > 1) << 0
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004081 << BaseExpr->getSourceRange();
4082 int ViableOverloadCount = ViableOverloads.size();
4083 int I;
4084 for (I = 0; I < ViableOverloadCount; ++I) {
4085 // FIXME: Magic number for max shown overloads stolen from
4086 // OverloadCandidateSet::NoteCandidates.
4087 if (I >= 4 && Diags.getShowOverloads() == Diagnostic::Ovl_Best) {
4088 break;
4089 }
4090 Diag(ViableOverloads[I].getDecl()->getSourceRange().getBegin(),
4091 diag::note_member_ref_possible_intended_overload);
4092 }
4093 if (I != ViableOverloadCount) {
4094 Diag(BaseExpr->getExprLoc(), diag::note_ovl_too_many_candidates)
4095 << int(ViableOverloadCount - I);
4096 }
4097 return ExprError();
4098 }
4099 } else {
4100 // We don't have an expression that's convenient to get a Decl from, but we
4101 // can at least check if the type is "function of 0 arguments which returns
4102 // an acceptable type".
4103 const FunctionType *Fun = NULL;
4104 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4105 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
4106 TryCall = true;
4107 }
4108 } else if ((Fun = BaseType->getAs<FunctionType>())) {
4109 TryCall = true;
4110 }
John McCall68fc88ec2010-12-15 16:46:44 +00004111
4112 if (TryCall) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004113 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
4114 if (FPT->getNumArgs() == 0) {
4115 QualType ResultTy = Fun->getResultType();
4116 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
4117 (IsArrow && ResultTy->isPointerType() &&
4118 ResultTy->getPointeeType()->isRecordType());
4119 }
Matt Beaumont-Gay956fc1c2011-02-17 02:54:17 +00004120 }
John McCall68fc88ec2010-12-15 16:46:44 +00004121 }
4122 }
4123
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004124 if (TryCall) {
4125 // At this point, we know BaseExpr looks like it's potentially callable with
4126 // 0 arguments, and that it returns something of a reasonable type, so we
4127 // can emit a fixit and carry on pretending that BaseExpr was actually a
4128 // CallExpr.
4129 SourceLocation ParenInsertionLoc =
4130 PP.getLocForEndOfToken(BaseExpr->getLocEnd());
4131 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
4132 << int(Overloaded) << 1
4133 << BaseExpr->getSourceRange()
4134 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
4135 ExprResult NewBase = ActOnCallExpr(0, BaseExpr, ParenInsertionLoc,
4136 MultiExprArg(*this, 0, 0),
4137 ParenInsertionLoc);
4138 if (NewBase.isInvalid())
4139 return ExprError();
4140 BaseExpr = NewBase.takeAs<Expr>();
4141 DefaultFunctionArrayConversion(BaseExpr);
4142 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4143 ObjCImpDecl, HasTemplateArgs);
4144 }
4145
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004146 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
4147 << BaseType << BaseExpr->getSourceRange();
4148
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004149 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00004150}
4151
John McCall10eae182009-11-30 22:42:35 +00004152/// The main callback when the parser finds something like
4153/// expression . [nested-name-specifier] identifier
4154/// expression -> [nested-name-specifier] identifier
4155/// where 'identifier' encompasses a fairly broad spectrum of
4156/// possibilities, including destructor and operator references.
4157///
4158/// \param OpKind either tok::arrow or tok::period
4159/// \param HasTrailingLParen whether the next token is '(', which
4160/// is used to diagnose mis-uses of special members that can
4161/// only be called
4162/// \param ObjCImpDecl the current ObjC @implementation decl;
4163/// this is an ugly hack around the fact that ObjC @implementations
4164/// aren't properly put in the context chain
John McCalldadc5752010-08-24 06:29:42 +00004165ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall15317a22010-12-15 04:42:30 +00004166 SourceLocation OpLoc,
4167 tok::TokenKind OpKind,
4168 CXXScopeSpec &SS,
4169 UnqualifiedId &Id,
4170 Decl *ObjCImpDecl,
4171 bool HasTrailingLParen) {
John McCall10eae182009-11-30 22:42:35 +00004172 if (SS.isSet() && SS.isInvalid())
4173 return ExprError();
4174
Francois Pichet64225792011-01-18 05:04:39 +00004175 // Warn about the explicit constructor calls Microsoft extension.
4176 if (getLangOptions().Microsoft &&
4177 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4178 Diag(Id.getSourceRange().getBegin(),
4179 diag::ext_ms_explicit_constructor_call);
4180
John McCall10eae182009-11-30 22:42:35 +00004181 TemplateArgumentListInfo TemplateArgsBuffer;
4182
4183 // Decompose the name into its component parts.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004184 DeclarationNameInfo NameInfo;
John McCall10eae182009-11-30 22:42:35 +00004185 const TemplateArgumentListInfo *TemplateArgs;
4186 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004187 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004188
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004189 DeclarationName Name = NameInfo.getName();
John McCall10eae182009-11-30 22:42:35 +00004190 bool IsArrow = (OpKind == tok::arrow);
4191
4192 NamedDecl *FirstQualifierInScope
4193 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4194 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4195
4196 // This is a postfix expression, so get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004197 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00004198 if (Result.isInvalid()) return ExprError();
4199 Base = Result.take();
John McCall10eae182009-11-30 22:42:35 +00004200
Douglas Gregor41f90302010-04-12 20:54:26 +00004201 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4202 isDependentScopeSpecifier(SS)) {
John McCallb268a282010-08-23 23:25:46 +00004203 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00004204 IsArrow, OpLoc,
4205 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004206 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004207 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004208 LookupResult R(*this, NameInfo, LookupMemberName);
John McCalle9cccd82010-06-16 08:42:20 +00004209 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
4210 SS, ObjCImpDecl, TemplateArgs != 0);
Alexis Huntc46382e2010-04-28 23:02:27 +00004211
John McCalle9cccd82010-06-16 08:42:20 +00004212 if (Result.isInvalid()) {
4213 Owned(Base);
4214 return ExprError();
4215 }
John McCall10eae182009-11-30 22:42:35 +00004216
John McCalle9cccd82010-06-16 08:42:20 +00004217 if (Result.get()) {
4218 // The only way a reference to a destructor can be used is to
4219 // immediately call it, which falls into this case. If the
4220 // next token is not a '(', produce a diagnostic and build the
4221 // call now.
4222 if (!HasTrailingLParen &&
4223 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCallb268a282010-08-23 23:25:46 +00004224 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall10eae182009-11-30 22:42:35 +00004225
John McCalle9cccd82010-06-16 08:42:20 +00004226 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00004227 }
4228
John McCallb268a282010-08-23 23:25:46 +00004229 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00004230 OpLoc, IsArrow, SS, FirstQualifierInScope,
4231 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004232 }
4233
4234 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00004235}
4236
John McCalldadc5752010-08-24 06:29:42 +00004237ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00004238 FunctionDecl *FD,
4239 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00004240 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004241 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00004242 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00004243 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004244 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00004245 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004246 return ExprError();
4247 }
4248
4249 if (Param->hasUninstantiatedDefaultArg()) {
4250 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00004251
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004252 // Instantiate the expression.
4253 MultiLevelTemplateArgumentList ArgList
4254 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00004255
Nico Weber44887f62010-11-29 18:19:25 +00004256 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004257 = ArgList.getInnermost();
4258 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4259 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00004260
Nico Weber44887f62010-11-29 18:19:25 +00004261 ExprResult Result;
4262 {
4263 // C++ [dcl.fct.default]p5:
4264 // The names in the [default argument] expression are bound, and
4265 // the semantic constraints are checked, at the point where the
4266 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00004267 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00004268 Result = SubstExpr(UninstExpr, ArgList);
4269 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004270 if (Result.isInvalid())
4271 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004272
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004273 // Check the expression as an initializer for the parameter.
4274 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004275 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004276 InitializationKind Kind
4277 = InitializationKind::CreateCopy(Param->getLocation(),
4278 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4279 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00004280
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004281 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4282 Result = InitSeq.Perform(*this, Entity, Kind,
4283 MultiExprArg(*this, &ResultE, 1));
4284 if (Result.isInvalid())
4285 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004286
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004287 // Build the default argument expression.
4288 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4289 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00004290 }
4291
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004292 // If the default expression creates temporaries, we need to
4293 // push them to the current stack of expression temporaries so they'll
4294 // be properly destroyed.
4295 // FIXME: We should really be rebuilding the default argument with new
4296 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00004297 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4298 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4299 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4300 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4301 ExprTemporaries.push_back(Temporary);
4302 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004303
4304 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00004305 // Just mark all of the declarations in this potentially-evaluated expression
4306 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004307 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00004308 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00004309}
4310
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004311/// ConvertArgumentsForCall - Converts the arguments specified in
4312/// Args/NumArgs to the parameter types of the function FDecl with
4313/// function prototype Proto. Call is the call expression itself, and
4314/// Fn is the function expression. For a C++ member function, this
4315/// routine does not attempt to convert the object argument. Returns
4316/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004317bool
4318Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004319 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004320 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004321 Expr **Args, unsigned NumArgs,
4322 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00004323 // Bail out early if calling a builtin with custom typechecking.
4324 // We don't need to do this in the
4325 if (FDecl)
4326 if (unsigned ID = FDecl->getBuiltinID())
4327 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4328 return false;
4329
Mike Stump4e1f26a2009-02-19 03:04:26 +00004330 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004331 // assignment, to the types of the corresponding parameter, ...
4332 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00004333 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004334
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004335 // If too few arguments are available (and we don't have default
4336 // arguments for the remaining parameters), don't make the call.
4337 if (NumArgs < NumArgsInProto) {
4338 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4339 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004340 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00004341 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00004342 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004343 }
4344
4345 // If too many are passed and not variadic, error on the extras and drop
4346 // them.
4347 if (NumArgs > NumArgsInProto) {
4348 if (!Proto->isVariadic()) {
4349 Diag(Args[NumArgsInProto]->getLocStart(),
4350 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004351 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004352 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004353 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4354 Args[NumArgs-1]->getLocEnd());
4355 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00004356 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004357 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004358 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004359 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004360 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004361 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004362 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4363 if (Fn->getType()->isBlockPointerType())
4364 CallType = VariadicBlock; // Block
4365 else if (isa<MemberExpr>(Fn))
4366 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004367 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004368 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004369 if (Invalid)
4370 return true;
4371 unsigned TotalNumArgs = AllArgs.size();
4372 for (unsigned i = 0; i < TotalNumArgs; ++i)
4373 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004374
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004375 return false;
4376}
Mike Stump4e1f26a2009-02-19 03:04:26 +00004377
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004378bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4379 FunctionDecl *FDecl,
4380 const FunctionProtoType *Proto,
4381 unsigned FirstProtoArg,
4382 Expr **Args, unsigned NumArgs,
4383 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004384 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004385 unsigned NumArgsInProto = Proto->getNumArgs();
4386 unsigned NumArgsToCheck = NumArgs;
4387 bool Invalid = false;
4388 if (NumArgs != NumArgsInProto)
4389 // Use default arguments for missing arguments
4390 NumArgsToCheck = NumArgsInProto;
4391 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004392 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004393 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004394 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004395
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004396 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004397 if (ArgIx < NumArgs) {
4398 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004399
Eli Friedman3164fb12009-03-22 22:00:50 +00004400 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4401 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00004402 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004403 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00004404 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004405
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004406 // Pass the argument
4407 ParmVarDecl *Param = 0;
4408 if (FDecl && i < FDecl->getNumParams())
4409 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00004410
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004411 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004412 Param? InitializedEntity::InitializeParameter(Context, Param)
4413 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCalldadc5752010-08-24 06:29:42 +00004414 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00004415 SourceLocation(),
4416 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004417 if (ArgE.isInvalid())
4418 return true;
4419
4420 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004421 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00004422 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004423
John McCalldadc5752010-08-24 06:29:42 +00004424 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004425 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004426 if (ArgExpr.isInvalid())
4427 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004428
Anders Carlsson355933d2009-08-25 03:49:14 +00004429 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004430 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004431 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004432 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004433
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004434 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004435 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004436 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004437 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004438 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004439 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004440 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004441 }
4442 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00004443 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004444}
4445
Steve Naroff83895f72007-09-16 03:34:24 +00004446/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00004447/// This provides the location of the left/right parens and a list of comma
4448/// locations.
John McCalldadc5752010-08-24 06:29:42 +00004449ExprResult
John McCallb268a282010-08-23 23:25:46 +00004450Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004451 MultiExprArg args, SourceLocation RParenLoc,
4452 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004453 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00004454
4455 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004456 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00004457 if (Result.isInvalid()) return ExprError();
4458 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00004459
John McCallb268a282010-08-23 23:25:46 +00004460 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00004461
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004462 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00004463 // If this is a pseudo-destructor expression, build the call immediately.
4464 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4465 if (NumArgs > 0) {
4466 // Pseudo-destructor calls should not have any arguments.
4467 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00004468 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00004469 SourceRange(Args[0]->getLocStart(),
4470 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00004471
Douglas Gregorad8a3362009-09-04 17:36:40 +00004472 NumArgs = 0;
4473 }
Mike Stump11289f42009-09-09 15:08:12 +00004474
Douglas Gregorad8a3362009-09-04 17:36:40 +00004475 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00004476 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00004477 }
Mike Stump11289f42009-09-09 15:08:12 +00004478
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004479 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00004480 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00004481 // FIXME: Will need to cache the results of name lookup (including ADL) in
4482 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004483 bool Dependent = false;
4484 if (Fn->isTypeDependent())
4485 Dependent = true;
4486 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4487 Dependent = true;
4488
Peter Collingbourne41f85462011-02-09 21:07:24 +00004489 if (Dependent) {
4490 if (ExecConfig) {
4491 return Owned(new (Context) CUDAKernelCallExpr(
4492 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4493 Context.DependentTy, VK_RValue, RParenLoc));
4494 } else {
4495 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4496 Context.DependentTy, VK_RValue,
4497 RParenLoc));
4498 }
4499 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004500
4501 // Determine whether this is a call to an object (C++ [over.call.object]).
4502 if (Fn->getType()->isRecordType())
4503 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004504 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004505
John McCall10eae182009-11-30 22:42:35 +00004506 Expr *NakedFn = Fn->IgnoreParens();
4507
4508 // Determine whether this is a call to an unresolved member function.
4509 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4510 // If lookup was unresolved but not dependent (i.e. didn't find
4511 // an unresolved using declaration), it has to be an overloaded
4512 // function set, which means it must contain either multiple
4513 // declarations (all methods or method templates) or a single
4514 // method template.
4515 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor516d6722010-04-25 21:15:30 +00004516 isa<FunctionTemplateDecl>(
4517 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00004518 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00004519
John McCall2d74de92009-12-01 22:10:20 +00004520 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004521 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00004522 }
4523
Douglas Gregore254f902009-02-04 00:32:51 +00004524 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00004525 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004526 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00004527 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00004528 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004529 RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004530 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004531
Anders Carlsson61914b52009-10-03 17:40:22 +00004532 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00004533 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
John McCalle3027922010-08-25 11:45:40 +00004534 if (BO->getOpcode() == BO_PtrMemD ||
4535 BO->getOpcode() == BO_PtrMemI) {
Douglas Gregorc8be9522010-05-04 18:18:31 +00004536 if (const FunctionProtoType *FPT
4537 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00004538 QualType ResultTy = FPT->getCallResultType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00004539 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004540
Douglas Gregor125fa402011-02-04 12:57:49 +00004541 // Check that the object type isn't more qualified than the
4542 // member function we're calling.
4543 Qualifiers FuncQuals = Qualifiers::fromCVRMask(FPT->getTypeQuals());
4544 Qualifiers ObjectQuals
4545 = BO->getOpcode() == BO_PtrMemD
4546 ? BO->getLHS()->getType().getQualifiers()
4547 : BO->getLHS()->getType()->getAs<PointerType>()
4548 ->getPointeeType().getQualifiers();
4549
4550 Qualifiers Difference = ObjectQuals - FuncQuals;
4551 Difference.removeObjCGCAttr();
4552 Difference.removeAddressSpace();
4553 if (Difference) {
4554 std::string QualsString = Difference.getAsString();
4555 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
4556 << BO->getType().getUnqualifiedType()
4557 << QualsString
4558 << (QualsString.find(' ') == std::string::npos? 1 : 2);
4559 }
4560
John McCallb268a282010-08-23 23:25:46 +00004561 CXXMemberCallExpr *TheCall
Abramo Bagnara21e9d862010-12-03 21:39:42 +00004562 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
John McCall7decc9e2010-11-18 06:31:45 +00004563 NumArgs, ResultTy, VK,
John McCallb268a282010-08-23 23:25:46 +00004564 RParenLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004565
4566 if (CheckCallReturnType(FPT->getResultType(),
4567 BO->getRHS()->getSourceRange().getBegin(),
John McCallb268a282010-08-23 23:25:46 +00004568 TheCall, 0))
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004569 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00004570
John McCallb268a282010-08-23 23:25:46 +00004571 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004572 RParenLoc))
4573 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00004574
John McCallb268a282010-08-23 23:25:46 +00004575 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004576 }
Anders Carlsson61914b52009-10-03 17:40:22 +00004577 }
4578 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004579 }
4580
Douglas Gregore254f902009-02-04 00:32:51 +00004581 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004582 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00004583 // lookup and whether there were any explicitly-specified template arguments.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004584
Eli Friedmane14b1992009-12-26 03:35:45 +00004585 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00004586 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4587 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4588 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004589 RParenLoc, ExecConfig);
Douglas Gregor928479e2010-11-09 20:03:54 +00004590 }
4591
John McCall57500772009-12-16 12:17:52 +00004592 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00004593 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4594 if (UnOp->getOpcode() == UO_AddrOf)
4595 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4596
John McCall57500772009-12-16 12:17:52 +00004597 if (isa<DeclRefExpr>(NakedFn))
4598 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4599
Peter Collingbourne41f85462011-02-09 21:07:24 +00004600 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
4601 ExecConfig);
4602}
4603
4604ExprResult
4605Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4606 MultiExprArg execConfig, SourceLocation GGGLoc) {
4607 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4608 if (!ConfigDecl)
4609 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4610 << "cudaConfigureCall");
4611 QualType ConfigQTy = ConfigDecl->getType();
4612
4613 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4614 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
4615
4616 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00004617}
4618
John McCall57500772009-12-16 12:17:52 +00004619/// BuildResolvedCallExpr - Build a call to a resolved expression,
4620/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00004621/// unary-convert to an expression of function-pointer or
4622/// block-pointer type.
4623///
4624/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00004625ExprResult
John McCall2d74de92009-12-01 22:10:20 +00004626Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4627 SourceLocation LParenLoc,
4628 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004629 SourceLocation RParenLoc,
4630 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00004631 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4632
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004633 // Promote the function operand.
4634 UsualUnaryConversions(Fn);
4635
Chris Lattner08464942007-12-28 05:29:59 +00004636 // Make the call expr early, before semantic checks. This guarantees cleanup
4637 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00004638 CallExpr *TheCall;
4639 if (Config) {
4640 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4641 cast<CallExpr>(Config),
4642 Args, NumArgs,
4643 Context.BoolTy,
4644 VK_RValue,
4645 RParenLoc);
4646 } else {
4647 TheCall = new (Context) CallExpr(Context, Fn,
4648 Args, NumArgs,
4649 Context.BoolTy,
4650 VK_RValue,
4651 RParenLoc);
4652 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004653
John McCallbebede42011-02-26 05:39:39 +00004654 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4655
4656 // Bail out early if calling a builtin with custom typechecking.
4657 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4658 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4659
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004660 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00004661 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004662 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4663 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00004664 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00004665 if (FuncT == 0)
4666 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4667 << Fn->getType() << Fn->getSourceRange());
4668 } else if (const BlockPointerType *BPT =
4669 Fn->getType()->getAs<BlockPointerType>()) {
4670 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4671 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004672 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4673 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00004674 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004675
Peter Collingbourne4b66c472011-02-23 01:53:29 +00004676 if (getLangOptions().CUDA) {
4677 if (Config) {
4678 // CUDA: Kernel calls must be to global functions
4679 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4680 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4681 << FDecl->getName() << Fn->getSourceRange());
4682
4683 // CUDA: Kernel function must have 'void' return type
4684 if (!FuncT->getResultType()->isVoidType())
4685 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4686 << Fn->getType() << Fn->getSourceRange());
4687 }
4688 }
4689
Eli Friedman3164fb12009-03-22 22:00:50 +00004690 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004691 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00004692 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004693 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00004694 return ExprError();
4695
Chris Lattner08464942007-12-28 05:29:59 +00004696 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004697 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00004698 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004699
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004700 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00004701 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004702 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004703 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00004704 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004705 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004706
Douglas Gregord8e97de2009-04-02 15:37:10 +00004707 if (FDecl) {
4708 // Check if we have too few/too many template arguments, based
4709 // on our knowledge of the function definition.
4710 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00004711 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004712 const FunctionProtoType *Proto
4713 = Def->getType()->getAs<FunctionProtoType>();
4714 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004715 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4716 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004717 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00004718
4719 // If the function we're calling isn't a function prototype, but we have
4720 // a function prototype from a prior declaratiom, use that prototype.
4721 if (!FDecl->hasPrototype())
4722 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00004723 }
4724
Steve Naroff0b661582007-08-28 23:30:39 +00004725 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00004726 for (unsigned i = 0; i != NumArgs; i++) {
4727 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00004728
4729 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004730 InitializedEntity Entity
4731 = InitializedEntity::InitializeParameter(Context,
4732 Proto->getArgType(i));
4733 ExprResult ArgE = PerformCopyInitialization(Entity,
4734 SourceLocation(),
4735 Owned(Arg));
4736 if (ArgE.isInvalid())
4737 return true;
4738
4739 Arg = ArgE.takeAs<Expr>();
4740
4741 } else {
4742 DefaultArgumentPromotion(Arg);
Douglas Gregor8e09a722010-10-25 20:39:23 +00004743 }
4744
Douglas Gregor83025412010-10-26 05:45:40 +00004745 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4746 Arg->getType(),
4747 PDiag(diag::err_call_incomplete_argument)
4748 << Arg->getSourceRange()))
4749 return ExprError();
4750
Chris Lattner08464942007-12-28 05:29:59 +00004751 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00004752 }
Steve Naroffae4143e2007-04-26 20:39:23 +00004753 }
Chris Lattner08464942007-12-28 05:29:59 +00004754
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004755 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4756 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004757 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4758 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004759
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00004760 // Check for sentinels
4761 if (NDecl)
4762 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004763
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004764 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004765 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00004766 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004767 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004768
John McCallbebede42011-02-26 05:39:39 +00004769 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00004770 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004771 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00004772 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004773 return ExprError();
4774 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004775
John McCallb268a282010-08-23 23:25:46 +00004776 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00004777}
4778
John McCalldadc5752010-08-24 06:29:42 +00004779ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004780Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004781 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00004782 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00004783 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00004784 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00004785
4786 TypeSourceInfo *TInfo;
4787 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4788 if (!TInfo)
4789 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4790
John McCallb268a282010-08-23 23:25:46 +00004791 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00004792}
4793
John McCalldadc5752010-08-24 06:29:42 +00004794ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00004795Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00004796 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00004797 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00004798
Eli Friedman37a186d2008-05-20 05:22:08 +00004799 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004800 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4801 PDiag(diag::err_illegal_decl_array_incomplete_type)
4802 << SourceRange(LParenLoc,
4803 literalExpr->getSourceRange().getEnd())))
4804 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00004805 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004806 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4807 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00004808 } else if (!literalType->isDependentType() &&
4809 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00004810 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00004811 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00004812 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004813 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00004814
Douglas Gregor85dabae2009-12-16 01:38:02 +00004815 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00004816 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004817 InitializationKind Kind
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004818 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004819 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00004820 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00004821 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00004822 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00004823 &literalType);
4824 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004825 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00004826 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00004827
Chris Lattner79413952008-12-04 23:50:19 +00004828 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00004829 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00004830 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004831 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004832 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004833
John McCall7decc9e2010-11-18 06:31:45 +00004834 // In C, compound literals are l-values for some reason.
4835 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
4836
John McCall5d7aa7f2010-01-19 22:33:45 +00004837 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCall7decc9e2010-11-18 06:31:45 +00004838 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004839}
4840
John McCalldadc5752010-08-24 06:29:42 +00004841ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00004842Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004843 SourceLocation RBraceLoc) {
4844 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00004845 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00004846
Steve Naroff30d242c2007-09-15 18:49:24 +00004847 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004848 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004849
Ted Kremenekac034612010-04-13 23:39:13 +00004850 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4851 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004852 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004853 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004854}
4855
John McCalld7646252010-11-14 08:17:51 +00004856/// Prepares for a scalar cast, performing all the necessary stages
4857/// except the final cast and returning the kind required.
4858static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
4859 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4860 // Also, callers should have filtered out the invalid cases with
4861 // pointers. Everything else should be possible.
4862
Abramo Bagnaraba854972011-01-04 09:50:03 +00004863 QualType SrcTy = Src->getType();
John McCalld7646252010-11-14 08:17:51 +00004864 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004865 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004866
John McCall8cb679e2010-11-15 09:13:47 +00004867 switch (SrcTy->getScalarTypeKind()) {
4868 case Type::STK_MemberPointer:
4869 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00004870
John McCall8cb679e2010-11-15 09:13:47 +00004871 case Type::STK_Pointer:
4872 switch (DestTy->getScalarTypeKind()) {
4873 case Type::STK_Pointer:
4874 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00004875 CK_AnyPointerToObjCPointerCast :
4876 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00004877 case Type::STK_Bool:
4878 return CK_PointerToBoolean;
4879 case Type::STK_Integral:
4880 return CK_PointerToIntegral;
4881 case Type::STK_Floating:
4882 case Type::STK_FloatingComplex:
4883 case Type::STK_IntegralComplex:
4884 case Type::STK_MemberPointer:
4885 llvm_unreachable("illegal cast from pointer");
4886 }
4887 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004888
John McCall8cb679e2010-11-15 09:13:47 +00004889 case Type::STK_Bool: // casting from bool is like casting from an integer
4890 case Type::STK_Integral:
4891 switch (DestTy->getScalarTypeKind()) {
4892 case Type::STK_Pointer:
John McCalld7646252010-11-14 08:17:51 +00004893 if (Src->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004894 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004895 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004896 case Type::STK_Bool:
4897 return CK_IntegralToBoolean;
4898 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004899 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004900 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004901 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004902 case Type::STK_IntegralComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004903 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallfcef3cf2010-12-14 17:51:41 +00004904 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004905 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004906 case Type::STK_FloatingComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004907 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004908 CK_IntegralToFloating);
4909 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004910 case Type::STK_MemberPointer:
4911 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004912 }
4913 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004914
John McCall8cb679e2010-11-15 09:13:47 +00004915 case Type::STK_Floating:
4916 switch (DestTy->getScalarTypeKind()) {
4917 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004918 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004919 case Type::STK_Bool:
4920 return CK_FloatingToBoolean;
4921 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004922 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004923 case Type::STK_FloatingComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004924 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallfcef3cf2010-12-14 17:51:41 +00004925 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004926 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004927 case Type::STK_IntegralComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004928 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004929 CK_FloatingToIntegral);
4930 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004931 case Type::STK_Pointer:
4932 llvm_unreachable("valid float->pointer cast?");
4933 case Type::STK_MemberPointer:
4934 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004935 }
4936 break;
4937
John McCall8cb679e2010-11-15 09:13:47 +00004938 case Type::STK_FloatingComplex:
4939 switch (DestTy->getScalarTypeKind()) {
4940 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004941 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004942 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004943 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004944 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00004945 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00004946 if (S.Context.hasSameType(ET, DestTy))
4947 return CK_FloatingComplexToReal;
4948 S.ImpCastExprToType(Src, ET, CK_FloatingComplexToReal);
4949 return CK_FloatingCast;
4950 }
John McCall8cb679e2010-11-15 09:13:47 +00004951 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004952 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004953 case Type::STK_Integral:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004954 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004955 CK_FloatingComplexToReal);
4956 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004957 case Type::STK_Pointer:
4958 llvm_unreachable("valid complex float->pointer cast?");
4959 case Type::STK_MemberPointer:
4960 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004961 }
4962 break;
4963
John McCall8cb679e2010-11-15 09:13:47 +00004964 case Type::STK_IntegralComplex:
4965 switch (DestTy->getScalarTypeKind()) {
4966 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004967 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004968 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004969 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004970 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00004971 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00004972 if (S.Context.hasSameType(ET, DestTy))
4973 return CK_IntegralComplexToReal;
4974 S.ImpCastExprToType(Src, ET, CK_IntegralComplexToReal);
4975 return CK_IntegralCast;
4976 }
John McCall8cb679e2010-11-15 09:13:47 +00004977 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004978 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004979 case Type::STK_Floating:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004980 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004981 CK_IntegralComplexToReal);
4982 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004983 case Type::STK_Pointer:
4984 llvm_unreachable("valid complex int->pointer cast?");
4985 case Type::STK_MemberPointer:
4986 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004987 }
4988 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00004989 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004990
John McCalld7646252010-11-14 08:17:51 +00004991 llvm_unreachable("Unhandled scalar cast");
4992 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00004993}
4994
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004995/// CheckCastTypes - Check type constraints for casting between types.
John McCall7decc9e2010-11-18 06:31:45 +00004996bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
4997 Expr *&castExpr, CastKind& Kind, ExprValueKind &VK,
4998 CXXCastPath &BasePath, bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00004999 if (getLangOptions().CPlusPlus)
Douglas Gregor15417cf2010-11-03 00:35:38 +00005000 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
5001 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00005002 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00005003 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00005004
John McCall7decc9e2010-11-18 06:31:45 +00005005 // We only support r-value casts in C.
5006 VK = VK_RValue;
5007
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005008 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
5009 // type needs to be scalar.
5010 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00005011 // We don't necessarily do lvalue-to-rvalue conversions on this.
5012 IgnoredValueConversions(castExpr);
5013
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005014 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00005015 Kind = CK_ToVoid;
Anders Carlssonef918ac2009-10-16 02:35:04 +00005016 return false;
5017 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005018
John McCall34376a62010-12-04 03:47:34 +00005019 DefaultFunctionArrayLvalueConversion(castExpr);
5020
Eli Friedmane98194d2010-07-17 20:43:49 +00005021 if (RequireCompleteType(TyR.getBegin(), castType,
5022 diag::err_typecheck_cast_to_incomplete))
5023 return true;
5024
Anders Carlssonef918ac2009-10-16 02:35:04 +00005025 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005026 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005027 (castType->isStructureType() || castType->isUnionType())) {
5028 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00005029 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005030 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
5031 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005032 Kind = CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00005033 return false;
5034 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005035
Anders Carlsson525b76b2009-10-16 02:48:28 +00005036 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005037 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005038 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005039 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005040 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005041 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005042 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00005043 castExpr->getType()) &&
5044 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005045 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
5046 << castExpr->getSourceRange();
5047 break;
5048 }
5049 }
5050 if (Field == FieldEnd)
5051 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
5052 << castExpr->getType() << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005053 Kind = CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00005054 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005055 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005056
Anders Carlsson525b76b2009-10-16 02:48:28 +00005057 // Reject any other conversions to non-scalar types.
5058 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
5059 << castType << castExpr->getSourceRange();
5060 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005061
John McCalld7646252010-11-14 08:17:51 +00005062 // The type we're casting to is known to be a scalar or vector.
5063
5064 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005065 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00005066 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00005067 return Diag(castExpr->getLocStart(),
5068 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005069 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00005070 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005071
5072 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00005073 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005074
Anders Carlsson525b76b2009-10-16 02:48:28 +00005075 if (castType->isVectorType())
5076 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
5077 if (castExpr->getType()->isVectorType())
5078 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
5079
John McCalld7646252010-11-14 08:17:51 +00005080 // The source and target types are both scalars, i.e.
5081 // - arithmetic types (fundamental, enum, and complex)
5082 // - all kinds of pointers
5083 // Note that member pointers were filtered out with C++, above.
5084
Anders Carlsson43d70f82009-10-16 05:23:41 +00005085 if (isa<ObjCSelectorExpr>(castExpr))
5086 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005087
John McCalld7646252010-11-14 08:17:51 +00005088 // If either type is a pointer, the other type has to be either an
5089 // integer or a pointer.
Anders Carlsson525b76b2009-10-16 02:48:28 +00005090 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005091 QualType castExprType = castExpr->getType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005092 if (!castExprType->isIntegralType(Context) &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005093 castExprType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005094 return Diag(castExpr->getLocStart(),
5095 diag::err_cast_pointer_from_non_pointer_int)
5096 << castExprType << castExpr->getSourceRange();
5097 } else if (!castExpr->getType()->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00005098 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005099 return Diag(castExpr->getLocStart(),
5100 diag::err_cast_pointer_to_non_pointer_int)
5101 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005102 }
Anders Carlsson094c4592009-10-18 18:12:03 +00005103
John McCalld7646252010-11-14 08:17:51 +00005104 Kind = PrepareScalarCast(*this, castExpr, castType);
John McCall2b5c1b22010-08-12 21:44:57 +00005105
John McCalld7646252010-11-14 08:17:51 +00005106 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00005107 CheckCastAlign(castExpr, castType, TyR);
5108
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005109 return false;
5110}
5111
Anders Carlsson525b76b2009-10-16 02:48:28 +00005112bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00005113 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00005114 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005115
Anders Carlssonde71adf2007-11-27 05:51:55 +00005116 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00005117 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00005118 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00005119 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00005120 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00005121 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005122 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005123 } else
5124 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00005125 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005126 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005127
John McCalle3027922010-08-25 11:45:40 +00005128 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005129 return false;
5130}
5131
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005132bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
John McCalle3027922010-08-25 11:45:40 +00005133 CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00005134 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005135
Anders Carlsson43d70f82009-10-16 05:23:41 +00005136 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005137
Nate Begemanc8961a42009-06-27 22:05:55 +00005138 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5139 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00005140 if (SrcTy->isVectorType()) {
5141 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
5142 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5143 << DestTy << SrcTy << R;
John McCalle3027922010-08-25 11:45:40 +00005144 Kind = CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00005145 return false;
5146 }
5147
Nate Begemanbd956c42009-06-28 02:36:38 +00005148 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00005149 // conversion will take place first from scalar to elt type, and then
5150 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00005151 if (SrcTy->isPointerType())
5152 return Diag(R.getBegin(),
5153 diag::err_invalid_conversion_between_vector_and_scalar)
5154 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00005155
5156 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5157 ImpCastExprToType(CastExpr, DestElemTy,
John McCalld7646252010-11-14 08:17:51 +00005158 PrepareScalarCast(*this, CastExpr, DestElemTy));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005159
John McCalle3027922010-08-25 11:45:40 +00005160 Kind = CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00005161 return false;
5162}
5163
John McCalldadc5752010-08-24 06:29:42 +00005164ExprResult
John McCallba7bf592010-08-24 05:47:05 +00005165Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00005166 SourceLocation RParenLoc, Expr *castExpr) {
5167 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00005168 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00005169
John McCall97513962010-01-15 18:39:57 +00005170 TypeSourceInfo *castTInfo;
5171 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5172 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00005173 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00005174
Nate Begeman5ec4b312009-08-10 23:49:36 +00005175 // If the Expr being casted is a ParenListExpr, handle it specially.
5176 if (isa<ParenListExpr>(castExpr))
John McCallb268a282010-08-23 23:25:46 +00005177 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCalle15bbff2010-01-18 19:35:47 +00005178 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00005179
John McCallb268a282010-08-23 23:25:46 +00005180 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00005181}
5182
John McCalldadc5752010-08-24 06:29:42 +00005183ExprResult
John McCallebe54742010-01-15 18:56:44 +00005184Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00005185 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00005186 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00005187 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00005188 CXXCastPath BasePath;
John McCallebe54742010-01-15 18:56:44 +00005189 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
John McCall7decc9e2010-11-18 06:31:45 +00005190 Kind, VK, BasePath))
Sebastian Redlb5d49352009-01-19 22:31:54 +00005191 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00005192
John McCallcf142162010-08-07 06:22:56 +00005193 return Owned(CStyleCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +00005194 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00005195 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00005196 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00005197}
5198
Nate Begeman5ec4b312009-08-10 23:49:36 +00005199/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5200/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00005201ExprResult
John McCallb268a282010-08-23 23:25:46 +00005202Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005203 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5204 if (!E)
5205 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00005206
John McCalldadc5752010-08-24 06:29:42 +00005207 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00005208
Nate Begeman5ec4b312009-08-10 23:49:36 +00005209 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00005210 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5211 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00005212
John McCallb268a282010-08-23 23:25:46 +00005213 if (Result.isInvalid()) return ExprError();
5214
5215 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005216}
5217
John McCalldadc5752010-08-24 06:29:42 +00005218ExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00005219Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00005220 SourceLocation RParenLoc, Expr *Op,
John McCalle15bbff2010-01-18 19:35:47 +00005221 TypeSourceInfo *TInfo) {
John McCallb268a282010-08-23 23:25:46 +00005222 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCalle15bbff2010-01-18 19:35:47 +00005223 QualType Ty = TInfo->getType();
John Thompson781ad172010-06-30 22:55:51 +00005224 bool isAltiVecLiteral = false;
Mike Stump11289f42009-09-09 15:08:12 +00005225
John Thompson781ad172010-06-30 22:55:51 +00005226 // Check for an altivec literal,
5227 // i.e. all the elements are integer constants.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005228 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5229 if (PE->getNumExprs() == 0) {
5230 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5231 return ExprError();
5232 }
John Thompson781ad172010-06-30 22:55:51 +00005233 if (PE->getNumExprs() == 1) {
5234 if (!PE->getExpr(0)->getType()->isVectorType())
5235 isAltiVecLiteral = true;
5236 }
5237 else
5238 isAltiVecLiteral = true;
5239 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00005240
John Thompson781ad172010-06-30 22:55:51 +00005241 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
5242 // then handle it as such.
5243 if (isAltiVecLiteral) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005244 llvm::SmallVector<Expr *, 8> initExprs;
5245 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5246 initExprs.push_back(PE->getExpr(i));
5247
5248 // FIXME: This means that pretty-printing the final AST will produce curly
5249 // braces instead of the original commas.
Ted Kremenekac034612010-04-13 23:39:13 +00005250 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5251 &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00005252 initExprs.size(), RParenLoc);
5253 E->setType(Ty);
John McCallb268a282010-08-23 23:25:46 +00005254 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005255 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005256 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00005257 // sequence of BinOp comma operators.
John McCalldadc5752010-08-24 06:29:42 +00005258 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCallb268a282010-08-23 23:25:46 +00005259 if (Result.isInvalid()) return ExprError();
5260 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005261 }
5262}
5263
John McCalldadc5752010-08-24 06:29:42 +00005264ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00005265 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005266 MultiExprArg Val,
John McCallba7bf592010-08-24 05:47:05 +00005267 ParsedType TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005268 unsigned nexprs = Val.size();
5269 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005270 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5271 Expr *expr;
5272 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5273 expr = new (Context) ParenExpr(L, R, exprs[0]);
5274 else
5275 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005276 return Owned(expr);
5277}
5278
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005279/// \brief Emit a specialized diagnostic when one expression is a null pointer
5280/// constant and the other is not a pointer.
5281bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5282 SourceLocation QuestionLoc) {
5283 Expr *NullExpr = LHS;
5284 Expr *NonPointerExpr = RHS;
5285 Expr::NullPointerConstantKind NullKind =
5286 NullExpr->isNullPointerConstant(Context,
5287 Expr::NPC_ValueDependentIsNotNull);
5288
5289 if (NullKind == Expr::NPCK_NotNull) {
5290 NullExpr = RHS;
5291 NonPointerExpr = LHS;
5292 NullKind =
5293 NullExpr->isNullPointerConstant(Context,
5294 Expr::NPC_ValueDependentIsNotNull);
5295 }
5296
5297 if (NullKind == Expr::NPCK_NotNull)
5298 return false;
5299
5300 if (NullKind == Expr::NPCK_ZeroInteger) {
5301 // In this case, check to make sure that we got here from a "NULL"
5302 // string in the source code.
5303 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00005304 SourceLocation loc = NullExpr->getExprLoc();
5305 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005306 return false;
5307 }
5308
5309 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5310 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5311 << NonPointerExpr->getType() << DiagType
5312 << NonPointerExpr->getSourceRange();
5313 return true;
5314}
5315
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005316/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5317/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00005318/// C99 6.5.15
5319QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005320 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00005321 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00005322
5323 // If either LHS or RHS are overloaded functions, try to resolve them.
5324 if (LHS->getType() == Context.OverloadTy ||
5325 RHS->getType() == Context.OverloadTy) {
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005326 ExprResult LHSResult = CheckPlaceholderExpr(LHS, QuestionLoc);
5327 if (LHSResult.isInvalid())
5328 return QualType();
5329
5330 ExprResult RHSResult = CheckPlaceholderExpr(RHS, QuestionLoc);
5331 if (RHSResult.isInvalid())
5332 return QualType();
5333
5334 LHS = LHSResult.take();
5335 RHS = RHSResult.take();
5336 }
5337
Sebastian Redl1a99f442009-04-16 17:51:27 +00005338 // C++ is sufficiently different to merit its own checker.
5339 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00005340 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00005341
5342 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005343 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005344
Chris Lattner432cff52009-02-18 04:28:32 +00005345 UsualUnaryConversions(Cond);
John McCallc07a0c72011-02-17 10:25:35 +00005346 UsualUnaryConversions(LHS);
Chris Lattner432cff52009-02-18 04:28:32 +00005347 UsualUnaryConversions(RHS);
5348 QualType CondTy = Cond->getType();
5349 QualType LHSTy = LHS->getType();
5350 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00005351
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005352 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005353 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00005354 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5355 // Throw an error if its not either.
5356 if (getLangOptions().OpenCL) {
5357 if (!CondTy->isVectorType()) {
5358 Diag(Cond->getLocStart(),
5359 diag::err_typecheck_cond_expect_scalar_or_vector)
5360 << CondTy;
5361 return QualType();
5362 }
5363 }
5364 else {
5365 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5366 << CondTy;
5367 return QualType();
5368 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005369 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005370
Chris Lattnere2949f42008-01-06 22:42:25 +00005371 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005372 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5373 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00005374
Nate Begemanabb5a732010-09-20 22:41:17 +00005375 // OpenCL: If the condition is a vector, and both operands are scalar,
5376 // attempt to implicity convert them to the vector type to act like the
5377 // built in select.
5378 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5379 // Both operands should be of scalar type.
5380 if (!LHSTy->isScalarType()) {
5381 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5382 << CondTy;
5383 return QualType();
5384 }
5385 if (!RHSTy->isScalarType()) {
5386 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5387 << CondTy;
5388 return QualType();
5389 }
5390 // Implicity convert these scalars to the type of the condition.
5391 ImpCastExprToType(LHS, CondTy, CK_IntegralCast);
5392 ImpCastExprToType(RHS, CondTy, CK_IntegralCast);
5393 }
5394
Chris Lattnere2949f42008-01-06 22:42:25 +00005395 // If both operands have arithmetic type, do the usual arithmetic conversions
5396 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00005397 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5398 UsualArithmeticConversions(LHS, RHS);
5399 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00005400 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005401
Chris Lattnere2949f42008-01-06 22:42:25 +00005402 // If both operands are the same structure or union type, the result is that
5403 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005404 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5405 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00005406 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005407 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00005408 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00005409 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00005410 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005411 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005412
Chris Lattnere2949f42008-01-06 22:42:25 +00005413 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00005414 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00005415 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5416 if (!LHSTy->isVoidType())
5417 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5418 << RHS->getSourceRange();
5419 if (!RHSTy->isVoidType())
5420 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5421 << LHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005422 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid);
5423 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00005424 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00005425 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00005426 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5427 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00005428 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005429 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005430 // promote the null to a pointer.
John McCall8cb679e2010-11-15 09:13:47 +00005431 ImpCastExprToType(RHS, LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005432 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005433 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005434 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005435 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00005436 ImpCastExprToType(LHS, RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005437 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005438 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005439
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005440 // All objective-c pointer type analysis is done here.
5441 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5442 QuestionLoc);
5443 if (!compositeType.isNull())
5444 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005445
5446
Steve Naroff05efa972009-07-01 14:36:47 +00005447 // Handle block pointer types.
5448 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5449 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5450 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5451 QualType destType = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005452 ImpCastExprToType(LHS, destType, CK_BitCast);
5453 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005454 return destType;
5455 }
5456 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005457 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00005458 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00005459 }
Steve Naroff05efa972009-07-01 14:36:47 +00005460 // We have 2 block pointer types.
5461 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5462 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00005463 return LHSTy;
5464 }
Steve Naroff05efa972009-07-01 14:36:47 +00005465 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005466 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5467 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005468
Steve Naroff05efa972009-07-01 14:36:47 +00005469 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5470 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00005471 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005472 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00005473 // In this situation, we assume void* type. No especially good
5474 // reason, but this is what gcc does, and we do have to pick
5475 // to get a consistent AST.
5476 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005477 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5478 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00005479 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005480 }
Steve Naroff05efa972009-07-01 14:36:47 +00005481 // The block pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00005482 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5483 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00005484 return LHSTy;
5485 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005486
Steve Naroff05efa972009-07-01 14:36:47 +00005487 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5488 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5489 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005490 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5491 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00005492
5493 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5494 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5495 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00005496 QualType destPointee
5497 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005498 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005499 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005500 ImpCastExprToType(LHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005501 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005502 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005503 return destType;
5504 }
5505 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00005506 QualType destPointee
5507 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005508 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005509 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005510 ImpCastExprToType(RHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005511 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005512 ImpCastExprToType(LHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005513 return destType;
5514 }
5515
5516 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5517 // Two identical pointer types are always compatible.
5518 return LHSTy;
5519 }
5520 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5521 rhptee.getUnqualifiedType())) {
5522 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5523 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5524 // In this situation, we assume void* type. No especially good
5525 // reason, but this is what gcc does, and we do have to pick
5526 // to get a consistent AST.
5527 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005528 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5529 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005530 return incompatTy;
5531 }
5532 // The pointer types are compatible.
5533 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5534 // differently qualified versions of compatible types, the result type is
5535 // a pointer to an appropriately qualified version of the *composite*
5536 // type.
5537 // FIXME: Need to calculate the composite type.
5538 // FIXME: Need to add qualifiers
John McCalle3027922010-08-25 11:45:40 +00005539 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5540 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005541 return LHSTy;
5542 }
Mike Stump11289f42009-09-09 15:08:12 +00005543
John McCalle84af4e2010-11-13 01:35:44 +00005544 // GCC compatibility: soften pointer/integer mismatch. Note that
5545 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00005546 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5547 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5548 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005549 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005550 return RHSTy;
5551 }
5552 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5553 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5554 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005555 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005556 return LHSTy;
5557 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00005558
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005559 // Emit a better diagnostic if one of the expressions is a null pointer
5560 // constant and the other is not a pointer type. In this case, the user most
5561 // likely forgot to take the address of the other expression.
5562 if (DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
5563 return QualType();
5564
Chris Lattnere2949f42008-01-06 22:42:25 +00005565 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00005566 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5567 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005568 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00005569}
5570
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005571/// FindCompositeObjCPointerType - Helper method to find composite type of
5572/// two objective-c pointer types of the two input expressions.
5573QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
5574 SourceLocation QuestionLoc) {
5575 QualType LHSTy = LHS->getType();
5576 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005577
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005578 // Handle things like Class and struct objc_class*. Here we case the result
5579 // to the pseudo-builtin, because that will be implicitly cast back to the
5580 // redefinition type if an attempt is made to access its fields.
5581 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005582 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005583 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005584 return LHSTy;
5585 }
5586 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005587 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005588 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005589 return RHSTy;
5590 }
5591 // And the same for struct objc_object* / id
5592 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005593 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005594 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005595 return LHSTy;
5596 }
5597 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005598 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005599 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005600 return RHSTy;
5601 }
5602 // And the same for struct objc_selector* / SEL
5603 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005604 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005605 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005606 return LHSTy;
5607 }
5608 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005609 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005610 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005611 return RHSTy;
5612 }
5613 // Check constraints for Objective-C object pointers types.
5614 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005615
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005616 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5617 // Two identical object pointer types are always compatible.
5618 return LHSTy;
5619 }
5620 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5621 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5622 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005623
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005624 // If both operands are interfaces and either operand can be
5625 // assigned to the other, use that type as the composite
5626 // type. This allows
5627 // xxx ? (A*) a : (B*) b
5628 // where B is a subclass of A.
5629 //
5630 // Additionally, as for assignment, if either type is 'id'
5631 // allow silent coercion. Finally, if the types are
5632 // incompatible then make sure to use 'id' as the composite
5633 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005634
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005635 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5636 // It could return the composite type.
5637 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5638 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5639 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5640 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5641 } else if ((LHSTy->isObjCQualifiedIdType() ||
5642 RHSTy->isObjCQualifiedIdType()) &&
5643 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5644 // Need to handle "id<xx>" explicitly.
5645 // GCC allows qualified id and any Objective-C type to devolve to
5646 // id. Currently localizing to here until clear this should be
5647 // part of ObjCQualifiedIdTypesAreCompatible.
5648 compositeType = Context.getObjCIdType();
5649 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5650 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005651 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005652 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5653 ;
5654 else {
5655 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5656 << LHSTy << RHSTy
5657 << LHS->getSourceRange() << RHS->getSourceRange();
5658 QualType incompatTy = Context.getObjCIdType();
John McCalle3027922010-08-25 11:45:40 +00005659 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5660 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005661 return incompatTy;
5662 }
5663 // The object pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00005664 ImpCastExprToType(LHS, compositeType, CK_BitCast);
5665 ImpCastExprToType(RHS, compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005666 return compositeType;
5667 }
5668 // Check Objective-C object pointer types and 'void *'
5669 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5670 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5671 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5672 QualType destPointee
5673 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5674 QualType destType = Context.getPointerType(destPointee);
5675 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005676 ImpCastExprToType(LHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005677 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005678 ImpCastExprToType(RHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005679 return destType;
5680 }
5681 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5682 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5683 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5684 QualType destPointee
5685 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5686 QualType destType = Context.getPointerType(destPointee);
5687 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005688 ImpCastExprToType(RHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005689 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005690 ImpCastExprToType(LHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005691 return destType;
5692 }
5693 return QualType();
5694}
5695
Steve Naroff83895f72007-09-16 03:34:24 +00005696/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005697/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005698ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005699 SourceLocation ColonLoc,
5700 Expr *CondExpr, Expr *LHSExpr,
5701 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005702 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5703 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005704 OpaqueValueExpr *opaqueValue = 0;
5705 Expr *commonExpr = 0;
5706 if (LHSExpr == 0) {
5707 commonExpr = CondExpr;
5708
5709 // We usually want to apply unary conversions *before* saving, except
5710 // in the special case of a C++ l-value conditional.
5711 if (!(getLangOptions().CPlusPlus
5712 && !commonExpr->isTypeDependent()
5713 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5714 && commonExpr->isGLValue()
5715 && commonExpr->isOrdinaryOrBitFieldObject()
5716 && RHSExpr->isOrdinaryOrBitFieldObject()
5717 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5718 UsualUnaryConversions(commonExpr);
5719 }
5720
5721 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5722 commonExpr->getType(),
5723 commonExpr->getValueKind(),
5724 commonExpr->getObjectKind());
5725 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005726 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005727
John McCall7decc9e2010-11-18 06:31:45 +00005728 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005729 ExprObjectKind OK = OK_Ordinary;
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00005730 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr,
John McCallc07a0c72011-02-17 10:25:35 +00005731 VK, OK, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00005732 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005733 return ExprError();
5734
John McCallc07a0c72011-02-17 10:25:35 +00005735 if (!commonExpr)
5736 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
5737 LHSExpr, ColonLoc,
5738 RHSExpr, result, VK, OK));
5739
5740 return Owned(new (Context)
5741 BinaryConditionalOperator(commonExpr, opaqueValue, CondExpr, LHSExpr,
5742 RHSExpr, QuestionLoc, ColonLoc, result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005743}
5744
John McCallaba90822011-01-31 23:13:11 +00005745// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005746// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005747// routine is it effectively iqnores the qualifiers on the top level pointee.
5748// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5749// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005750static Sema::AssignConvertType
5751checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5752 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5753 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005754
Steve Naroff1f4d7272007-05-11 04:00:31 +00005755 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005756 const Type *lhptee, *rhptee;
5757 Qualifiers lhq, rhq;
5758 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5759 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005760
John McCallaba90822011-01-31 23:13:11 +00005761 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005762
5763 // C99 6.5.16.1p1: This following citation is common to constraints
5764 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5765 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005766 Qualifiers lq;
5767
5768 if (!lhq.compatiblyIncludes(rhq)) {
5769 // Treat address-space mismatches as fatal. TODO: address subspaces
5770 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5771 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5772
5773 // For GCC compatibility, other qualifier mismatches are treated
5774 // as still compatible in C.
5775 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5776 }
Steve Naroff3f597292007-05-11 22:18:03 +00005777
Mike Stump4e1f26a2009-02-19 03:04:26 +00005778 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5779 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005780 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005781 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005782 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005783 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005784
Chris Lattner0a788432008-01-03 22:56:36 +00005785 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005786 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005787 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005788 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005789
Chris Lattner0a788432008-01-03 22:56:36 +00005790 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005791 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005792 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005793
5794 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005795 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005796 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005797 }
John McCall4fff8f62011-02-01 00:10:29 +00005798
Mike Stump4e1f26a2009-02-19 03:04:26 +00005799 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005800 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005801 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5802 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005803 // Check if the pointee types are compatible ignoring the sign.
5804 // We explicitly check for char so that we catch "char" vs
5805 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005806 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005807 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005808 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005809 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005810
Chris Lattnerec3a1562009-10-17 20:33:28 +00005811 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005812 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005813 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005814 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005815
John McCall4fff8f62011-02-01 00:10:29 +00005816 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005817 // Types are compatible ignoring the sign. Qualifier incompatibility
5818 // takes priority over sign incompatibility because the sign
5819 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005820 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005821 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005822
John McCallaba90822011-01-31 23:13:11 +00005823 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005824 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005825
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005826 // If we are a multi-level pointer, it's possible that our issue is simply
5827 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5828 // the eventual target type is the same and the pointers have the same
5829 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005830 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005831 do {
John McCall4fff8f62011-02-01 00:10:29 +00005832 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5833 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005834 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005835
John McCall4fff8f62011-02-01 00:10:29 +00005836 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005837 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005838 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005839
Eli Friedman80160bd2009-03-22 23:59:44 +00005840 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005841 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005842 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005843 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005844}
5845
John McCallaba90822011-01-31 23:13:11 +00005846/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005847/// block pointer types are compatible or whether a block and normal pointer
5848/// are compatible. It is more restrict than comparing two function pointer
5849// types.
John McCallaba90822011-01-31 23:13:11 +00005850static Sema::AssignConvertType
5851checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5852 QualType rhsType) {
5853 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5854 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5855
Steve Naroff081c7422008-09-04 15:10:53 +00005856 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005857
Steve Naroff081c7422008-09-04 15:10:53 +00005858 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00005859 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5860 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005861
John McCallaba90822011-01-31 23:13:11 +00005862 // In C++, the types have to match exactly.
5863 if (S.getLangOptions().CPlusPlus)
5864 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005865
John McCallaba90822011-01-31 23:13:11 +00005866 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005867
Steve Naroff081c7422008-09-04 15:10:53 +00005868 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005869 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5870 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005871
John McCallaba90822011-01-31 23:13:11 +00005872 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5873 return Sema::IncompatibleBlockPointer;
5874
Steve Naroff081c7422008-09-04 15:10:53 +00005875 return ConvTy;
5876}
5877
John McCallaba90822011-01-31 23:13:11 +00005878/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005879/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005880static Sema::AssignConvertType
5881checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5882 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5883 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5884
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005885 if (lhsType->isObjCBuiltinType()) {
5886 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005887 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5888 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005889 return Sema::IncompatiblePointer;
5890 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005891 }
5892 if (rhsType->isObjCBuiltinType()) {
5893 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005894 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5895 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005896 return Sema::IncompatiblePointer;
5897 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005898 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005899 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005900 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005901 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005902 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005903
John McCallaba90822011-01-31 23:13:11 +00005904 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5905 return Sema::CompatiblePointerDiscardsQualifiers;
5906
5907 if (S.Context.typesAreCompatible(lhsType, rhsType))
5908 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005909 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005910 return Sema::IncompatibleObjCQualifiedId;
5911 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005912}
5913
John McCall29600e12010-11-16 02:32:08 +00005914Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005915Sema::CheckAssignmentConstraints(SourceLocation Loc,
5916 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00005917 // Fake up an opaque expression. We don't actually care about what
5918 // cast operations are required, so if CheckAssignmentConstraints
5919 // adds casts to this they'll be wasted, but fortunately that doesn't
5920 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00005921 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John McCall29600e12010-11-16 02:32:08 +00005922 Expr *rhsPtr = &rhs;
5923 CastKind K = CK_Invalid;
5924
5925 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5926}
5927
Mike Stump4e1f26a2009-02-19 03:04:26 +00005928/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5929/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005930/// pointers. Here are some objectionable examples that GCC considers warnings:
5931///
5932/// int a, *pint;
5933/// short *pshort;
5934/// struct foo *pfoo;
5935///
5936/// pint = pshort; // warning: assignment from incompatible pointer type
5937/// a = pint; // warning: assignment makes integer from pointer without a cast
5938/// pint = a; // warning: assignment makes pointer from integer without a cast
5939/// pint = pfoo; // warning: assignment from incompatible pointer type
5940///
5941/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005942/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005943///
John McCall8cb679e2010-11-15 09:13:47 +00005944/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005945Sema::AssignConvertType
John McCall29600e12010-11-16 02:32:08 +00005946Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs,
John McCall8cb679e2010-11-15 09:13:47 +00005947 CastKind &Kind) {
John McCall29600e12010-11-16 02:32:08 +00005948 QualType rhsType = rhs->getType();
5949
Chris Lattnera52c2f22008-01-04 23:18:45 +00005950 // Get canonical types. We're not formatting these types, just comparing
5951 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00005952 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5953 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005954
John McCalle5255932011-01-31 22:28:28 +00005955 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00005956 if (lhsType == rhsType) {
5957 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005958 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005959 }
5960
Douglas Gregor6b754842008-10-28 00:22:11 +00005961 // If the left-hand side is a reference type, then we are in a
5962 // (rare!) case where we've allowed the use of references in C,
5963 // e.g., as a parameter type in a built-in function. In this case,
5964 // just make sure that the type referenced is compatible with the
5965 // right-hand side type. The caller is responsible for adjusting
5966 // lhsType so that the resulting expression does not have reference
5967 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005968 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005969 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5970 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005971 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005972 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005973 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005974 }
John McCalle5255932011-01-31 22:28:28 +00005975
Nate Begemanbd956c42009-06-28 02:36:38 +00005976 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5977 // to the same ExtVector type.
5978 if (lhsType->isExtVectorType()) {
5979 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005980 return Incompatible;
5981 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005982 // CK_VectorSplat does T -> vector T, so first cast to the
5983 // element type.
5984 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5985 if (elType != rhsType) {
5986 Kind = PrepareScalarCast(*this, rhs, elType);
5987 ImpCastExprToType(rhs, elType, Kind);
5988 }
5989 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005990 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005991 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005992 }
Mike Stump11289f42009-09-09 15:08:12 +00005993
John McCalle5255932011-01-31 22:28:28 +00005994 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00005995 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005996 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005997 // Allow assignments of an AltiVec vector type to an equivalent GCC
5998 // vector type and vice versa
5999 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
6000 Kind = CK_BitCast;
6001 return Compatible;
6002 }
6003
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006004 // If we are allowing lax vector conversions, and LHS and RHS are both
6005 // vectors, the total size only needs to be the same. This is a bitcast;
6006 // no bits are changed but the result type is different.
6007 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00006008 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00006009 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006010 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00006011 }
Chris Lattner881a2122008-01-04 23:32:24 +00006012 }
6013 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006014 }
Eli Friedman3360d892008-05-30 18:07:22 +00006015
John McCalle5255932011-01-31 22:28:28 +00006016 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00006017 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00006018 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00006019 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00006020 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006021 }
Eli Friedman3360d892008-05-30 18:07:22 +00006022
John McCalle5255932011-01-31 22:28:28 +00006023 // Conversions to normal pointers.
6024 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
6025 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00006026 if (isa<PointerType>(rhsType)) {
6027 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006028 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00006029 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006030
John McCalle5255932011-01-31 22:28:28 +00006031 // int -> T*
6032 if (rhsType->isIntegerType()) {
6033 Kind = CK_IntegralToPointer; // FIXME: null?
6034 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006035 }
John McCalle5255932011-01-31 22:28:28 +00006036
6037 // C pointers are not compatible with ObjC object pointers,
6038 // with two exceptions:
6039 if (isa<ObjCObjectPointerType>(rhsType)) {
6040 // - conversions to void*
6041 if (lhsPointer->getPointeeType()->isVoidType()) {
6042 Kind = CK_AnyPointerToObjCPointerCast;
6043 return Compatible;
6044 }
6045
6046 // - conversions from 'Class' to the redefinition type
6047 if (rhsType->isObjCClassType() &&
6048 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006049 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006050 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006051 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006052
John McCalle5255932011-01-31 22:28:28 +00006053 Kind = CK_BitCast;
6054 return IncompatiblePointer;
6055 }
6056
6057 // U^ -> void*
6058 if (rhsType->getAs<BlockPointerType>()) {
6059 if (lhsPointer->getPointeeType()->isVoidType()) {
6060 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006061 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006062 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006063 }
John McCalle5255932011-01-31 22:28:28 +00006064
Steve Naroff081c7422008-09-04 15:10:53 +00006065 return Incompatible;
6066 }
6067
John McCalle5255932011-01-31 22:28:28 +00006068 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00006069 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006070 // U^ -> T^
6071 if (rhsType->isBlockPointerType()) {
6072 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00006073 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006074 }
6075
6076 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006077 if (rhsType->isIntegerType()) {
6078 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00006079 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006080 }
6081
John McCalle5255932011-01-31 22:28:28 +00006082 // id -> T^
6083 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6084 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006085 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006086 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006087
John McCalle5255932011-01-31 22:28:28 +00006088 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006089 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00006090 if (RHSPT->getPointeeType()->isVoidType()) {
6091 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006092 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006093 }
John McCall8cb679e2010-11-15 09:13:47 +00006094
Chris Lattnera52c2f22008-01-04 23:18:45 +00006095 return Incompatible;
6096 }
6097
John McCalle5255932011-01-31 22:28:28 +00006098 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006099 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006100 // A* -> B*
6101 if (rhsType->isObjCObjectPointerType()) {
6102 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006103 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006104 }
6105
6106 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00006107 if (rhsType->isIntegerType()) {
6108 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00006109 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006110 }
6111
John McCalle5255932011-01-31 22:28:28 +00006112 // In general, C pointers are not compatible with ObjC object pointers,
6113 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00006114 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006115 // - conversions from 'void*'
6116 if (rhsType->isVoidPointerType()) {
6117 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006118 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006119 }
6120
6121 // - conversions to 'Class' from its redefinition type
6122 if (lhsType->isObjCClassType() &&
6123 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6124 Kind = CK_BitCast;
6125 return Compatible;
6126 }
6127
6128 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006129 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006130 }
John McCalle5255932011-01-31 22:28:28 +00006131
6132 // T^ -> A*
6133 if (rhsType->isBlockPointerType()) {
6134 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006135 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006136 }
6137
Steve Naroff7cae42b2009-07-10 23:34:53 +00006138 return Incompatible;
6139 }
John McCalle5255932011-01-31 22:28:28 +00006140
6141 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00006142 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006143 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006144 if (lhsType == Context.BoolTy) {
6145 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00006146 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006147 }
Eli Friedman3360d892008-05-30 18:07:22 +00006148
John McCalle5255932011-01-31 22:28:28 +00006149 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006150 if (lhsType->isIntegerType()) {
6151 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006152 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006153 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006154
Chris Lattnera52c2f22008-01-04 23:18:45 +00006155 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00006156 }
John McCalle5255932011-01-31 22:28:28 +00006157
6158 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006159 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006160 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006161 if (lhsType == Context.BoolTy) {
6162 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006163 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006164 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006165
John McCalle5255932011-01-31 22:28:28 +00006166 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006167 if (lhsType->isIntegerType()) {
6168 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006169 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006170 }
6171
Steve Naroff7cae42b2009-07-10 23:34:53 +00006172 return Incompatible;
6173 }
Eli Friedman3360d892008-05-30 18:07:22 +00006174
John McCalle5255932011-01-31 22:28:28 +00006175 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00006176 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006177 if (Context.typesAreCompatible(lhsType, rhsType)) {
6178 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00006179 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006180 }
Bill Wendling216423b2007-05-30 06:30:29 +00006181 }
John McCalle5255932011-01-31 22:28:28 +00006182
Steve Naroff98cf3e92007-06-06 18:38:38 +00006183 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00006184}
6185
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006186/// \brief Constructs a transparent union from an expression that is
6187/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00006188static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006189 QualType UnionType, FieldDecl *Field) {
6190 // Build an initializer list that designates the appropriate member
6191 // of the transparent union.
Ted Kremenekac034612010-04-13 23:39:13 +00006192 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00006193 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006194 SourceLocation());
6195 Initializer->setType(UnionType);
6196 Initializer->setInitializedFieldInUnion(Field);
6197
6198 // Build a compound literal constructing a value of the transparent
6199 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00006200 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall5d7aa7f2010-01-19 22:33:45 +00006201 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCall7decc9e2010-11-18 06:31:45 +00006202 VK_RValue, Initializer, false);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006203}
6204
6205Sema::AssignConvertType
6206Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
6207 QualType FromType = rExpr->getType();
6208
Mike Stump11289f42009-09-09 15:08:12 +00006209 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006210 // transparent_union GCC extension.
6211 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006212 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006213 return Incompatible;
6214
6215 // The field to initialize within the transparent union.
6216 RecordDecl *UD = UT->getDecl();
6217 FieldDecl *InitField = 0;
6218 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006219 for (RecordDecl::field_iterator it = UD->field_begin(),
6220 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006221 it != itend; ++it) {
6222 if (it->getType()->isPointerType()) {
6223 // If the transparent union contains a pointer type, we allow:
6224 // 1) void pointer
6225 // 2) null pointer constant
6226 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006227 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John McCalle3027922010-08-25 11:45:40 +00006228 ImpCastExprToType(rExpr, it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006229 InitField = *it;
6230 break;
6231 }
Mike Stump11289f42009-09-09 15:08:12 +00006232
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006233 if (rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006234 Expr::NPC_ValueDependentIsNull)) {
John McCalle84af4e2010-11-13 01:35:44 +00006235 ImpCastExprToType(rExpr, it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006236 InitField = *it;
6237 break;
6238 }
6239 }
6240
John McCall29600e12010-11-16 02:32:08 +00006241 Expr *rhs = rExpr;
John McCall8cb679e2010-11-15 09:13:47 +00006242 CastKind Kind = CK_Invalid;
John McCall29600e12010-11-16 02:32:08 +00006243 if (CheckAssignmentConstraints(it->getType(), rhs, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006244 == Compatible) {
John McCall29600e12010-11-16 02:32:08 +00006245 ImpCastExprToType(rhs, it->getType(), Kind);
6246 rExpr = rhs;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006247 InitField = *it;
6248 break;
6249 }
6250 }
6251
6252 if (!InitField)
6253 return Incompatible;
6254
6255 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
6256 return Compatible;
6257}
6258
Chris Lattner9bad62c2008-01-04 18:04:52 +00006259Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006260Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00006261 if (getLangOptions().CPlusPlus) {
6262 if (!lhsType->isRecordType()) {
6263 // C++ 5.17p3: If the left operand is not of class type, the
6264 // expression is implicitly converted (C++ 4) to the
6265 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00006266 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006267 AA_Assigning))
Douglas Gregor9a657932008-10-21 23:43:52 +00006268 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00006269 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00006270 }
6271
6272 // FIXME: Currently, we fall through and treat C++ classes like C
6273 // structures.
John McCall34376a62010-12-04 03:47:34 +00006274 }
Douglas Gregor9a657932008-10-21 23:43:52 +00006275
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006276 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6277 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00006278 if ((lhsType->isPointerType() ||
6279 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00006280 lhsType->isBlockPointerType())
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006281 && rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006282 Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00006283 ImpCastExprToType(rExpr, lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006284 return Compatible;
6285 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006286
Chris Lattnere6dcd502007-10-16 02:55:40 +00006287 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006288 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00006289 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00006290 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00006291 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00006292 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00006293 if (!lhsType->isReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00006294 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006295
John McCall8cb679e2010-11-15 09:13:47 +00006296 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006297 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00006298 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006299
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006300 // C99 6.5.16.1p2: The value of the right operand is converted to the
6301 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00006302 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6303 // so that we can use references in built-in functions even in C.
6304 // The getNonReferenceType() call makes sure that the resulting expression
6305 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006306 if (result != Incompatible && rExpr->getType() != lhsType)
John McCall8cb679e2010-11-15 09:13:47 +00006307 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006308 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006309}
6310
Chris Lattner326f7572008-11-18 01:30:42 +00006311QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006312 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006313 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00006314 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00006315 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00006316}
6317
Chris Lattnerfaa54172010-01-12 21:23:57 +00006318QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00006319 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006320 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00006321 QualType lhsType =
6322 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
6323 QualType rhsType =
6324 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006325
Nate Begeman191a6b12008-07-14 18:02:46 +00006326 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006327 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00006328 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00006329
Nate Begeman191a6b12008-07-14 18:02:46 +00006330 // Handle the case of a vector & extvector type of the same size and element
6331 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006332 if (getLangOptions().LaxVectorConversions) {
John McCall9dd450b2009-09-21 23:43:11 +00006333 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006334 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006335 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006336 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006337 if (lhsType->isExtVectorType()) {
John McCalle3027922010-08-25 11:45:40 +00006338 ImpCastExprToType(rex, lhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006339 return lhsType;
6340 }
6341
John McCalle3027922010-08-25 11:45:40 +00006342 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006343 return rhsType;
Eric Christophera613f562010-08-26 00:42:16 +00006344 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6345 // If we are allowing lax vector conversions, and LHS and RHS are both
6346 // vectors, the total size only needs to be the same. This is a
6347 // bitcast; no bits are changed but the result type is different.
6348 ImpCastExprToType(rex, lhsType, CK_BitCast);
6349 return lhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006350 }
Eric Christophera613f562010-08-26 00:42:16 +00006351 }
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006352 }
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006353 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006354
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006355 // Handle the case of equivalent AltiVec and GCC vector types
6356 if (lhsType->isVectorType() && rhsType->isVectorType() &&
6357 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John McCalle3027922010-08-25 11:45:40 +00006358 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006359 return rhsType;
6360 }
6361
Nate Begemanbd956c42009-06-28 02:36:38 +00006362 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6363 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6364 bool swapped = false;
6365 if (rhsType->isExtVectorType()) {
6366 swapped = true;
6367 std::swap(rex, lex);
6368 std::swap(rhsType, lhsType);
6369 }
Mike Stump11289f42009-09-09 15:08:12 +00006370
Nate Begeman886448d2009-06-28 19:12:57 +00006371 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00006372 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006373 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00006374 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00006375 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6376 if (order > 0)
6377 ImpCastExprToType(rex, EltTy, CK_IntegralCast);
6378 if (order >= 0) {
6379 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006380 if (swapped) std::swap(rex, lex);
6381 return lhsType;
6382 }
6383 }
6384 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6385 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00006386 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6387 if (order > 0)
6388 ImpCastExprToType(rex, EltTy, CK_FloatingCast);
6389 if (order >= 0) {
6390 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006391 if (swapped) std::swap(rex, lex);
6392 return lhsType;
6393 }
Nate Begeman330aaa72007-12-30 02:59:45 +00006394 }
6395 }
Mike Stump11289f42009-09-09 15:08:12 +00006396
Nate Begeman886448d2009-06-28 19:12:57 +00006397 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00006398 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006399 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00006400 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00006401 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00006402}
6403
Chris Lattnerfaa54172010-01-12 21:23:57 +00006404QualType Sema::CheckMultiplyDivideOperands(
6405 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00006406 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006407 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006408
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006409 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006410
Chris Lattnerfaa54172010-01-12 21:23:57 +00006411 if (!lex->getType()->isArithmeticType() ||
6412 !rex->getType()->isArithmeticType())
6413 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006414
Chris Lattnerfaa54172010-01-12 21:23:57 +00006415 // Check for division by zero.
6416 if (isDiv &&
6417 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Ted Kremenek55ae3192011-02-23 01:51:43 +00006418 DiagRuntimeBehavior(Loc, rex, PDiag(diag::warn_division_by_zero)
6419 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006420
Chris Lattnerfaa54172010-01-12 21:23:57 +00006421 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006422}
6423
Chris Lattnerfaa54172010-01-12 21:23:57 +00006424QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00006425 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006426 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006427 if (lex->getType()->hasIntegerRepresentation() &&
6428 rex->getType()->hasIntegerRepresentation())
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006429 return CheckVectorOperands(Loc, lex, rex);
6430 return InvalidOperands(Loc, lex, rex);
6431 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006432
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006433 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006434
Chris Lattnerfaa54172010-01-12 21:23:57 +00006435 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
6436 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006437
Chris Lattnerfaa54172010-01-12 21:23:57 +00006438 // Check for remainder by zero.
6439 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Ted Kremenek55ae3192011-02-23 01:51:43 +00006440 DiagRuntimeBehavior(Loc, rex, PDiag(diag::warn_remainder_by_zero)
6441 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006442
Chris Lattnerfaa54172010-01-12 21:23:57 +00006443 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006444}
6445
Chris Lattnerfaa54172010-01-12 21:23:57 +00006446QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00006447 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006448 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6449 QualType compType = CheckVectorOperands(Loc, lex, rex);
6450 if (CompLHSTy) *CompLHSTy = compType;
6451 return compType;
6452 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006453
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006454 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006455
Steve Naroffe4718892007-04-27 18:30:00 +00006456 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006457 if (lex->getType()->isArithmeticType() &&
6458 rex->getType()->isArithmeticType()) {
6459 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006460 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006461 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006462
Eli Friedman8e122982008-05-18 18:08:51 +00006463 // Put any potential pointer into PExp
6464 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00006465 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006466 std::swap(PExp, IExp);
6467
Steve Naroff6b712a72009-07-14 18:25:06 +00006468 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006469
Eli Friedman8e122982008-05-18 18:08:51 +00006470 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006471 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006472
Chris Lattner12bdebb2009-04-24 23:50:08 +00006473 // Check for arithmetic on pointers to incomplete types.
6474 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006475 if (getLangOptions().CPlusPlus) {
6476 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00006477 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00006478 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006479 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006480
6481 // GNU extension: arithmetic on pointer to void
6482 Diag(Loc, diag::ext_gnu_void_ptr)
6483 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00006484 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006485 if (getLangOptions().CPlusPlus) {
6486 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6487 << lex->getType() << lex->getSourceRange();
6488 return QualType();
6489 }
6490
6491 // GNU extension: arithmetic on pointer to function
6492 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6493 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00006494 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006495 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00006496 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00006497 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006498 PExp->getType()->isObjCObjectPointerType()) &&
6499 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00006500 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6501 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006502 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006503 return QualType();
6504 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00006505 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006506 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006507 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6508 << PointeeTy << PExp->getSourceRange();
6509 return QualType();
6510 }
Mike Stump11289f42009-09-09 15:08:12 +00006511
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006512 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00006513 QualType LHSTy = Context.isPromotableBitField(lex);
6514 if (LHSTy.isNull()) {
6515 LHSTy = lex->getType();
6516 if (LHSTy->isPromotableIntegerType())
6517 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00006518 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006519 *CompLHSTy = LHSTy;
6520 }
Eli Friedman8e122982008-05-18 18:08:51 +00006521 return PExp->getType();
6522 }
6523 }
6524
Chris Lattner326f7572008-11-18 01:30:42 +00006525 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006526}
6527
Chris Lattner2a3569b2008-04-07 05:30:13 +00006528// C99 6.5.6
6529QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006530 SourceLocation Loc, QualType* CompLHSTy) {
6531 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6532 QualType compType = CheckVectorOperands(Loc, lex, rex);
6533 if (CompLHSTy) *CompLHSTy = compType;
6534 return compType;
6535 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006536
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006537 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006538
Chris Lattner4d62f422007-12-09 21:53:25 +00006539 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006540
Chris Lattner4d62f422007-12-09 21:53:25 +00006541 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00006542 if (lex->getType()->isArithmeticType()
6543 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006544 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006545 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006546 }
Mike Stump11289f42009-09-09 15:08:12 +00006547
Chris Lattner4d62f422007-12-09 21:53:25 +00006548 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00006549 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00006550 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006551
Douglas Gregorac1fb652009-03-24 19:52:54 +00006552 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006553
Douglas Gregorac1fb652009-03-24 19:52:54 +00006554 bool ComplainAboutVoid = false;
6555 Expr *ComplainAboutFunc = 0;
6556 if (lpointee->isVoidType()) {
6557 if (getLangOptions().CPlusPlus) {
6558 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6559 << lex->getSourceRange() << rex->getSourceRange();
6560 return QualType();
6561 }
6562
6563 // GNU C extension: arithmetic on pointer to void
6564 ComplainAboutVoid = true;
6565 } else if (lpointee->isFunctionType()) {
6566 if (getLangOptions().CPlusPlus) {
6567 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006568 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006569 return QualType();
6570 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006571
6572 // GNU C extension: arithmetic on pointer to function
6573 ComplainAboutFunc = lex;
6574 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00006575 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006576 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00006577 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006578 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006579 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006580
Chris Lattner12bdebb2009-04-24 23:50:08 +00006581 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006582 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006583 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6584 << lpointee << lex->getSourceRange();
6585 return QualType();
6586 }
Mike Stump11289f42009-09-09 15:08:12 +00006587
Chris Lattner4d62f422007-12-09 21:53:25 +00006588 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00006589 if (rex->getType()->isIntegerType()) {
6590 if (ComplainAboutVoid)
6591 Diag(Loc, diag::ext_gnu_void_ptr)
6592 << lex->getSourceRange() << rex->getSourceRange();
6593 if (ComplainAboutFunc)
6594 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006595 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006596 << ComplainAboutFunc->getSourceRange();
6597
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006598 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006599 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006600 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006601
Chris Lattner4d62f422007-12-09 21:53:25 +00006602 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006603 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006604 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006605
Douglas Gregorac1fb652009-03-24 19:52:54 +00006606 // RHS must be a completely-type object type.
6607 // Handle the GNU void* extension.
6608 if (rpointee->isVoidType()) {
6609 if (getLangOptions().CPlusPlus) {
6610 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6611 << lex->getSourceRange() << rex->getSourceRange();
6612 return QualType();
6613 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006614
Douglas Gregorac1fb652009-03-24 19:52:54 +00006615 ComplainAboutVoid = true;
6616 } else if (rpointee->isFunctionType()) {
6617 if (getLangOptions().CPlusPlus) {
6618 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006619 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006620 return QualType();
6621 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006622
6623 // GNU extension: arithmetic on pointer to function
6624 if (!ComplainAboutFunc)
6625 ComplainAboutFunc = rex;
6626 } else if (!rpointee->isDependentType() &&
6627 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006628 PDiag(diag::err_typecheck_sub_ptr_object)
6629 << rex->getSourceRange()
6630 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006631 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006632
Eli Friedman168fe152009-05-16 13:54:38 +00006633 if (getLangOptions().CPlusPlus) {
6634 // Pointee types must be the same: C++ [expr.add]
6635 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6636 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6637 << lex->getType() << rex->getType()
6638 << lex->getSourceRange() << rex->getSourceRange();
6639 return QualType();
6640 }
6641 } else {
6642 // Pointee types must be compatible C99 6.5.6p3
6643 if (!Context.typesAreCompatible(
6644 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6645 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6646 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6647 << lex->getType() << rex->getType()
6648 << lex->getSourceRange() << rex->getSourceRange();
6649 return QualType();
6650 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006651 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006652
Douglas Gregorac1fb652009-03-24 19:52:54 +00006653 if (ComplainAboutVoid)
6654 Diag(Loc, diag::ext_gnu_void_ptr)
6655 << lex->getSourceRange() << rex->getSourceRange();
6656 if (ComplainAboutFunc)
6657 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006658 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006659 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006660
6661 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006662 return Context.getPointerDiffType();
6663 }
6664 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006665
Chris Lattner326f7572008-11-18 01:30:42 +00006666 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006667}
6668
Douglas Gregor0bf31402010-10-08 23:50:27 +00006669static bool isScopedEnumerationType(QualType T) {
6670 if (const EnumType *ET = dyn_cast<EnumType>(T))
6671 return ET->getDecl()->isScoped();
6672 return false;
6673}
6674
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006675static void DiagnoseBadShiftValues(Sema& S, Expr *&lex, Expr *&rex,
6676 SourceLocation Loc, unsigned Opc,
6677 QualType LHSTy) {
6678 llvm::APSInt Right;
6679 // Check right/shifter operand
6680 if (rex->isValueDependent() || !rex->isIntegerConstantExpr(Right, S.Context))
6681 return;
6682
6683 if (Right.isNegative()) {
Ted Kremenek63657fe2011-03-01 18:09:31 +00006684 S.DiagRuntimeBehavior(Loc, rex,
6685 S.PDiag(diag::warn_shift_negative)
6686 << rex->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006687 return;
6688 }
6689 llvm::APInt LeftBits(Right.getBitWidth(),
6690 S.Context.getTypeSize(lex->getType()));
6691 if (Right.uge(LeftBits)) {
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006692 S.DiagRuntimeBehavior(Loc, rex,
6693 S.PDiag(diag::warn_shift_gt_typewidth)
6694 << rex->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006695 return;
6696 }
6697 if (Opc != BO_Shl)
6698 return;
6699
6700 // When left shifting an ICE which is signed, we can check for overflow which
6701 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6702 // integers have defined behavior modulo one more than the maximum value
6703 // representable in the result type, so never warn for those.
6704 llvm::APSInt Left;
Chandler Carruth60ed89d2011-02-24 00:03:53 +00006705 if (lex->isValueDependent() || !lex->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006706 LHSTy->hasUnsignedIntegerRepresentation())
6707 return;
6708 llvm::APInt ResultBits =
6709 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6710 if (LeftBits.uge(ResultBits))
6711 return;
6712 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6713 Result = Result.shl(Right);
6714
6715 // If we are only missing a sign bit, this is less likely to result in actual
6716 // bugs -- if the result is cast back to an unsigned type, it will have the
6717 // expected value. Thus we place this behind a different warning that can be
6718 // turned off separately if needed.
6719 if (LeftBits == ResultBits - 1) {
6720 S.Diag(Loc, diag::warn_shift_result_overrides_sign_bit)
6721 << Result.toString(10) << LHSTy
6722 << lex->getSourceRange() << rex->getSourceRange();
6723 return;
6724 }
6725
6726 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
6727 << Result.toString(10) << Result.getMinSignedBits() << LHSTy
6728 << Left.getBitWidth() << lex->getSourceRange() << rex->getSourceRange();
6729}
6730
Chris Lattner2a3569b2008-04-07 05:30:13 +00006731// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00006732QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006733 unsigned Opc, bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00006734 // C99 6.5.7p2: Each of the operands shall have integer type.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006735 if (!lex->getType()->hasIntegerRepresentation() ||
6736 !rex->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006737 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006738
Douglas Gregor0bf31402010-10-08 23:50:27 +00006739 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6740 // hasIntegerRepresentation() above instead of this.
6741 if (isScopedEnumerationType(lex->getType()) ||
6742 isScopedEnumerationType(rex->getType())) {
6743 return InvalidOperands(Loc, lex, rex);
6744 }
6745
Nate Begemane46ee9a2009-10-25 02:26:48 +00006746 // Vector shifts promote their scalar inputs to vector type.
6747 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6748 return CheckVectorOperands(Loc, lex, rex);
6749
Chris Lattner5c11c412007-12-12 05:47:28 +00006750 // Shifts don't perform usual arithmetic conversions, they just do integer
6751 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006752
John McCall57cdd882010-12-16 19:28:59 +00006753 // For the LHS, do usual unary conversions, but then reset them away
6754 // if this is a compound assignment.
6755 Expr *old_lex = lex;
6756 UsualUnaryConversions(lex);
6757 QualType LHSTy = lex->getType();
6758 if (isCompAssign) lex = old_lex;
6759
6760 // The RHS is simpler.
Chris Lattner5c11c412007-12-12 05:47:28 +00006761 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006762
Ryan Flynnf53fab82009-08-07 16:20:20 +00006763 // Sanity-check shift operands
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006764 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006765
Chris Lattner5c11c412007-12-12 05:47:28 +00006766 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006767 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006768}
6769
Chandler Carruth17773fc2010-07-10 12:30:03 +00006770static bool IsWithinTemplateSpecialization(Decl *D) {
6771 if (DeclContext *DC = D->getDeclContext()) {
6772 if (isa<ClassTemplateSpecializationDecl>(DC))
6773 return true;
6774 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6775 return FD->isFunctionTemplateSpecialization();
6776 }
6777 return false;
6778}
6779
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006780// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00006781QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006782 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00006783 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006784
Chris Lattner9a152e22009-12-05 05:40:13 +00006785 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00006786 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006787 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006788
Steve Naroff31090012007-07-16 21:54:35 +00006789 QualType lType = lex->getType();
6790 QualType rType = rex->getType();
Douglas Gregor1beec452011-03-12 01:48:56 +00006791
Chandler Carruth712563b2011-02-17 08:37:06 +00006792 Expr *LHSStripped = lex->IgnoreParenImpCasts();
6793 Expr *RHSStripped = rex->IgnoreParenImpCasts();
6794 QualType LHSStrippedType = LHSStripped->getType();
6795 QualType RHSStrippedType = RHSStripped->getType();
6796
Douglas Gregor1beec452011-03-12 01:48:56 +00006797
6798
Chandler Carruth712563b2011-02-17 08:37:06 +00006799 // Two different enums will raise a warning when compared.
6800 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
6801 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
6802 if (LHSEnumType->getDecl()->getIdentifier() &&
6803 RHSEnumType->getDecl()->getIdentifier() &&
6804 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
6805 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6806 << LHSStrippedType << RHSStrippedType
6807 << lex->getSourceRange() << rex->getSourceRange();
6808 }
6809 }
6810 }
6811
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006812 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00006813 !(lType->isBlockPointerType() && isRelational) &&
6814 !lex->getLocStart().isMacroID() &&
6815 !rex->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006816 // For non-floating point types, check for self-comparisons of the form
6817 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6818 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006819 //
6820 // NOTE: Don't warn about comparison expressions resulting from macro
6821 // expansion. Also don't warn about comparisons which are only self
6822 // comparisons within a template specialization. The warnings should catch
6823 // obvious cases in the definition of the template anyways. The idea is to
6824 // warn when the typed comparison operator will always evaluate to the same
6825 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006826 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006827 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006828 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006829 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006830 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006831 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006832 << (Opc == BO_EQ
6833 || Opc == BO_LE
6834 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00006835 } else if (lType->isArrayType() && rType->isArrayType() &&
6836 !DRL->getDecl()->getType()->isReferenceType() &&
6837 !DRR->getDecl()->getType()->isReferenceType()) {
6838 // what is it always going to eval to?
6839 char always_evals_to;
6840 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006841 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006842 always_evals_to = 0; // false
6843 break;
John McCalle3027922010-08-25 11:45:40 +00006844 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006845 always_evals_to = 1; // true
6846 break;
6847 default:
6848 // best we can say is 'a constant'
6849 always_evals_to = 2; // e.g. array1 <= array2
6850 break;
6851 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006852 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006853 << 1 // array
6854 << always_evals_to);
6855 }
6856 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006857 }
Mike Stump11289f42009-09-09 15:08:12 +00006858
Chris Lattner222b8bd2009-03-08 19:39:53 +00006859 if (isa<CastExpr>(LHSStripped))
6860 LHSStripped = LHSStripped->IgnoreParenCasts();
6861 if (isa<CastExpr>(RHSStripped))
6862 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006863
Chris Lattner222b8bd2009-03-08 19:39:53 +00006864 // Warn about comparisons against a string constant (unless the other
6865 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006866 Expr *literalString = 0;
6867 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006868 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006869 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006870 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006871 literalString = lex;
6872 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006873 } else if ((isa<StringLiteral>(RHSStripped) ||
6874 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006875 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006876 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006877 literalString = rex;
6878 literalStringStripped = RHSStripped;
6879 }
6880
6881 if (literalString) {
6882 std::string resultComparison;
6883 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006884 case BO_LT: resultComparison = ") < 0"; break;
6885 case BO_GT: resultComparison = ") > 0"; break;
6886 case BO_LE: resultComparison = ") <= 0"; break;
6887 case BO_GE: resultComparison = ") >= 0"; break;
6888 case BO_EQ: resultComparison = ") == 0"; break;
6889 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006890 default: assert(false && "Invalid comparison operator");
6891 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006892
Ted Kremenek3427fac2011-02-23 01:52:04 +00006893 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006894 PDiag(diag::warn_stringcompare)
6895 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006896 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006897 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006898 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006899
Douglas Gregorec170db2010-06-08 19:50:34 +00006900 // C99 6.5.8p3 / C99 6.5.9p4
6901 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
6902 UsualArithmeticConversions(lex, rex);
6903 else {
6904 UsualUnaryConversions(lex);
6905 UsualUnaryConversions(rex);
6906 }
6907
6908 lType = lex->getType();
6909 rType = rex->getType();
6910
Douglas Gregorca63811b2008-11-19 03:25:36 +00006911 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006912 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006913
Chris Lattnerb620c342007-08-26 01:18:55 +00006914 if (isRelational) {
6915 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006916 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006917 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006918 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006919 if (lType->hasFloatingRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006920 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006921
Chris Lattnerb620c342007-08-26 01:18:55 +00006922 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006923 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006924 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006925
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006926 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006927 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006928 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006929 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006930
Douglas Gregorf267edd2010-06-15 21:38:40 +00006931 // All of the following pointer-related warnings are GCC extensions, except
6932 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00006933 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006934 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006935 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00006936 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006937 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006938
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006939 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006940 if (LCanPointeeTy == RCanPointeeTy)
6941 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006942 if (!isRelational &&
6943 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6944 // Valid unless comparison between non-null pointer and function pointer
6945 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006946 // In a SFINAE context, we treat this as a hard error to maintain
6947 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006948 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6949 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00006950 Diag(Loc,
6951 isSFINAEContext()?
6952 diag::err_typecheck_comparison_of_fptr_to_void
6953 : diag::ext_typecheck_comparison_of_fptr_to_void)
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006954 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006955
6956 if (isSFINAEContext())
6957 return QualType();
6958
John McCalle3027922010-08-25 11:45:40 +00006959 ImpCastExprToType(rex, lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006960 return ResultTy;
6961 }
6962 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006963
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006964 // C++ [expr.rel]p2:
6965 // [...] Pointer conversions (4.10) and qualification
6966 // conversions (4.4) are performed on pointer operands (or on
6967 // a pointer operand and a null pointer constant) to bring
6968 // them to their composite pointer type. [...]
6969 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006970 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006971 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006972 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006973 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006974 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006975 if (T.isNull()) {
6976 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6977 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6978 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006979 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006980 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006981 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006982 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006983 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006984 }
6985
John McCalle3027922010-08-25 11:45:40 +00006986 ImpCastExprToType(lex, T, CK_BitCast);
6987 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006988 return ResultTy;
6989 }
Eli Friedman16c209612009-08-23 00:27:47 +00006990 // C99 6.5.9p2 and C99 6.5.8p2
6991 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6992 RCanPointeeTy.getUnqualifiedType())) {
6993 // Valid unless a relational comparison of function pointers
6994 if (isRelational && LCanPointeeTy->isFunctionType()) {
6995 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
6996 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6997 }
6998 } else if (!isRelational &&
6999 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7000 // Valid unless comparison between non-null pointer and function pointer
7001 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7002 && !LHSIsNull && !RHSIsNull) {
7003 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
7004 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
7005 }
7006 } else {
7007 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00007008 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007009 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00007010 }
John McCall7684dde2011-03-11 04:25:25 +00007011 if (LCanPointeeTy != RCanPointeeTy) {
7012 if (LHSIsNull && !RHSIsNull)
7013 ImpCastExprToType(lex, rType, CK_BitCast);
7014 else
7015 ImpCastExprToType(rex, lType, CK_BitCast);
7016 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00007017 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00007018 }
Mike Stump11289f42009-09-09 15:08:12 +00007019
Sebastian Redl576fd422009-05-10 18:38:11 +00007020 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00007021 // Comparison of nullptr_t with itself.
7022 if (lType->isNullPtrType() && rType->isNullPtrType())
7023 return ResultTy;
7024
Mike Stump11289f42009-09-09 15:08:12 +00007025 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007026 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00007027 if (RHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00007028 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007029 (!isRelational && lType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00007030 ImpCastExprToType(rex, lType,
7031 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007032 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007033 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007034 return ResultTy;
7035 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007036 if (LHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00007037 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007038 (!isRelational && rType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00007039 ImpCastExprToType(lex, rType,
7040 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007041 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007042 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007043 return ResultTy;
7044 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007045
7046 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00007047 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007048 lType->isMemberPointerType() && rType->isMemberPointerType()) {
7049 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00007050 // In addition, pointers to members can be compared, or a pointer to
7051 // member and a null pointer constant. Pointer to member conversions
7052 // (4.11) and qualification conversions (4.4) are performed to bring
7053 // them to a common type. If one operand is a null pointer constant,
7054 // the common type is the type of the other operand. Otherwise, the
7055 // common type is a pointer to member type similar (4.4) to the type
7056 // of one of the operands, with a cv-qualification signature (4.4)
7057 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007058 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007059 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00007060 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007061 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007062 if (T.isNull()) {
7063 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007064 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007065 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007066 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007067 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007068 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007069 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007070 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007071 }
Mike Stump11289f42009-09-09 15:08:12 +00007072
John McCalle3027922010-08-25 11:45:40 +00007073 ImpCastExprToType(lex, T, CK_BitCast);
7074 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007075 return ResultTy;
7076 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007077
7078 // Handle scoped enumeration types specifically, since they don't promote
7079 // to integers.
7080 if (lex->getType()->isEnumeralType() &&
7081 Context.hasSameUnqualifiedType(lex->getType(), rex->getType()))
7082 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00007083 }
Mike Stump11289f42009-09-09 15:08:12 +00007084
Steve Naroff081c7422008-09-04 15:10:53 +00007085 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00007086 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007087 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
7088 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007089
Steve Naroff081c7422008-09-04 15:10:53 +00007090 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00007091 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007092 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007093 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00007094 }
John McCalle3027922010-08-25 11:45:40 +00007095 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007096 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00007097 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00007098 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00007099 if (!isRelational
7100 && ((lType->isBlockPointerType() && rType->isPointerType())
7101 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00007102 if (!LHSIsNull && !RHSIsNull) {
John McCall7684dde2011-03-11 04:25:25 +00007103 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007104 ->getPointeeType()->isVoidType())
John McCall7684dde2011-03-11 04:25:25 +00007105 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007106 ->getPointeeType()->isVoidType())))
7107 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7108 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00007109 }
John McCall7684dde2011-03-11 04:25:25 +00007110 if (LHSIsNull && !RHSIsNull)
7111 ImpCastExprToType(lex, rType, CK_BitCast);
7112 else
7113 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007114 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00007115 }
Steve Naroff081c7422008-09-04 15:10:53 +00007116
John McCall7684dde2011-03-11 04:25:25 +00007117 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
7118 const PointerType *LPT = lType->getAs<PointerType>();
7119 const PointerType *RPT = rType->getAs<PointerType>();
7120 if (LPT || RPT) {
7121 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7122 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007123
Steve Naroff753567f2008-11-17 19:49:16 +00007124 if (!LPtrToVoid && !RPtrToVoid &&
7125 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007126 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007127 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007128 }
John McCall7684dde2011-03-11 04:25:25 +00007129 if (LHSIsNull && !RHSIsNull)
7130 ImpCastExprToType(lex, rType, CK_BitCast);
7131 else
7132 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007133 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00007134 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007135 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007136 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007137 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
7138 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
John McCall7684dde2011-03-11 04:25:25 +00007139 if (LHSIsNull && !RHSIsNull)
7140 ImpCastExprToType(lex, rType, CK_BitCast);
7141 else
7142 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007143 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00007144 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00007145 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007146 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7147 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00007148 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007149 bool isError = false;
7150 if ((LHSIsNull && lType->isIntegerType()) ||
7151 (RHSIsNull && rType->isIntegerType())) {
7152 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007153 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007154 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007155 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007156 else if (getLangOptions().CPlusPlus) {
7157 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7158 isError = true;
7159 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00007160 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00007161
Chris Lattnerd99bd522009-08-23 00:03:44 +00007162 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007163 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00007164 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007165 if (isError)
7166 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00007167 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007168
7169 if (lType->isIntegerType())
John McCalle84af4e2010-11-13 01:35:44 +00007170 ImpCastExprToType(lex, rType,
7171 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00007172 else
John McCalle84af4e2010-11-13 01:35:44 +00007173 ImpCastExprToType(rex, lType,
7174 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007175 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00007176 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007177
Steve Naroff4b191572008-09-04 16:56:14 +00007178 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00007179 if (!isRelational && RHSIsNull
7180 && lType->isBlockPointerType() && rType->isIntegerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00007181 ImpCastExprToType(rex, lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007182 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007183 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00007184 if (!isRelational && LHSIsNull
7185 && lType->isIntegerType() && rType->isBlockPointerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00007186 ImpCastExprToType(lex, rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007187 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007188 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007189
Chris Lattner326f7572008-11-18 01:30:42 +00007190 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007191}
7192
Nate Begeman191a6b12008-07-14 18:02:46 +00007193/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00007194/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00007195/// like a scalar comparison, a vector comparison produces a vector of integer
7196/// types.
7197QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00007198 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00007199 bool isRelational) {
7200 // Check to make sure we're operating on vectors of the same type and width,
7201 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00007202 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00007203 if (vType.isNull())
7204 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007205
Anton Yartsev3f8f2882010-11-18 03:19:30 +00007206 // If AltiVec, the comparison results in a numeric type, i.e.
7207 // bool for C++, int for C
7208 if (getLangOptions().AltiVec)
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007209 return Context.getLogicalOperationType();
Anton Yartsev3f8f2882010-11-18 03:19:30 +00007210
Nate Begeman191a6b12008-07-14 18:02:46 +00007211 QualType lType = lex->getType();
7212 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007213
Nate Begeman191a6b12008-07-14 18:02:46 +00007214 // For non-floating point types, check for self-comparisons of the form
7215 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7216 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007217 if (!lType->hasFloatingRepresentation()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00007218 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
7219 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
7220 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007221 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007222 PDiag(diag::warn_comparison_always)
7223 << 0 // self-
7224 << 2 // "a constant"
7225 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007226 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007227
Nate Begeman191a6b12008-07-14 18:02:46 +00007228 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007229 if (!isRelational && lType->hasFloatingRepresentation()) {
7230 assert (rType->hasFloatingRepresentation());
Chris Lattner326f7572008-11-18 01:30:42 +00007231 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00007232 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007233
Nate Begeman191a6b12008-07-14 18:02:46 +00007234 // Return the type for the comparison, which is the same as vector type for
7235 // integer vectors, or an integer type of identical size and number of
7236 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007237 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00007238 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007239
John McCall9dd450b2009-09-21 23:43:11 +00007240 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00007241 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007242 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00007243 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00007244 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007245 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7246
Mike Stump4e1f26a2009-02-19 03:04:26 +00007247 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007248 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00007249 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7250}
7251
Steve Naroff218bc2b2007-05-04 21:54:46 +00007252inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00007253 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007254 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
7255 if (lex->getType()->hasIntegerRepresentation() &&
7256 rex->getType()->hasIntegerRepresentation())
7257 return CheckVectorOperands(Loc, lex, rex);
7258
7259 return InvalidOperands(Loc, lex, rex);
7260 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007261
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007262 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007263
Douglas Gregor0bf31402010-10-08 23:50:27 +00007264 if (lex->getType()->isIntegralOrUnscopedEnumerationType() &&
7265 rex->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007266 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00007267 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007268}
7269
Steve Naroff218bc2b2007-05-04 21:54:46 +00007270inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner8406c512010-07-13 19:41:32 +00007271 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
7272
7273 // Diagnose cases where the user write a logical and/or but probably meant a
7274 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7275 // is a constant.
7276 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
Eli Friedman6b197e02010-07-27 19:14:53 +00007277 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
Chris Lattnerdeee7a32010-07-15 00:26:43 +00007278 // Don't warn in macros.
Chris Lattner938533d2010-07-24 01:10:11 +00007279 !Loc.isMacroID()) {
7280 // If the RHS can be constant folded, and if it constant folds to something
7281 // that isn't 0 or 1 (which indicate a potential logical operation that
7282 // happened to fold to true/false) then warn.
7283 Expr::EvalResult Result;
7284 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
7285 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
7286 Diag(Loc, diag::warn_logical_instead_of_bitwise)
7287 << rex->getSourceRange()
John McCalle3027922010-08-25 11:45:40 +00007288 << (Opc == BO_LAnd ? "&&" : "||")
7289 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00007290 }
7291 }
Chris Lattner8406c512010-07-13 19:41:32 +00007292
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007293 if (!Context.getLangOptions().CPlusPlus) {
7294 UsualUnaryConversions(lex);
7295 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007296
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007297 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
7298 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007299
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007300 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007301 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007302
John McCall4a2429a2010-06-04 00:29:51 +00007303 // The following is safe because we only use this method for
7304 // non-overloadable operands.
7305
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007306 // C++ [expr.log.and]p1
7307 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007308 // The operands are both contextually converted to type bool.
7309 if (PerformContextuallyConvertToBool(lex) ||
7310 PerformContextuallyConvertToBool(rex))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007311 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007312
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007313 // C++ [expr.log.and]p2
7314 // C++ [expr.log.or]p2
7315 // The result is a bool.
7316 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007317}
7318
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007319/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7320/// is a read-only property; return true if so. A readonly property expression
7321/// depends on various declarations and thus must be treated specially.
7322///
Mike Stump11289f42009-09-09 15:08:12 +00007323static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007324 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7325 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00007326 if (PropExpr->isImplicitProperty()) return false;
7327
7328 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7329 QualType BaseType = PropExpr->isSuperReceiver() ?
7330 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007331 PropExpr->getBase()->getType();
7332
John McCallb7bd14f2010-12-02 01:19:52 +00007333 if (const ObjCObjectPointerType *OPT =
7334 BaseType->getAsObjCInterfacePointerType())
7335 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7336 if (S.isPropertyReadonly(PDecl, IFace))
7337 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007338 }
7339 return false;
7340}
7341
Chris Lattner30bd3272008-11-18 01:22:49 +00007342/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7343/// emit an error and return true. If so, return false.
7344static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007345 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007346 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007347 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007348 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7349 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00007350 if (IsLV == Expr::MLV_Valid)
7351 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007352
Chris Lattner30bd3272008-11-18 01:22:49 +00007353 unsigned Diag = 0;
7354 bool NeedType = false;
7355 switch (IsLV) { // C99 6.5.16p2
Chris Lattner30bd3272008-11-18 01:22:49 +00007356 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007357 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007358 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7359 NeedType = true;
7360 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007361 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007362 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7363 NeedType = true;
7364 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007365 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007366 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7367 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007368 case Expr::MLV_Valid:
7369 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007370 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007371 case Expr::MLV_MemberFunction:
7372 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007373 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7374 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007375 case Expr::MLV_IncompleteType:
7376 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007377 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007378 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00007379 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00007380 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007381 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7382 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00007383 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00007384 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7385 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007386 case Expr::MLV_ReadonlyProperty:
7387 Diag = diag::error_readonly_property_assignment;
7388 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007389 case Expr::MLV_NoSetterProperty:
7390 Diag = diag::error_nosetter_property_assignment;
7391 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007392 case Expr::MLV_SubObjCPropertySetting:
7393 Diag = diag::error_no_subobject_property_setting;
7394 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007395 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007396
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007397 SourceRange Assign;
7398 if (Loc != OrigLoc)
7399 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007400 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007401 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007402 else
Mike Stump11289f42009-09-09 15:08:12 +00007403 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007404 return true;
7405}
7406
7407
7408
7409// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00007410QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
7411 SourceLocation Loc,
7412 QualType CompoundType) {
7413 // Verify that LHS is a modifiable lvalue, and emit error if not.
7414 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007415 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007416
7417 QualType LHSType = LHS->getType();
7418 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007419 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007420 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007421 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007422 // Simple assignment "x = y".
John McCall34376a62010-12-04 03:47:34 +00007423 if (LHS->getObjectKind() == OK_ObjCProperty)
7424 ConvertPropertyForLValue(LHS, RHS, LHSTy);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007425 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007426 // Special case of NSObject attributes on c-style pointer types.
7427 if (ConvTy == IncompatiblePointer &&
7428 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007429 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007430 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007431 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007432 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007433
John McCall7decc9e2010-11-18 06:31:45 +00007434 if (ConvTy == Compatible &&
7435 getLangOptions().ObjCNonFragileABI &&
7436 LHSType->isObjCObjectType())
7437 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7438 << LHSType;
7439
Chris Lattnerea714382008-08-21 18:04:13 +00007440 // If the RHS is a unary plus or minus, check to see if they = and + are
7441 // right next to each other. If so, the user may have typo'd "x =+ 4"
7442 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00007443 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00007444 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7445 RHSCheck = ICE->getSubExpr();
7446 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007447 if ((UO->getOpcode() == UO_Plus ||
7448 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007449 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007450 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00007451 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7452 // And there is a space or other character before the subexpr of the
7453 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00007454 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7455 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007456 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007457 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007458 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007459 }
Chris Lattnerea714382008-08-21 18:04:13 +00007460 }
7461 } else {
7462 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007463 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007464 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007465
Chris Lattner326f7572008-11-18 01:30:42 +00007466 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007467 RHS, AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007468 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007469
Chris Lattner39561062010-07-07 06:14:23 +00007470
7471 // Check to see if the destination operand is a dereferenced null pointer. If
7472 // so, and if not volatile-qualified, this is undefined behavior that the
7473 // optimizer will delete, so warn about it. People sometimes try to use this
7474 // to get a deterministic trap and are surprised by clang's behavior. This
7475 // only handles the pattern "*null = whatever", which is a very syntactic
7476 // check.
7477 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
John McCalle3027922010-08-25 11:45:40 +00007478 if (UO->getOpcode() == UO_Deref &&
Chris Lattner39561062010-07-07 06:14:23 +00007479 UO->getSubExpr()->IgnoreParenCasts()->
7480 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
7481 !UO->getType().isVolatileQualified()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00007482 DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7483 PDiag(diag::warn_indirection_through_null)
7484 << UO->getSubExpr()->getSourceRange());
7485 DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7486 PDiag(diag::note_indirection_through_null));
Chris Lattner39561062010-07-07 06:14:23 +00007487 }
7488
Ted Kremenek64699be2011-02-16 01:57:07 +00007489 // Check for trivial buffer overflows.
Ted Kremenekdf26df72011-03-01 18:41:00 +00007490 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremenek64699be2011-02-16 01:57:07 +00007491
Steve Naroff98cf3e92007-06-06 18:38:38 +00007492 // C99 6.5.16p3: The type of an assignment expression is the type of the
7493 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007494 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007495 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7496 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007497 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007498 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007499 return (getLangOptions().CPlusPlus
7500 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007501}
7502
Chris Lattner326f7572008-11-18 01:30:42 +00007503// C99 6.5.17
John McCall34376a62010-12-04 03:47:34 +00007504static QualType CheckCommaOperands(Sema &S, Expr *&LHS, Expr *&RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007505 SourceLocation Loc) {
7506 S.DiagnoseUnusedExprResult(LHS);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007507
John McCall4bc41ae2010-11-18 19:01:18 +00007508 ExprResult LHSResult = S.CheckPlaceholderExpr(LHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007509 if (LHSResult.isInvalid())
7510 return QualType();
7511
John McCall4bc41ae2010-11-18 19:01:18 +00007512 ExprResult RHSResult = S.CheckPlaceholderExpr(RHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007513 if (RHSResult.isInvalid())
7514 return QualType();
7515 RHS = RHSResult.take();
7516
John McCall73d36182010-10-12 07:14:40 +00007517 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7518 // operands, but not unary promotions.
7519 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007520
John McCall34376a62010-12-04 03:47:34 +00007521 // So we treat the LHS as a ignored value, and in C++ we allow the
7522 // containing site to determine what should be done with the RHS.
7523 S.IgnoredValueConversions(LHS);
7524
7525 if (!S.getLangOptions().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007526 S.DefaultFunctionArrayLvalueConversion(RHS);
John McCall73d36182010-10-12 07:14:40 +00007527 if (!RHS->getType()->isVoidType())
John McCall4bc41ae2010-11-18 19:01:18 +00007528 S.RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007529 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007530
Chris Lattner326f7572008-11-18 01:30:42 +00007531 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007532}
7533
Steve Naroff7a5af782007-07-13 16:58:59 +00007534/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7535/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007536static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7537 ExprValueKind &VK,
7538 SourceLocation OpLoc,
7539 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007540 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007541 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007542
Chris Lattner6b0cf142008-11-21 07:05:48 +00007543 QualType ResType = Op->getType();
7544 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007545
John McCall4bc41ae2010-11-18 19:01:18 +00007546 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007547 // Decrement of bool is not allowed.
7548 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007549 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007550 return QualType();
7551 }
7552 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007553 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007554 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007555 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007556 } else if (ResType->isAnyPointerType()) {
7557 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00007558
Chris Lattner6b0cf142008-11-21 07:05:48 +00007559 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00007560 if (PointeeTy->isVoidType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007561 if (S.getLangOptions().CPlusPlus) {
7562 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007563 << Op->getSourceRange();
7564 return QualType();
7565 }
7566
7567 // Pointer to void is a GNU extension in C.
John McCall4bc41ae2010-11-18 19:01:18 +00007568 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00007569 } else if (PointeeTy->isFunctionType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007570 if (S.getLangOptions().CPlusPlus) {
7571 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007572 << Op->getType() << Op->getSourceRange();
7573 return QualType();
7574 }
7575
John McCall4bc41ae2010-11-18 19:01:18 +00007576 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007577 << ResType << Op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007578 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
7579 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00007580 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00007581 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00007582 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007583 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00007584 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7585 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007586 << PointeeTy << Op->getSourceRange();
7587 return QualType();
7588 }
Eli Friedman090addd2010-01-03 00:20:48 +00007589 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007590 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007591 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007592 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007593 } else if (ResType->isPlaceholderType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007594 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007595 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007596 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7597 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00007598 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7599 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007600 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007601 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00007602 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007603 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007604 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007605 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007606 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007607 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007608 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007609 // In C++, a prefix increment is the same type as the operand. Otherwise
7610 // (in C or with postfix), the increment is the unqualified type of the
7611 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00007612 if (isPrefix && S.getLangOptions().CPlusPlus) {
7613 VK = VK_LValue;
7614 return ResType;
7615 } else {
7616 VK = VK_RValue;
7617 return ResType.getUnqualifiedType();
7618 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007619}
7620
John McCall34376a62010-12-04 03:47:34 +00007621void Sema::ConvertPropertyForRValue(Expr *&E) {
7622 assert(E->getValueKind() == VK_LValue &&
7623 E->getObjectKind() == OK_ObjCProperty);
7624 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7625
7626 ExprValueKind VK = VK_RValue;
7627 if (PRE->isImplicitProperty()) {
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007628 if (const ObjCMethodDecl *GetterMethod =
7629 PRE->getImplicitPropertyGetter()) {
7630 QualType Result = GetterMethod->getResultType();
7631 VK = Expr::getValueKindForType(Result);
7632 }
7633 else {
7634 Diag(PRE->getLocation(), diag::err_getter_not_found)
7635 << PRE->getBase()->getType();
7636 }
John McCall34376a62010-12-04 03:47:34 +00007637 }
7638
7639 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
7640 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007641
7642 ExprResult Result = MaybeBindToTemporary(E);
7643 if (!Result.isInvalid())
7644 E = Result.take();
John McCall34376a62010-12-04 03:47:34 +00007645}
7646
7647void Sema::ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType &LHSTy) {
7648 assert(LHS->getValueKind() == VK_LValue &&
7649 LHS->getObjectKind() == OK_ObjCProperty);
7650 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7651
7652 if (PRE->isImplicitProperty()) {
7653 // If using property-dot syntax notation for assignment, and there is a
7654 // setter, RHS expression is being passed to the setter argument. So,
7655 // type conversion (and comparison) is RHS to setter's argument type.
7656 if (const ObjCMethodDecl *SetterMD = PRE->getImplicitPropertySetter()) {
7657 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7658 LHSTy = (*P)->getType();
7659
7660 // Otherwise, if the getter returns an l-value, just call that.
7661 } else {
7662 QualType Result = PRE->getImplicitPropertyGetter()->getResultType();
7663 ExprValueKind VK = Expr::getValueKindForType(Result);
7664 if (VK == VK_LValue) {
7665 LHS = ImplicitCastExpr::Create(Context, LHS->getType(),
7666 CK_GetObjCProperty, LHS, 0, VK);
7667 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007668 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007669 }
John McCall34376a62010-12-04 03:47:34 +00007670 }
7671
7672 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007673 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007674 InitializedEntity::InitializeParameter(Context, LHSTy);
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007675 Expr *Arg = RHS;
7676 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(),
7677 Owned(Arg));
7678 if (!ArgE.isInvalid())
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007679 RHS = ArgE.takeAs<Expr>();
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007680 }
7681}
7682
7683
Anders Carlsson806700f2008-02-01 07:15:58 +00007684/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007685/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007686/// where the declaration is needed for type checking. We only need to
7687/// handle cases when the expression references a function designator
7688/// or is an lvalue. Here are some examples:
7689/// - &(x) => x
7690/// - &*****f => f for f a function designator.
7691/// - &s.xx => s
7692/// - &s.zz[1].yy -> s, if zz is an array
7693/// - *(x + 1) -> x, if x is an array
7694/// - &"123"[2] -> 0
7695/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007696static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007697 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007698 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007699 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007700 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007701 // If this is an arrow operator, the address is an offset from
7702 // the base's value, so the object the base refers to is
7703 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007704 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007705 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007706 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007707 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007708 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007709 // FIXME: This code shouldn't be necessary! We should catch the implicit
7710 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007711 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7712 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7713 if (ICE->getSubExpr()->getType()->isArrayType())
7714 return getPrimaryDecl(ICE->getSubExpr());
7715 }
7716 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007717 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007718 case Stmt::UnaryOperatorClass: {
7719 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007720
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007721 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007722 case UO_Real:
7723 case UO_Imag:
7724 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007725 return getPrimaryDecl(UO->getSubExpr());
7726 default:
7727 return 0;
7728 }
7729 }
Steve Naroff47500512007-04-19 23:00:49 +00007730 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007731 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007732 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007733 // If the result of an implicit cast is an l-value, we care about
7734 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007735 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007736 default:
7737 return 0;
7738 }
7739}
7740
7741/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007742/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007743/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007744/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007745/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007746/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007747/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007748static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7749 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007750 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007751 return S.Context.DependentTy;
7752 if (OrigOp->getType() == S.Context.OverloadTy)
7753 return S.Context.OverloadTy;
John McCall8d08b9b2010-08-27 09:08:28 +00007754
John McCall4bc41ae2010-11-18 19:01:18 +00007755 ExprResult PR = S.CheckPlaceholderExpr(OrigOp, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007756 if (PR.isInvalid()) return QualType();
7757 OrigOp = PR.take();
7758
John McCall8d08b9b2010-08-27 09:08:28 +00007759 // Make sure to ignore parentheses in subsequent checks
7760 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007761
John McCall4bc41ae2010-11-18 19:01:18 +00007762 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007763 // Implement C99-only parts of addressof rules.
7764 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007765 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007766 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7767 // (assuming the deref expression is valid).
7768 return uOp->getSubExpr()->getType();
7769 }
7770 // Technically, there should be a check for array subscript
7771 // expressions here, but the result of one is always an lvalue anyway.
7772 }
John McCallf3a88602011-02-03 08:15:49 +00007773 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007774 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00007775
Chris Lattner9156f1b2010-07-05 19:17:26 +00007776 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007777 bool sfinae = S.isSFINAEContext();
7778 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7779 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007780 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007781 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007782 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007783 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007784 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007785 } else if (lval == Expr::LV_MemberFunction) {
7786 // If it's an instance method, make a member pointer.
7787 // The expression must have exactly the form &A::foo.
7788
7789 // If the underlying expression isn't a decl ref, give up.
7790 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007791 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007792 << OrigOp->getSourceRange();
7793 return QualType();
7794 }
7795 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7796 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7797
7798 // The id-expression was parenthesized.
7799 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007800 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007801 << OrigOp->getSourceRange();
7802
7803 // The method was named without a qualifier.
7804 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007805 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007806 << op->getSourceRange();
7807 }
7808
John McCall4bc41ae2010-11-18 19:01:18 +00007809 return S.Context.getMemberPointerType(op->getType(),
7810 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007811 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007812 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007813 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007814 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007815 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007816 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007817 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007818 return QualType();
7819 }
John McCall086a4642010-11-24 05:12:34 +00007820 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007821 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00007822 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00007823 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00007824 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007825 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007826 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00007827 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00007828 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007829 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007830 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007831 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00007832 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00007833 << "property expression" << op->getSourceRange();
7834 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007835 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007836 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007837 // with the register storage-class specifier.
7838 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007839 // in C++ it is not error to take address of a register
7840 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007841 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007842 !S.getLangOptions().CPlusPlus) {
7843 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00007844 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007845 return QualType();
7846 }
John McCalld14a8642009-11-21 08:51:07 +00007847 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007848 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007849 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007850 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007851 // Could be a pointer to member, though, if there is an explicit
7852 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007853 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007854 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007855 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007856 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007857 S.Diag(OpLoc,
7858 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007859 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007860 return QualType();
7861 }
Mike Stump11289f42009-09-09 15:08:12 +00007862
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007863 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7864 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007865 return S.Context.getMemberPointerType(op->getType(),
7866 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007867 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007868 }
Anders Carlsson5b535762009-05-16 21:43:42 +00007869 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00007870 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007871 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007872
Eli Friedmance7f9002009-05-16 23:27:50 +00007873 if (lval == Expr::LV_IncompleteVoidType) {
7874 // Taking the address of a void variable is technically illegal, but we
7875 // allow it in cases which are otherwise valid.
7876 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007877 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007878 }
7879
Steve Naroff47500512007-04-19 23:00:49 +00007880 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007881 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007882 return S.Context.getObjCObjectPointerType(op->getType());
7883 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007884}
7885
Chris Lattner9156f1b2010-07-05 19:17:26 +00007886/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007887static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7888 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007889 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007890 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007891
John McCall4bc41ae2010-11-18 19:01:18 +00007892 S.UsualUnaryConversions(Op);
Chris Lattner9156f1b2010-07-05 19:17:26 +00007893 QualType OpTy = Op->getType();
7894 QualType Result;
7895
7896 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7897 // is an incomplete type or void. It would be possible to warn about
7898 // dereferencing a void pointer, but it's completely well-defined, and such a
7899 // warning is unlikely to catch any mistakes.
7900 if (const PointerType *PT = OpTy->getAs<PointerType>())
7901 Result = PT->getPointeeType();
7902 else if (const ObjCObjectPointerType *OPT =
7903 OpTy->getAs<ObjCObjectPointerType>())
7904 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007905 else {
John McCall4bc41ae2010-11-18 19:01:18 +00007906 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007907 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007908 if (PR.take() != Op)
7909 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007910 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007911
Chris Lattner9156f1b2010-07-05 19:17:26 +00007912 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007913 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007914 << OpTy << Op->getSourceRange();
7915 return QualType();
7916 }
John McCall4bc41ae2010-11-18 19:01:18 +00007917
7918 // Dereferences are usually l-values...
7919 VK = VK_LValue;
7920
7921 // ...except that certain expressions are never l-values in C.
7922 if (!S.getLangOptions().CPlusPlus &&
7923 IsCForbiddenLValueType(S.Context, Result))
7924 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007925
7926 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007927}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007928
John McCalle3027922010-08-25 11:45:40 +00007929static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007930 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007931 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007932 switch (Kind) {
7933 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007934 case tok::periodstar: Opc = BO_PtrMemD; break;
7935 case tok::arrowstar: Opc = BO_PtrMemI; break;
7936 case tok::star: Opc = BO_Mul; break;
7937 case tok::slash: Opc = BO_Div; break;
7938 case tok::percent: Opc = BO_Rem; break;
7939 case tok::plus: Opc = BO_Add; break;
7940 case tok::minus: Opc = BO_Sub; break;
7941 case tok::lessless: Opc = BO_Shl; break;
7942 case tok::greatergreater: Opc = BO_Shr; break;
7943 case tok::lessequal: Opc = BO_LE; break;
7944 case tok::less: Opc = BO_LT; break;
7945 case tok::greaterequal: Opc = BO_GE; break;
7946 case tok::greater: Opc = BO_GT; break;
7947 case tok::exclaimequal: Opc = BO_NE; break;
7948 case tok::equalequal: Opc = BO_EQ; break;
7949 case tok::amp: Opc = BO_And; break;
7950 case tok::caret: Opc = BO_Xor; break;
7951 case tok::pipe: Opc = BO_Or; break;
7952 case tok::ampamp: Opc = BO_LAnd; break;
7953 case tok::pipepipe: Opc = BO_LOr; break;
7954 case tok::equal: Opc = BO_Assign; break;
7955 case tok::starequal: Opc = BO_MulAssign; break;
7956 case tok::slashequal: Opc = BO_DivAssign; break;
7957 case tok::percentequal: Opc = BO_RemAssign; break;
7958 case tok::plusequal: Opc = BO_AddAssign; break;
7959 case tok::minusequal: Opc = BO_SubAssign; break;
7960 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7961 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7962 case tok::ampequal: Opc = BO_AndAssign; break;
7963 case tok::caretequal: Opc = BO_XorAssign; break;
7964 case tok::pipeequal: Opc = BO_OrAssign; break;
7965 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007966 }
7967 return Opc;
7968}
7969
John McCalle3027922010-08-25 11:45:40 +00007970static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007971 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007972 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007973 switch (Kind) {
7974 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007975 case tok::plusplus: Opc = UO_PreInc; break;
7976 case tok::minusminus: Opc = UO_PreDec; break;
7977 case tok::amp: Opc = UO_AddrOf; break;
7978 case tok::star: Opc = UO_Deref; break;
7979 case tok::plus: Opc = UO_Plus; break;
7980 case tok::minus: Opc = UO_Minus; break;
7981 case tok::tilde: Opc = UO_Not; break;
7982 case tok::exclaim: Opc = UO_LNot; break;
7983 case tok::kw___real: Opc = UO_Real; break;
7984 case tok::kw___imag: Opc = UO_Imag; break;
7985 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007986 }
7987 return Opc;
7988}
7989
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007990/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7991/// This warning is only emitted for builtin assignment operations. It is also
7992/// suppressed in the event of macro expansions.
7993static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7994 SourceLocation OpLoc) {
7995 if (!S.ActiveTemplateInstantiations.empty())
7996 return;
7997 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7998 return;
7999 lhs = lhs->IgnoreParenImpCasts();
8000 rhs = rhs->IgnoreParenImpCasts();
8001 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
8002 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
8003 if (!LeftDeclRef || !RightDeclRef ||
8004 LeftDeclRef->getLocation().isMacroID() ||
8005 RightDeclRef->getLocation().isMacroID())
8006 return;
8007 const ValueDecl *LeftDecl =
8008 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
8009 const ValueDecl *RightDecl =
8010 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
8011 if (LeftDecl != RightDecl)
8012 return;
8013 if (LeftDecl->getType().isVolatileQualified())
8014 return;
8015 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
8016 if (RefTy->getPointeeType().isVolatileQualified())
8017 return;
8018
8019 S.Diag(OpLoc, diag::warn_self_assignment)
8020 << LeftDeclRef->getType()
8021 << lhs->getSourceRange() << rhs->getSourceRange();
8022}
8023
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008024/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8025/// operator @p Opc at location @c TokLoc. This routine only supports
8026/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00008027ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008028 BinaryOperatorKind Opc,
John McCalle3027922010-08-25 11:45:40 +00008029 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008030 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008031 // The following two variables are used for compound assignment operators
8032 QualType CompLHSTy; // Type of LHS after promotions for computation
8033 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00008034 ExprValueKind VK = VK_RValue;
8035 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008036
Douglas Gregor1beec452011-03-12 01:48:56 +00008037 // Check if a 'foo<int>' involved in a binary op, identifies a single
8038 // function unambiguously (i.e. an lvalue ala 13.4)
8039 // But since an assignment can trigger target based overload, exclude it in
8040 // our blind search. i.e:
8041 // template<class T> void f(); template<class T, class U> void f(U);
8042 // f<int> == 0; // resolve f<int> blindly
8043 // void (*p)(int); p = f<int>; // resolve f<int> using target
8044 if (Opc != BO_Assign) {
8045 if (lhs->getType() == Context.OverloadTy) {
8046 ExprResult resolvedLHS =
8047 ResolveAndFixSingleFunctionTemplateSpecialization(lhs);
8048 if (resolvedLHS.isUsable()) lhs = resolvedLHS.release();
8049 }
8050 if (rhs->getType() == Context.OverloadTy) {
8051 ExprResult resolvedRHS =
8052 ResolveAndFixSingleFunctionTemplateSpecialization(rhs);
8053 if (resolvedRHS.isUsable()) rhs = resolvedRHS.release();
8054 }
8055 }
8056
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008057 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008058 case BO_Assign:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008059 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00008060 if (getLangOptions().CPlusPlus &&
8061 lhs->getObjectKind() != OK_ObjCProperty) {
John McCall4bc41ae2010-11-18 19:01:18 +00008062 VK = lhs->getValueKind();
8063 OK = lhs->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008064 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008065 if (!ResultTy.isNull())
8066 DiagnoseSelfAssignment(*this, lhs, rhs, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008067 break;
John McCalle3027922010-08-25 11:45:40 +00008068 case BO_PtrMemD:
8069 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00008070 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008071 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00008072 break;
John McCalle3027922010-08-25 11:45:40 +00008073 case BO_Mul:
8074 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00008075 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00008076 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008077 break;
John McCalle3027922010-08-25 11:45:40 +00008078 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008079 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
8080 break;
John McCalle3027922010-08-25 11:45:40 +00008081 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008082 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
8083 break;
John McCalle3027922010-08-25 11:45:40 +00008084 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008085 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
8086 break;
John McCalle3027922010-08-25 11:45:40 +00008087 case BO_Shl:
8088 case BO_Shr:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008089 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008090 break;
John McCalle3027922010-08-25 11:45:40 +00008091 case BO_LE:
8092 case BO_LT:
8093 case BO_GE:
8094 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008095 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008096 break;
John McCalle3027922010-08-25 11:45:40 +00008097 case BO_EQ:
8098 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008099 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008100 break;
John McCalle3027922010-08-25 11:45:40 +00008101 case BO_And:
8102 case BO_Xor:
8103 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008104 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
8105 break;
John McCalle3027922010-08-25 11:45:40 +00008106 case BO_LAnd:
8107 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00008108 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008109 break;
John McCalle3027922010-08-25 11:45:40 +00008110 case BO_MulAssign:
8111 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00008112 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00008113 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008114 CompLHSTy = CompResultTy;
8115 if (!CompResultTy.isNull())
8116 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008117 break;
John McCalle3027922010-08-25 11:45:40 +00008118 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008119 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
8120 CompLHSTy = CompResultTy;
8121 if (!CompResultTy.isNull())
8122 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008123 break;
John McCalle3027922010-08-25 11:45:40 +00008124 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008125 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
8126 if (!CompResultTy.isNull())
8127 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008128 break;
John McCalle3027922010-08-25 11:45:40 +00008129 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008130 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
8131 if (!CompResultTy.isNull())
8132 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008133 break;
John McCalle3027922010-08-25 11:45:40 +00008134 case BO_ShlAssign:
8135 case BO_ShrAssign:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008136 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008137 CompLHSTy = CompResultTy;
8138 if (!CompResultTy.isNull())
8139 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008140 break;
John McCalle3027922010-08-25 11:45:40 +00008141 case BO_AndAssign:
8142 case BO_XorAssign:
8143 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008144 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
8145 CompLHSTy = CompResultTy;
8146 if (!CompResultTy.isNull())
8147 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008148 break;
John McCalle3027922010-08-25 11:45:40 +00008149 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00008150 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John McCall7decc9e2010-11-18 06:31:45 +00008151 if (getLangOptions().CPlusPlus) {
8152 VK = rhs->getValueKind();
8153 OK = rhs->getObjectKind();
8154 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008155 break;
8156 }
8157 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00008158 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008159 if (CompResultTy.isNull())
John McCall7decc9e2010-11-18 06:31:45 +00008160 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy,
8161 VK, OK, OpLoc));
8162
John McCall34376a62010-12-04 03:47:34 +00008163 if (getLangOptions().CPlusPlus && lhs->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00008164 VK = VK_LValue;
8165 OK = lhs->getObjectKind();
8166 }
8167 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
8168 VK, OK, CompLHSTy,
8169 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008170}
8171
Sebastian Redl44615072009-10-27 12:10:02 +00008172/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
8173/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008174static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8175 const PartialDiagnostic &PD,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008176 const PartialDiagnostic &FirstNote,
8177 SourceRange FirstParenRange,
8178 const PartialDiagnostic &SecondNote,
Douglas Gregor89336232010-03-29 23:34:08 +00008179 SourceRange SecondParenRange) {
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008180 Self.Diag(Loc, PD);
8181
8182 if (!FirstNote.getDiagID())
8183 return;
8184
8185 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
8186 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8187 // We can't display the parentheses, so just return.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008188 return;
8189 }
8190
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008191 Self.Diag(Loc, FirstNote)
8192 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregora771f462010-03-31 17:46:05 +00008193 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008194
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008195 if (!SecondNote.getDiagID())
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008196 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008197
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008198 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
8199 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8200 // We can't display the parentheses, so just dig the
8201 // warning/error and return.
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008202 Self.Diag(Loc, SecondNote);
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008203 return;
8204 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008205
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008206 Self.Diag(Loc, SecondNote)
Douglas Gregora771f462010-03-31 17:46:05 +00008207 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
8208 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008209}
8210
Sebastian Redl44615072009-10-27 12:10:02 +00008211/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8212/// operators are mixed in a way that suggests that the programmer forgot that
8213/// comparison operators have higher precedence. The most typical example of
8214/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00008215static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00008216 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00008217 typedef BinaryOperator BinOp;
8218 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
8219 rhsopc = static_cast<BinOp::Opcode>(-1);
8220 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008221 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00008222 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008223 rhsopc = BO->getOpcode();
8224
8225 // Subs are not binary operators.
8226 if (lhsopc == -1 && rhsopc == -1)
8227 return;
8228
8229 // Bitwise operations are sometimes used as eager logical ops.
8230 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00008231 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
8232 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00008233 return;
8234
Sebastian Redl44615072009-10-27 12:10:02 +00008235 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008236 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008237 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008238 << SourceRange(lhs->getLocStart(), OpLoc)
8239 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00008240 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008241 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008242 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
8243 Self.PDiag(diag::note_precedence_bitwise_silence)
8244 << BinOp::getOpcodeStr(lhsopc),
8245 lhs->getSourceRange());
Sebastian Redl44615072009-10-27 12:10:02 +00008246 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008247 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008248 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008249 << SourceRange(OpLoc, rhs->getLocEnd())
8250 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00008251 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008252 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008253 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
8254 Self.PDiag(diag::note_precedence_bitwise_silence)
8255 << BinOp::getOpcodeStr(rhsopc),
8256 rhs->getSourceRange());
Sebastian Redl43028242009-10-26 15:24:15 +00008257}
8258
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008259/// \brief It accepts a '&&' expr that is inside a '||' one.
8260/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8261/// in parentheses.
8262static void
8263EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8264 Expr *E) {
8265 assert(isa<BinaryOperator>(E) &&
8266 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
8267 SuggestParentheses(Self, OpLoc,
8268 Self.PDiag(diag::warn_logical_and_in_logical_or)
8269 << E->getSourceRange(),
8270 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
8271 E->getSourceRange(),
8272 Self.PDiag(0), SourceRange());
8273}
8274
8275/// \brief Returns true if the given expression can be evaluated as a constant
8276/// 'true'.
8277static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8278 bool Res;
8279 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8280}
8281
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008282/// \brief Returns true if the given expression can be evaluated as a constant
8283/// 'false'.
8284static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8285 bool Res;
8286 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8287}
8288
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008289/// \brief Look for '&&' in the left hand of a '||' expr.
8290static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008291 Expr *OrLHS, Expr *OrRHS) {
8292 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008293 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008294 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8295 if (EvaluatesAsFalse(S, OrRHS))
8296 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008297 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8298 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8299 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8300 } else if (Bop->getOpcode() == BO_LOr) {
8301 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8302 // If it's "a || b && 1 || c" we didn't warn earlier for
8303 // "a || b && 1", but warn now.
8304 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8305 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8306 }
8307 }
8308 }
8309}
8310
8311/// \brief Look for '&&' in the right hand of a '||' expr.
8312static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008313 Expr *OrLHS, Expr *OrRHS) {
8314 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008315 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008316 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8317 if (EvaluatesAsFalse(S, OrLHS))
8318 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008319 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8320 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8321 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008322 }
8323 }
8324}
8325
Sebastian Redl43028242009-10-26 15:24:15 +00008326/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008327/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008328static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00008329 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008330 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008331 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008332 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
8333
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008334 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8335 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008336 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008337 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
8338 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008339 }
Sebastian Redl43028242009-10-26 15:24:15 +00008340}
8341
Steve Naroff218bc2b2007-05-04 21:54:46 +00008342// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008343ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008344 tok::TokenKind Kind,
8345 Expr *lhs, Expr *rhs) {
8346 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00008347 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8348 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008349
Sebastian Redl43028242009-10-26 15:24:15 +00008350 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8351 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8352
Douglas Gregor5287f092009-11-05 00:51:44 +00008353 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8354}
8355
John McCalldadc5752010-08-24 06:29:42 +00008356ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008357 BinaryOperatorKind Opc,
8358 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00008359 if (getLangOptions().CPlusPlus) {
8360 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008361
John McCall622114c2010-12-06 05:26:58 +00008362 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8363 UseBuiltinOperator = false;
8364 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8365 UseBuiltinOperator = true;
8366 } else {
8367 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8368 !rhs->getType()->isOverloadableType();
8369 }
8370
8371 if (!UseBuiltinOperator) {
8372 // Find all of the overloaded operators visible from this
8373 // point. We perform both an operator-name lookup from the local
8374 // scope and an argument-dependent lookup based on the types of
8375 // the arguments.
8376 UnresolvedSet<16> Functions;
8377 OverloadedOperatorKind OverOp
8378 = BinaryOperator::getOverloadedOperator(Opc);
8379 if (S && OverOp != OO_None)
8380 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8381 Functions);
8382
8383 // Build the (potentially-overloaded, potentially-dependent)
8384 // binary operation.
8385 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8386 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00008387 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008388
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008389 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00008390 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008391}
8392
John McCalldadc5752010-08-24 06:29:42 +00008393ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008394 UnaryOperatorKind Opc,
John McCall36226622010-10-12 02:09:17 +00008395 Expr *Input) {
John McCall7decc9e2010-11-18 06:31:45 +00008396 ExprValueKind VK = VK_RValue;
8397 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008398 QualType resultType;
8399 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008400 case UO_PreInc:
8401 case UO_PreDec:
8402 case UO_PostInc:
8403 case UO_PostDec:
John McCall4bc41ae2010-11-18 19:01:18 +00008404 resultType = CheckIncrementDecrementOperand(*this, Input, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008405 Opc == UO_PreInc ||
8406 Opc == UO_PostInc,
8407 Opc == UO_PreInc ||
8408 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008409 break;
John McCalle3027922010-08-25 11:45:40 +00008410 case UO_AddrOf:
John McCall4bc41ae2010-11-18 19:01:18 +00008411 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008412 break;
John McCalle3027922010-08-25 11:45:40 +00008413 case UO_Deref:
Douglas Gregor1beec452011-03-12 01:48:56 +00008414 if (Input->getType() == Context.OverloadTy ) {
8415 ExprResult er = ResolveAndFixSingleFunctionTemplateSpecialization(Input);
8416 if (er.isUsable())
8417 Input = er.release();
8418 }
Douglas Gregorb92a1562010-02-03 00:27:59 +00008419 DefaultFunctionArrayLvalueConversion(Input);
John McCall4bc41ae2010-11-18 19:01:18 +00008420 resultType = CheckIndirectionOperand(*this, Input, VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008421 break;
John McCalle3027922010-08-25 11:45:40 +00008422 case UO_Plus:
8423 case UO_Minus:
Steve Naroff31090012007-07-16 21:54:35 +00008424 UsualUnaryConversions(Input);
8425 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008426 if (resultType->isDependentType())
8427 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008428 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8429 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008430 break;
8431 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8432 resultType->isEnumeralType())
8433 break;
8434 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008435 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008436 resultType->isPointerType())
8437 break;
John McCall36226622010-10-12 02:09:17 +00008438 else if (resultType->isPlaceholderType()) {
8439 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8440 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008441 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00008442 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008443
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008444 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8445 << resultType << Input->getSourceRange());
John McCalle3027922010-08-25 11:45:40 +00008446 case UO_Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00008447 UsualUnaryConversions(Input);
8448 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008449 if (resultType->isDependentType())
8450 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008451 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8452 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8453 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008454 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008455 << resultType << Input->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008456 else if (resultType->hasIntegerRepresentation())
8457 break;
8458 else if (resultType->isPlaceholderType()) {
8459 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8460 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008461 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00008462 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008463 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8464 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008465 }
Steve Naroff35d85152007-05-07 00:24:15 +00008466 break;
John McCalle3027922010-08-25 11:45:40 +00008467 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008468 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregorb92a1562010-02-03 00:27:59 +00008469 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroff31090012007-07-16 21:54:35 +00008470 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008471 if (resultType->isDependentType())
8472 break;
John McCall36226622010-10-12 02:09:17 +00008473 if (resultType->isScalarType()) { // C99 6.5.3.3p1
8474 // ok, fallthrough
8475 } else if (resultType->isPlaceholderType()) {
8476 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8477 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008478 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00008479 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008480 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8481 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008482 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008483
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008484 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008485 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008486 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008487 break;
John McCalle3027922010-08-25 11:45:40 +00008488 case UO_Real:
8489 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008490 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00008491 // _Real and _Imag map ordinary l-values into ordinary l-values.
8492 if (Input->getValueKind() != VK_RValue &&
8493 Input->getObjectKind() == OK_Ordinary)
8494 VK = Input->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00008495 break;
John McCalle3027922010-08-25 11:45:40 +00008496 case UO_Extension:
Chris Lattner86554282007-06-08 22:32:33 +00008497 resultType = Input->getType();
John McCall7decc9e2010-11-18 06:31:45 +00008498 VK = Input->getValueKind();
8499 OK = Input->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008500 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008501 }
8502 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008503 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008504
John McCall7decc9e2010-11-18 06:31:45 +00008505 return Owned(new (Context) UnaryOperator(Input, Opc, resultType,
8506 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008507}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008508
John McCalldadc5752010-08-24 06:29:42 +00008509ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008510 UnaryOperatorKind Opc,
8511 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00008512 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00008513 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008514 // Find all of the overloaded operators visible from this
8515 // point. We perform both an operator-name lookup from the local
8516 // scope and an argument-dependent lookup based on the types of
8517 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008518 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008519 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008520 if (S && OverOp != OO_None)
8521 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8522 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008523
John McCallb268a282010-08-23 23:25:46 +00008524 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008525 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008526
John McCallb268a282010-08-23 23:25:46 +00008527 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008528}
8529
Douglas Gregor5287f092009-11-05 00:51:44 +00008530// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008531ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008532 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008533 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008534}
8535
Steve Naroff66356bd2007-09-16 14:56:35 +00008536/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008537ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008538 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008539 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008540 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008541 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008542 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008543}
8544
John McCalldadc5752010-08-24 06:29:42 +00008545ExprResult
John McCallb268a282010-08-23 23:25:46 +00008546Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008547 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008548 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8549 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8550
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008551 bool isFileScope
8552 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008553 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008554 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008555
Chris Lattner366727f2007-07-24 16:58:17 +00008556 // FIXME: there are a variety of strange constraints to enforce here, for
8557 // example, it is not possible to goto into a stmt expression apparently.
8558 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008559
Chris Lattner366727f2007-07-24 16:58:17 +00008560 // If there are sub stmts in the compound stmt, take the type of the last one
8561 // as the type of the stmtexpr.
8562 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008563 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008564 if (!Compound->body_empty()) {
8565 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008566 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008567 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008568 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8569 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008570 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008571 }
8572 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008573 // Do function/array conversion on the last expression, but not
8574 // lvalue-to-rvalue. However, initialize an unqualified type.
8575 DefaultFunctionArrayConversion(LastExpr);
8576 Ty = LastExpr->getType().getUnqualifiedType();
8577
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008578 if (!Ty->isDependentType() && !LastExpr->isTypeDependent()) {
8579 ExprResult Res = PerformCopyInitialization(
8580 InitializedEntity::InitializeResult(LPLoc,
8581 Ty,
8582 false),
8583 SourceLocation(),
8584 Owned(LastExpr));
8585 if (Res.isInvalid())
8586 return ExprError();
8587 if ((LastExpr = Res.takeAs<Expr>())) {
8588 if (!LastLabelStmt)
8589 Compound->setLastStmt(LastExpr);
8590 else
8591 LastLabelStmt->setSubStmt(LastExpr);
8592 StmtExprMayBindToTemp = true;
8593 }
8594 }
8595 }
Chris Lattner944d3062008-07-26 19:51:01 +00008596 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008597
Eli Friedmanba961a92009-03-23 00:24:07 +00008598 // FIXME: Check that expression type is complete/non-abstract; statement
8599 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008600 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8601 if (StmtExprMayBindToTemp)
8602 return MaybeBindToTemporary(ResStmtExpr);
8603 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008604}
Steve Naroff78864672007-08-01 22:05:33 +00008605
John McCalldadc5752010-08-24 06:29:42 +00008606ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008607 TypeSourceInfo *TInfo,
8608 OffsetOfComponent *CompPtr,
8609 unsigned NumComponents,
8610 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008611 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008612 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008613 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008614
Chris Lattnerf17bd422007-08-30 17:45:32 +00008615 // We must have at least one component that refers to the type, and the first
8616 // one is known to be a field designator. Verify that the ArgTy represents
8617 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008618 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008619 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8620 << ArgTy << TypeRange);
8621
8622 // Type must be complete per C99 7.17p3 because a declaring a variable
8623 // with an incomplete type would be ill-formed.
8624 if (!Dependent
8625 && RequireCompleteType(BuiltinLoc, ArgTy,
8626 PDiag(diag::err_offsetof_incomplete_type)
8627 << TypeRange))
8628 return ExprError();
8629
Chris Lattner78502cf2007-08-31 21:49:13 +00008630 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8631 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008632 // FIXME: This diagnostic isn't actually visible because the location is in
8633 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008634 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008635 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8636 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008637
8638 bool DidWarnAboutNonPOD = false;
8639 QualType CurrentType = ArgTy;
8640 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8641 llvm::SmallVector<OffsetOfNode, 4> Comps;
8642 llvm::SmallVector<Expr*, 4> Exprs;
8643 for (unsigned i = 0; i != NumComponents; ++i) {
8644 const OffsetOfComponent &OC = CompPtr[i];
8645 if (OC.isBrackets) {
8646 // Offset of an array sub-field. TODO: Should we allow vector elements?
8647 if (!CurrentType->isDependentType()) {
8648 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8649 if(!AT)
8650 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8651 << CurrentType);
8652 CurrentType = AT->getElementType();
8653 } else
8654 CurrentType = Context.DependentTy;
8655
8656 // The expression must be an integral expression.
8657 // FIXME: An integral constant expression?
8658 Expr *Idx = static_cast<Expr*>(OC.U.E);
8659 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8660 !Idx->getType()->isIntegerType())
8661 return ExprError(Diag(Idx->getLocStart(),
8662 diag::err_typecheck_subscript_not_integer)
8663 << Idx->getSourceRange());
8664
8665 // Record this array index.
8666 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8667 Exprs.push_back(Idx);
8668 continue;
8669 }
8670
8671 // Offset of a field.
8672 if (CurrentType->isDependentType()) {
8673 // We have the offset of a field, but we can't look into the dependent
8674 // type. Just record the identifier of the field.
8675 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8676 CurrentType = Context.DependentTy;
8677 continue;
8678 }
8679
8680 // We need to have a complete type to look into.
8681 if (RequireCompleteType(OC.LocStart, CurrentType,
8682 diag::err_offsetof_incomplete_type))
8683 return ExprError();
8684
8685 // Look for the designated field.
8686 const RecordType *RC = CurrentType->getAs<RecordType>();
8687 if (!RC)
8688 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8689 << CurrentType);
8690 RecordDecl *RD = RC->getDecl();
8691
8692 // C++ [lib.support.types]p5:
8693 // The macro offsetof accepts a restricted set of type arguments in this
8694 // International Standard. type shall be a POD structure or a POD union
8695 // (clause 9).
8696 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8697 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008698 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008699 PDiag(diag::warn_offsetof_non_pod_type)
8700 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8701 << CurrentType))
8702 DidWarnAboutNonPOD = true;
8703 }
8704
8705 // Look for the field.
8706 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8707 LookupQualifiedName(R, RD);
8708 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008709 IndirectFieldDecl *IndirectMemberDecl = 0;
8710 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008711 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008712 MemberDecl = IndirectMemberDecl->getAnonField();
8713 }
8714
Douglas Gregor882211c2010-04-28 22:16:22 +00008715 if (!MemberDecl)
8716 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8717 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8718 OC.LocEnd));
8719
Douglas Gregor10982ea2010-04-28 22:36:06 +00008720 // C99 7.17p3:
8721 // (If the specified member is a bit-field, the behavior is undefined.)
8722 //
8723 // We diagnose this as an error.
8724 if (MemberDecl->getBitWidth()) {
8725 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8726 << MemberDecl->getDeclName()
8727 << SourceRange(BuiltinLoc, RParenLoc);
8728 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8729 return ExprError();
8730 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008731
8732 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008733 if (IndirectMemberDecl)
8734 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008735
Douglas Gregord1702062010-04-29 00:18:15 +00008736 // If the member was found in a base class, introduce OffsetOfNodes for
8737 // the base class indirections.
8738 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8739 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008740 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008741 CXXBasePath &Path = Paths.front();
8742 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8743 B != BEnd; ++B)
8744 Comps.push_back(OffsetOfNode(B->Base));
8745 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008746
Francois Pichet783dd6e2010-11-21 06:08:52 +00008747 if (IndirectMemberDecl) {
8748 for (IndirectFieldDecl::chain_iterator FI =
8749 IndirectMemberDecl->chain_begin(),
8750 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8751 assert(isa<FieldDecl>(*FI));
8752 Comps.push_back(OffsetOfNode(OC.LocStart,
8753 cast<FieldDecl>(*FI), OC.LocEnd));
8754 }
8755 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008756 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008757
Douglas Gregor882211c2010-04-28 22:16:22 +00008758 CurrentType = MemberDecl->getType().getNonReferenceType();
8759 }
8760
8761 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8762 TInfo, Comps.data(), Comps.size(),
8763 Exprs.data(), Exprs.size(), RParenLoc));
8764}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008765
John McCalldadc5752010-08-24 06:29:42 +00008766ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008767 SourceLocation BuiltinLoc,
8768 SourceLocation TypeLoc,
8769 ParsedType argty,
8770 OffsetOfComponent *CompPtr,
8771 unsigned NumComponents,
8772 SourceLocation RPLoc) {
8773
Douglas Gregor882211c2010-04-28 22:16:22 +00008774 TypeSourceInfo *ArgTInfo;
8775 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8776 if (ArgTy.isNull())
8777 return ExprError();
8778
Eli Friedman06dcfd92010-08-05 10:15:45 +00008779 if (!ArgTInfo)
8780 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8781
8782 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8783 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008784}
8785
8786
John McCalldadc5752010-08-24 06:29:42 +00008787ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008788 Expr *CondExpr,
8789 Expr *LHSExpr, Expr *RHSExpr,
8790 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008791 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8792
John McCall7decc9e2010-11-18 06:31:45 +00008793 ExprValueKind VK = VK_RValue;
8794 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008795 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008796 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008797 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008798 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008799 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008800 } else {
8801 // The conditional expression is required to be a constant expression.
8802 llvm::APSInt condEval(32);
8803 SourceLocation ExpLoc;
8804 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008805 return ExprError(Diag(ExpLoc,
8806 diag::err_typecheck_choose_expr_requires_constant)
8807 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008808
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008809 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008810 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8811
8812 resType = ActiveExpr->getType();
8813 ValueDependent = ActiveExpr->isValueDependent();
8814 VK = ActiveExpr->getValueKind();
8815 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008816 }
8817
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008818 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008819 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008820 resType->isDependentType(),
8821 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008822}
8823
Steve Naroffc540d662008-09-03 18:15:37 +00008824//===----------------------------------------------------------------------===//
8825// Clang Extensions.
8826//===----------------------------------------------------------------------===//
8827
8828/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008829void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008830 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8831 PushBlockScope(BlockScope, Block);
8832 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008833 if (BlockScope)
8834 PushDeclContext(BlockScope, Block);
8835 else
8836 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008837}
8838
Mike Stump82f071f2009-02-04 22:31:32 +00008839void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008840 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008841 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008842 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008843
John McCall8cb7bdf2010-06-04 23:28:52 +00008844 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008845 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008846
John McCall3882ace2011-01-05 12:14:39 +00008847 // GetTypeForDeclarator always produces a function type for a block
8848 // literal signature. Furthermore, it is always a FunctionProtoType
8849 // unless the function was written with a typedef.
8850 assert(T->isFunctionType() &&
8851 "GetTypeForDeclarator made a non-function block signature");
8852
8853 // Look for an explicit signature in that function type.
8854 FunctionProtoTypeLoc ExplicitSignature;
8855
8856 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8857 if (isa<FunctionProtoTypeLoc>(tmp)) {
8858 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8859
8860 // Check whether that explicit signature was synthesized by
8861 // GetTypeForDeclarator. If so, don't save that as part of the
8862 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008863 if (ExplicitSignature.getLocalRangeBegin() ==
8864 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008865 // This would be much cheaper if we stored TypeLocs instead of
8866 // TypeSourceInfos.
8867 TypeLoc Result = ExplicitSignature.getResultLoc();
8868 unsigned Size = Result.getFullDataSize();
8869 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8870 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8871
8872 ExplicitSignature = FunctionProtoTypeLoc();
8873 }
John McCalla3ccba02010-06-04 11:21:44 +00008874 }
Mike Stump11289f42009-09-09 15:08:12 +00008875
John McCall3882ace2011-01-05 12:14:39 +00008876 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8877 CurBlock->FunctionType = T;
8878
8879 const FunctionType *Fn = T->getAs<FunctionType>();
8880 QualType RetTy = Fn->getResultType();
8881 bool isVariadic =
8882 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8883
John McCall8e346702010-06-04 19:02:56 +00008884 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008885
John McCalla3ccba02010-06-04 11:21:44 +00008886 // Don't allow returning a objc interface by value.
8887 if (RetTy->isObjCObjectType()) {
8888 Diag(ParamInfo.getSourceRange().getBegin(),
8889 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8890 return;
8891 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008892
John McCalla3ccba02010-06-04 11:21:44 +00008893 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008894 // return type. TODO: what should we do with declarators like:
8895 // ^ * { ... }
8896 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008897 if (RetTy != Context.DependentTy)
8898 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008899
John McCalla3ccba02010-06-04 11:21:44 +00008900 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00008901 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008902 if (ExplicitSignature) {
8903 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8904 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008905 if (Param->getIdentifier() == 0 &&
8906 !Param->isImplicit() &&
8907 !Param->isInvalidDecl() &&
8908 !getLangOptions().CPlusPlus)
8909 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008910 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008911 }
John McCalla3ccba02010-06-04 11:21:44 +00008912
8913 // Fake up parameter variables if we have a typedef, like
8914 // ^ fntype { ... }
8915 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8916 for (FunctionProtoType::arg_type_iterator
8917 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8918 ParmVarDecl *Param =
8919 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8920 ParamInfo.getSourceRange().getBegin(),
8921 *I);
John McCall8e346702010-06-04 19:02:56 +00008922 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008923 }
Steve Naroffc540d662008-09-03 18:15:37 +00008924 }
John McCalla3ccba02010-06-04 11:21:44 +00008925
John McCall8e346702010-06-04 19:02:56 +00008926 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008927 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00008928 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00008929 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8930 CurBlock->TheDecl->param_end(),
8931 /*CheckParameterNames=*/false);
8932 }
8933
John McCalla3ccba02010-06-04 11:21:44 +00008934 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008935 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008936
John McCall8e346702010-06-04 19:02:56 +00008937 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008938 Diag(ParamInfo.getAttributes()->getLoc(),
8939 diag::warn_attribute_sentinel_not_variadic) << 1;
8940 // FIXME: remove the attribute.
8941 }
8942
8943 // Put the parameter variables in scope. We can bail out immediately
8944 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008945 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008946 return;
8947
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008948 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008949 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8950 (*AI)->setOwningFunction(CurBlock->TheDecl);
8951
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008952 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008953 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008954 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008955
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008956 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008957 }
John McCallf7b2fb52010-01-22 00:28:27 +00008958 }
Steve Naroffc540d662008-09-03 18:15:37 +00008959}
8960
8961/// ActOnBlockError - If there is an error parsing a block, this callback
8962/// is invoked to pop the information about the block from the action impl.
8963void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008964 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008965 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008966 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008967}
8968
8969/// ActOnBlockStmtExpr - This is called when the body of a block statement
8970/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008971ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008972 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008973 // If blocks are disabled, emit an error.
8974 if (!LangOpts.Blocks)
8975 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008976
Douglas Gregor9a28e842010-03-01 23:15:13 +00008977 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008978
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008979 PopDeclContext();
8980
Steve Naroffc540d662008-09-03 18:15:37 +00008981 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008982 if (!BSI->ReturnType.isNull())
8983 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008984
Mike Stump3bf1ab42009-07-28 22:04:01 +00008985 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008986 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008987
John McCallc63de662011-02-02 13:00:07 +00008988 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00008989 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8990 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00008991
John McCall8e346702010-06-04 19:02:56 +00008992 // If the user wrote a function type in some form, try to use that.
8993 if (!BSI->FunctionType.isNull()) {
8994 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8995
8996 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8997 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8998
8999 // Turn protoless block types into nullary block types.
9000 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009001 FunctionProtoType::ExtProtoInfo EPI;
9002 EPI.ExtInfo = Ext;
9003 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009004
9005 // Otherwise, if we don't need to change anything about the function type,
9006 // preserve its sugar structure.
9007 } else if (FTy->getResultType() == RetTy &&
9008 (!NoReturn || FTy->getNoReturnAttr())) {
9009 BlockTy = BSI->FunctionType;
9010
9011 // Otherwise, make the minimal modifications to the function type.
9012 } else {
9013 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00009014 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9015 EPI.TypeQuals = 0; // FIXME: silently?
9016 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00009017 BlockTy = Context.getFunctionType(RetTy,
9018 FPT->arg_type_begin(),
9019 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00009020 EPI);
John McCall8e346702010-06-04 19:02:56 +00009021 }
9022
9023 // If we don't have a function type, just build one from nothing.
9024 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00009025 FunctionProtoType::ExtProtoInfo EPI;
9026 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, 0, CC_Default);
9027 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009028 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009029
John McCall8e346702010-06-04 19:02:56 +00009030 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9031 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00009032 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009033
Chris Lattner45542ea2009-04-19 05:28:12 +00009034 // If needed, diagnose invalid gotos and switches in the block.
John McCallaab3e412010-08-25 08:40:02 +00009035 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00009036 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00009037
Chris Lattner60f84492011-02-17 23:58:47 +00009038 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009039
John McCallc63de662011-02-02 13:00:07 +00009040 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCall1d570a72010-08-25 05:56:39 +00009041
Ted Kremenek1767a272011-02-23 01:51:48 +00009042 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9043 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009044 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00009045}
9046
John McCalldadc5752010-08-24 06:29:42 +00009047ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00009048 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009049 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00009050 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009051 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00009052 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00009053}
9054
John McCalldadc5752010-08-24 06:29:42 +00009055ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00009056 Expr *E, TypeSourceInfo *TInfo,
9057 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00009058 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00009059
Eli Friedman121ba0c2008-08-09 23:32:40 +00009060 // Get the va_list type
9061 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00009062 if (VaListType->isArrayType()) {
9063 // Deal with implicit array decay; for example, on x86-64,
9064 // va_list is an array, but it's supposed to decay to
9065 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00009066 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00009067 // Make sure the input expression also decays appropriately.
9068 UsualUnaryConversions(E);
9069 } else {
9070 // Otherwise, the va_list argument must be an l-value because
9071 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00009072 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00009073 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00009074 return ExprError();
9075 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00009076
Douglas Gregorad3150c2009-05-19 23:10:31 +00009077 if (!E->isTypeDependent() &&
9078 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009079 return ExprError(Diag(E->getLocStart(),
9080 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00009081 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00009082 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009083
Eli Friedmanba961a92009-03-23 00:24:07 +00009084 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009085 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00009086
Abramo Bagnara27db2392010-08-10 10:06:15 +00009087 QualType T = TInfo->getType().getNonLValueExprType(Context);
9088 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009089}
9090
John McCalldadc5752010-08-24 06:29:42 +00009091ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009092 // The type of __null will be int or long, depending on the size of
9093 // pointers on the target.
9094 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009095 unsigned pw = Context.Target.getPointerWidth(0);
9096 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009097 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009098 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009099 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009100 else if (pw == Context.Target.getLongLongWidth())
9101 Ty = Context.LongLongTy;
9102 else {
9103 assert(!"I don't know size of pointer!");
9104 Ty = Context.IntTy;
9105 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009106
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009107 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009108}
9109
Alexis Huntc46382e2010-04-28 23:02:27 +00009110static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009111 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00009112 if (!SemaRef.getLangOptions().ObjC1)
9113 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009114
Anders Carlssonace5d072009-11-10 04:46:30 +00009115 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9116 if (!PT)
9117 return;
9118
9119 // Check if the destination is of type 'id'.
9120 if (!PT->isObjCIdType()) {
9121 // Check if the destination is the 'NSString' interface.
9122 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9123 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9124 return;
9125 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009126
Anders Carlssonace5d072009-11-10 04:46:30 +00009127 // Strip off any parens and casts.
9128 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
9129 if (!SL || SL->isWide())
9130 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009131
Douglas Gregora771f462010-03-31 17:46:05 +00009132 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009133}
9134
Chris Lattner9bad62c2008-01-04 18:04:52 +00009135bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9136 SourceLocation Loc,
9137 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009138 Expr *SrcExpr, AssignmentAction Action,
9139 bool *Complained) {
9140 if (Complained)
9141 *Complained = false;
9142
Chris Lattner9bad62c2008-01-04 18:04:52 +00009143 // Decode the result (notice that AST's are still created for extensions).
9144 bool isInvalid = false;
9145 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00009146 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009147
Chris Lattner9bad62c2008-01-04 18:04:52 +00009148 switch (ConvTy) {
9149 default: assert(0 && "Unknown conversion type");
9150 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009151 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009152 DiagKind = diag::ext_typecheck_convert_pointer_int;
9153 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009154 case IntToPointer:
9155 DiagKind = diag::ext_typecheck_convert_int_pointer;
9156 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009157 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009158 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009159 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9160 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009161 case IncompatiblePointerSign:
9162 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9163 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009164 case FunctionVoidPointer:
9165 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9166 break;
John McCall4fff8f62011-02-01 00:10:29 +00009167 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009168 // Perform array-to-pointer decay if necessary.
9169 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9170
John McCall4fff8f62011-02-01 00:10:29 +00009171 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9172 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9173 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9174 DiagKind = diag::err_typecheck_incompatible_address_space;
9175 break;
9176 }
9177
9178 llvm_unreachable("unknown error case for discarding qualifiers!");
9179 // fallthrough
9180 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009181 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009182 // If the qualifiers lost were because we were applying the
9183 // (deprecated) C++ conversion from a string literal to a char*
9184 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9185 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009186 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009187 // bit of refactoring (so that the second argument is an
9188 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009189 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009190 // C++ semantics.
9191 if (getLangOptions().CPlusPlus &&
9192 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9193 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009194 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9195 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009196 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009197 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009198 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009199 case IntToBlockPointer:
9200 DiagKind = diag::err_int_to_block_pointer;
9201 break;
9202 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009203 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009204 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009205 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009206 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009207 // it can give a more specific diagnostic.
9208 DiagKind = diag::warn_incompatible_qualified_id;
9209 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009210 case IncompatibleVectors:
9211 DiagKind = diag::warn_incompatible_vectors;
9212 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009213 case Incompatible:
9214 DiagKind = diag::err_typecheck_convert_incompatible;
9215 isInvalid = true;
9216 break;
9217 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009218
Douglas Gregorc68e1402010-04-09 00:35:39 +00009219 QualType FirstType, SecondType;
9220 switch (Action) {
9221 case AA_Assigning:
9222 case AA_Initializing:
9223 // The destination type comes first.
9224 FirstType = DstType;
9225 SecondType = SrcType;
9226 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009227
Douglas Gregorc68e1402010-04-09 00:35:39 +00009228 case AA_Returning:
9229 case AA_Passing:
9230 case AA_Converting:
9231 case AA_Sending:
9232 case AA_Casting:
9233 // The source type comes first.
9234 FirstType = SrcType;
9235 SecondType = DstType;
9236 break;
9237 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009238
Douglas Gregorc68e1402010-04-09 00:35:39 +00009239 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00009240 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009241 if (Complained)
9242 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009243 return isInvalid;
9244}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009245
Chris Lattnerc71d08b2009-04-25 21:59:05 +00009246bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009247 llvm::APSInt ICEResult;
9248 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9249 if (Result)
9250 *Result = ICEResult;
9251 return false;
9252 }
9253
Anders Carlssone54e8a12008-11-30 19:50:32 +00009254 Expr::EvalResult EvalResult;
9255
Mike Stump4e1f26a2009-02-19 03:04:26 +00009256 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00009257 EvalResult.HasSideEffects) {
9258 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9259
9260 if (EvalResult.Diag) {
9261 // We only show the note if it's not the usual "invalid subexpression"
9262 // or if it's actually in a subexpression.
9263 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9264 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9265 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9266 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009267
Anders Carlssone54e8a12008-11-30 19:50:32 +00009268 return true;
9269 }
9270
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009271 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9272 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009273
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009274 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009275 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9276 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009277 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009278
Anders Carlssone54e8a12008-11-30 19:50:32 +00009279 if (Result)
9280 *Result = EvalResult.Val.getInt();
9281 return false;
9282}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009283
Douglas Gregorff790f12009-11-26 00:44:06 +00009284void
Mike Stump11289f42009-09-09 15:08:12 +00009285Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009286 ExprEvalContexts.push_back(
9287 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009288}
9289
Mike Stump11289f42009-09-09 15:08:12 +00009290void
Douglas Gregorff790f12009-11-26 00:44:06 +00009291Sema::PopExpressionEvaluationContext() {
9292 // Pop the current expression evaluation context off the stack.
9293 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9294 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009295
Douglas Gregorfab31f42009-12-12 07:57:52 +00009296 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9297 if (Rec.PotentiallyReferenced) {
9298 // Mark any remaining declarations in the current position of the stack
9299 // as "referenced". If they were not meant to be referenced, semantic
9300 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009301 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00009302 I = Rec.PotentiallyReferenced->begin(),
9303 IEnd = Rec.PotentiallyReferenced->end();
9304 I != IEnd; ++I)
9305 MarkDeclarationReferenced(I->first, I->second);
9306 }
9307
9308 if (Rec.PotentiallyDiagnosed) {
9309 // Emit any pending diagnostics.
9310 for (PotentiallyEmittedDiagnostics::iterator
9311 I = Rec.PotentiallyDiagnosed->begin(),
9312 IEnd = Rec.PotentiallyDiagnosed->end();
9313 I != IEnd; ++I)
9314 Diag(I->first, I->second);
9315 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009316 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009317
9318 // When are coming out of an unevaluated context, clear out any
9319 // temporaries that we may have created as part of the evaluation of
9320 // the expression in that context: they aren't relevant because they
9321 // will never be constructed.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009322 if (Rec.Context == Unevaluated &&
Douglas Gregorff790f12009-11-26 00:44:06 +00009323 ExprTemporaries.size() > Rec.NumTemporaries)
9324 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9325 ExprTemporaries.end());
9326
9327 // Destroy the popped expression evaluation record.
9328 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009329}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009330
9331/// \brief Note that the given declaration was referenced in the source code.
9332///
9333/// This routine should be invoke whenever a given declaration is referenced
9334/// in the source code, and where that reference occurred. If this declaration
9335/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9336/// C99 6.9p3), then the declaration will be marked as used.
9337///
9338/// \param Loc the location where the declaration was referenced.
9339///
9340/// \param D the declaration that has been referenced by the source code.
9341void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9342 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009343
Douglas Gregorebada0772010-06-17 23:14:26 +00009344 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009345 return;
Mike Stump11289f42009-09-09 15:08:12 +00009346
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00009347 // Mark a parameter or variable declaration "used", regardless of whether we're in a
9348 // template or not. The reason for this is that unevaluated expressions
9349 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9350 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009351 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009352 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009353 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009354 return;
9355 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009356
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009357 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9358 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009359
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009360 // Do not mark anything as "used" within a dependent context; wait for
9361 // an instantiation.
9362 if (CurContext->isDependentContext())
9363 return;
Mike Stump11289f42009-09-09 15:08:12 +00009364
Douglas Gregorff790f12009-11-26 00:44:06 +00009365 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009366 case Unevaluated:
9367 // We are in an expression that is not potentially evaluated; do nothing.
9368 return;
Mike Stump11289f42009-09-09 15:08:12 +00009369
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009370 case PotentiallyEvaluated:
9371 // We are in a potentially-evaluated expression, so this declaration is
9372 // "used"; handle this below.
9373 break;
Mike Stump11289f42009-09-09 15:08:12 +00009374
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009375 case PotentiallyPotentiallyEvaluated:
9376 // We are in an expression that may be potentially evaluated; queue this
9377 // declaration reference until we know whether the expression is
9378 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009379 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009380 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009381
9382 case PotentiallyEvaluatedIfUsed:
9383 // Referenced declarations will only be used if the construct in the
9384 // containing expression is used.
9385 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009386 }
Mike Stump11289f42009-09-09 15:08:12 +00009387
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009388 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009389 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009390 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00009391 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruthc9262402010-08-23 07:55:51 +00009392 if (Constructor->getParent()->hasTrivialConstructor())
9393 return;
9394 if (!Constructor->isUsed(false))
9395 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00009396 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00009397 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009398 if (!Constructor->isUsed(false))
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009399 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
9400 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009401
Douglas Gregor88d292c2010-05-13 16:44:06 +00009402 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009403 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009404 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009405 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009406 if (Destructor->isVirtual())
9407 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009408 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9409 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
9410 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009411 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00009412 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009413 } else if (MethodDecl->isVirtual())
9414 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009415 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009416 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009417 // Recursive functions should be marked when used from another function.
9418 if (CurContext == Function) return;
9419
Mike Stump11289f42009-09-09 15:08:12 +00009420 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009421 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009422 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009423 bool AlreadyInstantiated = false;
9424 if (FunctionTemplateSpecializationInfo *SpecInfo
9425 = Function->getTemplateSpecializationInfo()) {
9426 if (SpecInfo->getPointOfInstantiation().isInvalid())
9427 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009428 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009429 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009430 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009431 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009432 = Function->getMemberSpecializationInfo()) {
9433 if (MSInfo->getPointOfInstantiation().isInvalid())
9434 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009435 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009436 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009437 AlreadyInstantiated = true;
9438 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009439
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009440 if (!AlreadyInstantiated) {
9441 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9442 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9443 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9444 Loc));
9445 else
Chandler Carruth54080172010-08-25 08:44:16 +00009446 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009447 }
John McCall83779672011-02-19 02:53:41 +00009448 } else {
9449 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009450 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9451 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009452 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009453 MarkDeclarationReferenced(Loc, *i);
9454 }
John McCall83779672011-02-19 02:53:41 +00009455 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009456
John McCall83779672011-02-19 02:53:41 +00009457 // Keep track of used but undefined functions.
9458 if (!Function->isPure() && !Function->hasBody() &&
9459 Function->getLinkage() != ExternalLinkage) {
9460 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9461 if (old.isInvalid()) old = Loc;
9462 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009463
John McCall83779672011-02-19 02:53:41 +00009464 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009465 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009466 }
Mike Stump11289f42009-09-09 15:08:12 +00009467
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009468 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009469 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009470 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009471 Var->getInstantiatedFromStaticDataMember()) {
9472 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9473 assert(MSInfo && "Missing member specialization information?");
9474 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9475 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9476 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth54080172010-08-25 08:44:16 +00009477 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009478 }
9479 }
Mike Stump11289f42009-09-09 15:08:12 +00009480
John McCall15dd4042011-02-21 19:25:48 +00009481 // Keep track of used but undefined variables. We make a hole in
9482 // the warning for static const data members with in-line
9483 // initializers.
John McCall83779672011-02-19 02:53:41 +00009484 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009485 && Var->getLinkage() != ExternalLinkage
9486 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009487 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9488 if (old.isInvalid()) old = Loc;
9489 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009490
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009491 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009492 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009493 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009494}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009495
Douglas Gregor5597ab42010-05-07 23:12:07 +00009496namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009497 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009498 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009499 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009500 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9501 Sema &S;
9502 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009503
Douglas Gregor5597ab42010-05-07 23:12:07 +00009504 public:
9505 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009506
Douglas Gregor5597ab42010-05-07 23:12:07 +00009507 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009508
9509 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9510 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009511 };
9512}
9513
Chandler Carruthaf80f662010-06-09 08:17:30 +00009514bool MarkReferencedDecls::TraverseTemplateArgument(
9515 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009516 if (Arg.getKind() == TemplateArgument::Declaration) {
9517 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9518 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009519
9520 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009521}
9522
Chandler Carruthaf80f662010-06-09 08:17:30 +00009523bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009524 if (ClassTemplateSpecializationDecl *Spec
9525 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9526 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009527 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009528 }
9529
Chandler Carruthc65667c2010-06-10 10:31:57 +00009530 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009531}
9532
9533void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9534 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009535 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009536}
9537
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009538namespace {
9539 /// \brief Helper class that marks all of the declarations referenced by
9540 /// potentially-evaluated subexpressions as "referenced".
9541 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9542 Sema &S;
9543
9544 public:
9545 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9546
9547 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9548
9549 void VisitDeclRefExpr(DeclRefExpr *E) {
9550 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9551 }
9552
9553 void VisitMemberExpr(MemberExpr *E) {
9554 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009555 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009556 }
9557
9558 void VisitCXXNewExpr(CXXNewExpr *E) {
9559 if (E->getConstructor())
9560 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9561 if (E->getOperatorNew())
9562 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9563 if (E->getOperatorDelete())
9564 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009565 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009566 }
9567
9568 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9569 if (E->getOperatorDelete())
9570 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009571 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9572 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9573 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9574 S.MarkDeclarationReferenced(E->getLocStart(),
9575 S.LookupDestructor(Record));
9576 }
9577
Douglas Gregor32b3de52010-09-11 23:32:50 +00009578 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009579 }
9580
9581 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9582 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009583 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009584 }
9585
9586 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9587 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9588 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009589
9590 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9591 Visit(E->getExpr());
9592 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009593 };
9594}
9595
9596/// \brief Mark any declarations that appear within this expression or any
9597/// potentially-evaluated subexpressions as "referenced".
9598void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9599 EvaluatedExprMarker(*this).Visit(E);
9600}
9601
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009602/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9603/// of the program being compiled.
9604///
9605/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009606/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009607/// possibility that the code will actually be executable. Code in sizeof()
9608/// expressions, code used only during overload resolution, etc., are not
9609/// potentially evaluated. This routine will suppress such diagnostics or,
9610/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009611/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009612/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009613///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009614/// This routine should be used for all diagnostics that describe the run-time
9615/// behavior of a program, such as passing a non-POD value through an ellipsis.
9616/// Failure to do so will likely result in spurious diagnostics or failures
9617/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek55ae3192011-02-23 01:51:43 +00009618bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009619 const PartialDiagnostic &PD) {
9620 switch (ExprEvalContexts.back().Context ) {
9621 case Unevaluated:
9622 // The argument will never be evaluated, so don't complain.
9623 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009624
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009625 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009626 case PotentiallyEvaluatedIfUsed:
Ted Kremenek3427fac2011-02-23 01:52:04 +00009627 if (stmt && getCurFunctionOrMethodDecl()) {
9628 FunctionScopes.back()->PossiblyUnreachableDiags.
9629 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9630 }
9631 else
9632 Diag(Loc, PD);
9633
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009634 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009635
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009636 case PotentiallyPotentiallyEvaluated:
9637 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9638 break;
9639 }
9640
9641 return false;
9642}
9643
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009644bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9645 CallExpr *CE, FunctionDecl *FD) {
9646 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9647 return false;
9648
9649 PartialDiagnostic Note =
9650 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9651 << FD->getDeclName() : PDiag();
9652 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009653
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009654 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009655 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009656 PDiag(diag::err_call_function_incomplete_return)
9657 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009658 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009659 << CE->getSourceRange(),
9660 std::make_pair(NoteLoc, Note)))
9661 return true;
9662
9663 return false;
9664}
9665
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009666// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009667// will prevent this condition from triggering, which is what we want.
9668void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9669 SourceLocation Loc;
9670
John McCall0506e4a2009-11-11 02:41:58 +00009671 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009672 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009673
John McCalld5707ab2009-10-12 21:59:07 +00009674 if (isa<BinaryOperator>(E)) {
9675 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009676 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009677 return;
9678
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009679 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9680
John McCallb0e419e2009-11-12 00:06:05 +00009681 // Greylist some idioms by putting them into a warning subcategory.
9682 if (ObjCMessageExpr *ME
9683 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9684 Selector Sel = ME->getSelector();
9685
John McCallb0e419e2009-11-12 00:06:05 +00009686 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009687 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +00009688 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9689
9690 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009691 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +00009692 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9693 }
John McCall0506e4a2009-11-11 02:41:58 +00009694
John McCalld5707ab2009-10-12 21:59:07 +00009695 Loc = Op->getOperatorLoc();
9696 } else if (isa<CXXOperatorCallExpr>(E)) {
9697 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009698 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009699 return;
9700
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009701 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009702 Loc = Op->getOperatorLoc();
9703 } else {
9704 // Not an assignment.
9705 return;
9706 }
9707
John McCalld5707ab2009-10-12 21:59:07 +00009708 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00009709 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009710
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009711 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009712
9713 if (IsOrAssign)
9714 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9715 << FixItHint::CreateReplacement(Loc, "!=");
9716 else
9717 Diag(Loc, diag::note_condition_assign_to_comparison)
9718 << FixItHint::CreateReplacement(Loc, "==");
9719
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009720 Diag(Loc, diag::note_condition_assign_silence)
9721 << FixItHint::CreateInsertion(Open, "(")
9722 << FixItHint::CreateInsertion(Close, ")");
John McCalld5707ab2009-10-12 21:59:07 +00009723}
9724
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009725/// \brief Redundant parentheses over an equality comparison can indicate
9726/// that the user intended an assignment used as condition.
9727void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009728 // Don't warn if the parens came from a macro.
9729 SourceLocation parenLoc = parenE->getLocStart();
9730 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9731 return;
9732
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009733 Expr *E = parenE->IgnoreParens();
9734
9735 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009736 if (opE->getOpcode() == BO_EQ &&
9737 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9738 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009739 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009740
Ted Kremenekae022092011-02-02 02:20:30 +00009741 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
9742 Diag(Loc, diag::note_equality_comparison_to_assign)
9743 << FixItHint::CreateReplacement(Loc, "=");
9744 Diag(Loc, diag::note_equality_comparison_silence)
9745 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9746 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009747 }
9748}
9749
John McCalld5707ab2009-10-12 21:59:07 +00009750bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
9751 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009752 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9753 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009754
9755 if (!E->isTypeDependent()) {
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009756 if (E->isBoundMemberFunction(Context))
9757 return Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9758 << E->getSourceRange();
9759
John McCall34376a62010-12-04 03:47:34 +00009760 if (getLangOptions().CPlusPlus)
9761 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9762
9763 DefaultFunctionArrayLvalueConversion(E);
John McCall29cb2fd2010-12-04 06:09:13 +00009764
9765 QualType T = E->getType();
John McCall34376a62010-12-04 03:47:34 +00009766 if (!T->isScalarType()) // C99 6.8.4.1p1
9767 return Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9768 << T << E->getSourceRange();
John McCalld5707ab2009-10-12 21:59:07 +00009769 }
9770
9771 return false;
9772}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009773
John McCalldadc5752010-08-24 06:29:42 +00009774ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9775 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00009776 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009777 return ExprError();
9778
Douglas Gregorb412e172010-07-25 18:17:45 +00009779 if (CheckBooleanCondition(Sub, Loc))
Douglas Gregore60e41a2010-05-06 17:25:47 +00009780 return ExprError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00009781
9782 return Owned(Sub);
9783}
John McCall36e7fe32010-10-12 00:20:44 +00009784
9785/// Check for operands with placeholder types and complain if found.
9786/// Returns true if there was an error and no recovery was possible.
9787ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) {
9788 const BuiltinType *BT = E->getType()->getAs<BuiltinType>();
9789 if (!BT || !BT->isPlaceholderType()) return Owned(E);
9790
9791 // If this is overload, check for a single overload.
Richard Smith30482bc2011-02-20 03:19:35 +00009792 assert(BT->getKind() == BuiltinType::Overload);
Douglas Gregor89f3cd52011-03-16 19:16:25 +00009793 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
9794 E->getSourceRange(),
9795 QualType(),
9796 diag::err_ovl_unresolvable);
John McCall36e7fe32010-10-12 00:20:44 +00009797}