blob: b8f0c729d1788ba0652738d8c709b2f5f56281e8 [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
John McCall92d627e2011-03-22 23:15:50 +0000785 // Certain madnesses can happen with parameter declarations, which
786 // we want to ignore.
787 if (isa<ParmVarDecl>(var)) {
788 // - If the parameter still belongs to the translation unit, then
789 // we're actually just using one parameter in the declaration of
790 // the next. This is useful in e.g. VLAs.
791 if (isa<TranslationUnitDecl>(var->getDeclContext()))
792 return CR_NoCapture;
793
794 // - This particular madness can happen in ill-formed default
795 // arguments; claim it's okay and let downstream code handle it.
796 if (S.CurContext == var->getDeclContext()->getParent())
797 return CR_NoCapture;
798 }
John McCallc63de662011-02-02 13:00:07 +0000799
800 DeclarationName functionName;
801 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
802 functionName = fn->getDeclName();
803 // FIXME: variable from enclosing block that we couldn't capture from!
804
805 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
806 << var->getIdentifier() << functionName;
807 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
808 << var->getIdentifier();
809
810 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +0000811}
812
John McCall351762c2011-02-07 10:33:21 +0000813/// There is a well-formed capture at a particular scope level;
814/// propagate it through all the nested blocks.
815static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
816 const BlockDecl::Capture &capture) {
817 VarDecl *var = capture.getVariable();
818
819 // Update all the inner blocks with the capture information.
820 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
821 i != e; ++i) {
822 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
823 innerBlock->Captures.push_back(
824 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
825 /*nested*/ true, capture.getCopyExpr()));
826 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
827 }
828
829 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
830}
831
832/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +0000833/// given value in the current context requires a variable capture.
834///
835/// This also keeps the captures set in the BlockScopeInfo records
836/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +0000837static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +0000838 ValueDecl *value) {
839 // Only variables ever require capture.
840 VarDecl *var = dyn_cast<VarDecl>(value);
John McCallf4cd4f92011-02-09 01:13:10 +0000841 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +0000842
843 // Fast path: variables from the current context never require capture.
844 DeclContext *DC = S.CurContext;
845 if (var->getDeclContext() == DC) return CR_NoCapture;
846
847 // Only variables with local storage require capture.
848 // FIXME: What about 'const' variables in C++?
849 if (!var->hasLocalStorage()) return CR_NoCapture;
850
851 // Otherwise, we need to capture.
852
853 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +0000854 do {
855 // Only blocks (and eventually C++0x closures) can capture; other
856 // scopes don't work.
857 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +0000858 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +0000859
860 BlockScopeInfo *blockScope =
861 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
862 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
863
John McCall351762c2011-02-07 10:33:21 +0000864 // Check whether we've already captured it in this block. If so,
865 // we're done.
866 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
867 return propagateCapture(S, functionScopesIndex,
868 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +0000869
870 functionScopesIndex--;
871 DC = cast<BlockDecl>(DC)->getDeclContext();
872 } while (var->getDeclContext() != DC);
873
John McCall351762c2011-02-07 10:33:21 +0000874 // Okay, we descended all the way to the block that defines the variable.
875 // Actually try to capture it.
876 QualType type = var->getType();
877
878 // Prohibit variably-modified types.
879 if (type->isVariablyModifiedType()) {
880 S.Diag(loc, diag::err_ref_vm_type);
881 S.Diag(var->getLocation(), diag::note_declared_at);
882 return CR_Error;
883 }
884
885 // Prohibit arrays, even in __block variables, but not references to
886 // them.
887 if (type->isArrayType()) {
888 S.Diag(loc, diag::err_ref_array_type);
889 S.Diag(var->getLocation(), diag::note_declared_at);
890 return CR_Error;
891 }
892
893 S.MarkDeclarationReferenced(loc, var);
894
895 // The BlocksAttr indicates the variable is bound by-reference.
896 bool byRef = var->hasAttr<BlocksAttr>();
897
898 // Build a copy expression.
899 Expr *copyExpr = 0;
900 if (!byRef && S.getLangOptions().CPlusPlus &&
901 !type->isDependentType() && type->isStructureOrClassType()) {
902 // According to the blocks spec, the capture of a variable from
903 // the stack requires a const copy constructor. This is not true
904 // of the copy/move done to move a __block variable to the heap.
905 type.addConst();
906
907 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
908 ExprResult result =
909 S.PerformCopyInitialization(
910 InitializedEntity::InitializeBlock(var->getLocation(),
911 type, false),
912 loc, S.Owned(declRef));
913
914 // Build a full-expression copy expression if initialization
915 // succeeded and used a non-trivial constructor. Recover from
916 // errors by pretending that the copy isn't necessary.
917 if (!result.isInvalid() &&
918 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
919 result = S.MaybeCreateExprWithCleanups(result);
920 copyExpr = result.take();
921 }
922 }
923
924 // We're currently at the declarer; go back to the closure.
925 functionScopesIndex++;
926 BlockScopeInfo *blockScope =
927 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
928
929 // Build a valid capture in this scope.
930 blockScope->Captures.push_back(
931 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
932 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
933
934 // Propagate that to inner captures if necessary.
935 return propagateCapture(S, functionScopesIndex,
936 blockScope->Captures.back());
937}
938
939static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
940 const DeclarationNameInfo &NameInfo,
941 bool byRef) {
942 assert(isa<VarDecl>(vd) && "capturing non-variable");
943
944 VarDecl *var = cast<VarDecl>(vd);
945 assert(var->hasLocalStorage() && "capturing non-local");
946 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
947
948 QualType exprType = var->getType().getNonReferenceType();
949
950 BlockDeclRefExpr *BDRE;
951 if (!byRef) {
952 // The variable will be bound by copy; make it const within the
953 // closure, but record that this was done in the expression.
954 bool constAdded = !exprType.isConstQualified();
955 exprType.addConst();
956
957 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
958 NameInfo.getLoc(), false,
959 constAdded);
960 } else {
961 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
962 NameInfo.getLoc(), true);
963 }
964
965 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +0000966}
Chris Lattner2a9d9892008-10-20 05:16:36 +0000967
John McCalldadc5752010-08-24 06:29:42 +0000968ExprResult
John McCall7decc9e2010-11-18 06:31:45 +0000969Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +0000970 SourceLocation Loc,
971 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000972 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +0000973 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000974}
975
John McCallf4cd4f92011-02-09 01:13:10 +0000976/// BuildDeclRefExpr - Build an expression that references a
977/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +0000978ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +0000979Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000980 const DeclarationNameInfo &NameInfo,
981 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000982 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +0000983
John McCall086a4642010-11-24 05:12:34 +0000984 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000985 SS? SS->getWithLocInContext(Context)
986 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +0000987 D, NameInfo, Ty, VK);
988
989 // Just in case we're building an illegal pointer-to-member.
990 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
991 E->setObjectKind(OK_BitField);
992
993 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000994}
995
John McCallfeb624a2010-11-23 20:48:44 +0000996static ExprResult
997BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
998 const CXXScopeSpec &SS, FieldDecl *Field,
999 DeclAccessPair FoundDecl,
1000 const DeclarationNameInfo &MemberNameInfo);
1001
John McCalldadc5752010-08-24 06:29:42 +00001002ExprResult
John McCallf3a88602011-02-03 08:15:49 +00001003Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
1004 SourceLocation loc,
1005 IndirectFieldDecl *indirectField,
1006 Expr *baseObjectExpr,
1007 SourceLocation opLoc) {
1008 // First, build the expression that refers to the base object.
1009
1010 bool baseObjectIsPointer = false;
1011 Qualifiers baseQuals;
1012
1013 // Case 1: the base of the indirect field is not a field.
1014 VarDecl *baseVariable = indirectField->getVarDecl();
Douglas Gregore10f36d2011-02-18 02:44:58 +00001015 CXXScopeSpec EmptySS;
John McCallf3a88602011-02-03 08:15:49 +00001016 if (baseVariable) {
1017 assert(baseVariable->getType()->isRecordType());
1018
1019 // In principle we could have a member access expression that
1020 // accesses an anonymous struct/union that's a static member of
1021 // the base object's class. However, under the current standard,
1022 // static data members cannot be anonymous structs or unions.
1023 // Supporting this is as easy as building a MemberExpr here.
1024 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1025
1026 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1027
1028 ExprResult result =
Douglas Gregore10f36d2011-02-18 02:44:58 +00001029 BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
John McCallf3a88602011-02-03 08:15:49 +00001030 if (result.isInvalid()) return ExprError();
1031
1032 baseObjectExpr = result.take();
1033 baseObjectIsPointer = false;
1034 baseQuals = baseObjectExpr->getType().getQualifiers();
1035
1036 // Case 2: the base of the indirect field is a field and the user
1037 // wrote a member expression.
1038 } else if (baseObjectExpr) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001039 // The caller provided the base object expression. Determine
1040 // whether its a pointer and whether it adds any qualifiers to the
1041 // anonymous struct/union fields we're looking into.
John McCallf3a88602011-02-03 08:15:49 +00001042 QualType objectType = baseObjectExpr->getType();
1043
1044 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1045 baseObjectIsPointer = true;
1046 objectType = ptr->getPointeeType();
1047 } else {
1048 baseObjectIsPointer = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001049 }
John McCallf3a88602011-02-03 08:15:49 +00001050 baseQuals = objectType.getQualifiers();
1051
1052 // Case 3: the base of the indirect field is a field and we should
1053 // build an implicit member access.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001054 } else {
1055 // We've found a member of an anonymous struct/union that is
1056 // inside a non-anonymous struct/union, so in a well-formed
1057 // program our base object expression is "this".
John McCallf3a88602011-02-03 08:15:49 +00001058 CXXMethodDecl *method = tryCaptureCXXThis();
1059 if (!method) {
1060 Diag(loc, diag::err_invalid_member_use_in_static_method)
1061 << indirectField->getDeclName();
1062 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001063 }
1064
John McCallf3a88602011-02-03 08:15:49 +00001065 // Our base object expression is "this".
1066 baseObjectExpr =
1067 new (Context) CXXThisExpr(loc, method->getThisType(Context),
1068 /*isImplicit=*/ true);
1069 baseObjectIsPointer = true;
1070 baseQuals = Qualifiers::fromCVRMask(method->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001071 }
1072
1073 // Build the implicit member references to the field of the
1074 // anonymous struct/union.
John McCallf3a88602011-02-03 08:15:49 +00001075 Expr *result = baseObjectExpr;
1076 IndirectFieldDecl::chain_iterator
1077 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCallfeb624a2010-11-23 20:48:44 +00001078
John McCallf3a88602011-02-03 08:15:49 +00001079 // Build the first member access in the chain with full information.
1080 if (!baseVariable) {
1081 FieldDecl *field = cast<FieldDecl>(*FI);
John McCallfeb624a2010-11-23 20:48:44 +00001082
John McCallf3a88602011-02-03 08:15:49 +00001083 // FIXME: use the real found-decl info!
1084 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall8ccfcb52009-09-24 19:53:00 +00001085
John McCallf3a88602011-02-03 08:15:49 +00001086 // Make a nameInfo that properly uses the anonymous name.
1087 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall8ccfcb52009-09-24 19:53:00 +00001088
John McCallf3a88602011-02-03 08:15:49 +00001089 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001090 EmptySS, field, foundDecl,
John McCallf3a88602011-02-03 08:15:49 +00001091 memberNameInfo).take();
1092 baseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +00001093
John McCallf3a88602011-02-03 08:15:49 +00001094 // FIXME: check qualified member access
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001095 }
1096
John McCallf3a88602011-02-03 08:15:49 +00001097 // In all cases, we should now skip the first declaration in the chain.
1098 ++FI;
1099
Douglas Gregore10f36d2011-02-18 02:44:58 +00001100 while (FI != FEnd) {
1101 FieldDecl *field = cast<FieldDecl>(*FI++);
John McCallf3a88602011-02-03 08:15:49 +00001102
1103 // FIXME: these are somewhat meaningless
1104 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1105 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCallf3a88602011-02-03 08:15:49 +00001106
1107 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001108 (FI == FEnd? SS : EmptySS), field,
1109 foundDecl, memberNameInfo)
John McCallf3a88602011-02-03 08:15:49 +00001110 .take();
1111 }
1112
1113 return Owned(result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001114}
1115
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001116/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001117/// possibly a list of template arguments.
1118///
1119/// If this produces template arguments, it is permitted to call
1120/// DecomposeTemplateName.
1121///
1122/// This actually loses a lot of source location information for
1123/// non-standard name kinds; we should consider preserving that in
1124/// some way.
1125static void DecomposeUnqualifiedId(Sema &SemaRef,
1126 const UnqualifiedId &Id,
1127 TemplateArgumentListInfo &Buffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001128 DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00001129 const TemplateArgumentListInfo *&TemplateArgs) {
1130 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1131 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1132 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1133
1134 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1135 Id.TemplateId->getTemplateArgs(),
1136 Id.TemplateId->NumArgs);
1137 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1138 TemplateArgsPtr.release();
1139
John McCall3e56fd42010-08-23 07:28:44 +00001140 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001141 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1142 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001143 TemplateArgs = &Buffer;
1144 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001145 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001146 TemplateArgs = 0;
1147 }
1148}
1149
John McCall2d74de92009-12-01 22:10:20 +00001150/// Determines if the given class is provably not derived from all of
1151/// the prospective base classes.
1152static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1153 CXXRecordDecl *Record,
1154 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +00001155 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +00001156 return false;
1157
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001158 RecordDecl *RD = Record->getDefinition();
John McCalla6d407c2009-12-01 22:28:41 +00001159 if (!RD) return false;
1160 Record = cast<CXXRecordDecl>(RD);
1161
John McCall2d74de92009-12-01 22:10:20 +00001162 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1163 E = Record->bases_end(); I != E; ++I) {
1164 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1165 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1166 if (!BaseRT) return false;
1167
1168 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +00001169 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1170 return false;
1171 }
1172
1173 return true;
1174}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001175
John McCall2d74de92009-12-01 22:10:20 +00001176enum IMAKind {
1177 /// The reference is definitely not an instance member access.
1178 IMA_Static,
1179
1180 /// The reference may be an implicit instance member access.
1181 IMA_Mixed,
1182
1183 /// The reference may be to an instance member, but it is invalid if
1184 /// so, because the context is not an instance method.
1185 IMA_Mixed_StaticContext,
1186
1187 /// The reference may be to an instance member, but it is invalid if
1188 /// so, because the context is from an unrelated class.
1189 IMA_Mixed_Unrelated,
1190
1191 /// The reference is definitely an implicit instance member access.
1192 IMA_Instance,
1193
1194 /// The reference may be to an unresolved using declaration.
1195 IMA_Unresolved,
1196
1197 /// The reference may be to an unresolved using declaration and the
1198 /// context is not an instance method.
1199 IMA_Unresolved_StaticContext,
1200
John McCall2d74de92009-12-01 22:10:20 +00001201 /// All possible referrents are instance members and the current
1202 /// context is not an instance method.
1203 IMA_Error_StaticContext,
1204
1205 /// All possible referrents are instance members of an unrelated
1206 /// class.
1207 IMA_Error_Unrelated
1208};
1209
1210/// The given lookup names class member(s) and is not being used for
1211/// an address-of-member expression. Classify the type of access
1212/// according to whether it's possible that this reference names an
1213/// instance member. This is best-effort; it is okay to
1214/// conservatively answer "yes", in which case some errors will simply
1215/// not be caught until template-instantiation.
1216static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1217 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +00001218 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +00001219
John McCall87fe5d52010-05-20 01:18:31 +00001220 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCall2d74de92009-12-01 22:10:20 +00001221 bool isStaticContext =
John McCall87fe5d52010-05-20 01:18:31 +00001222 (!isa<CXXMethodDecl>(DC) ||
1223 cast<CXXMethodDecl>(DC)->isStatic());
John McCall2d74de92009-12-01 22:10:20 +00001224
1225 if (R.isUnresolvableResult())
1226 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1227
1228 // Collect all the declaring classes of instance members we find.
1229 bool hasNonInstance = false;
Sebastian Redl34620312010-11-26 16:28:07 +00001230 bool hasField = false;
John McCall2d74de92009-12-01 22:10:20 +00001231 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1232 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCalla8ae2222010-04-06 21:38:20 +00001233 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00001234
John McCalla8ae2222010-04-06 21:38:20 +00001235 if (D->isCXXInstanceMember()) {
Sebastian Redl34620312010-11-26 16:28:07 +00001236 if (dyn_cast<FieldDecl>(D))
1237 hasField = true;
1238
John McCall2d74de92009-12-01 22:10:20 +00001239 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCall2d74de92009-12-01 22:10:20 +00001240 Classes.insert(R->getCanonicalDecl());
1241 }
1242 else
1243 hasNonInstance = true;
1244 }
1245
1246 // If we didn't find any instance members, it can't be an implicit
1247 // member reference.
1248 if (Classes.empty())
1249 return IMA_Static;
1250
1251 // If the current context is not an instance method, it can't be
1252 // an implicit member reference.
Sebastian Redl34620312010-11-26 16:28:07 +00001253 if (isStaticContext) {
1254 if (hasNonInstance)
1255 return IMA_Mixed_StaticContext;
1256
1257 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1258 // C++0x [expr.prim.general]p10:
1259 // An id-expression that denotes a non-static data member or non-static
1260 // member function of a class can only be used:
1261 // (...)
1262 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1263 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1264 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1265 if (isUnevaluatedExpression)
1266 return IMA_Mixed_StaticContext;
1267 }
1268
1269 return IMA_Error_StaticContext;
1270 }
John McCall2d74de92009-12-01 22:10:20 +00001271
1272 // If we can prove that the current context is unrelated to all the
1273 // declaring classes, it can't be an implicit member reference (in
1274 // which case it's an error if any of those members are selected).
1275 if (IsProvablyNotDerivedFrom(SemaRef,
John McCall87fe5d52010-05-20 01:18:31 +00001276 cast<CXXMethodDecl>(DC)->getParent(),
John McCall2d74de92009-12-01 22:10:20 +00001277 Classes))
1278 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1279
1280 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1281}
1282
1283/// Diagnose a reference to a field with no object available.
1284static void DiagnoseInstanceReference(Sema &SemaRef,
1285 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00001286 NamedDecl *rep,
1287 const DeclarationNameInfo &nameInfo) {
1288 SourceLocation Loc = nameInfo.getLoc();
John McCall2d74de92009-12-01 22:10:20 +00001289 SourceRange Range(Loc);
1290 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1291
John McCallf3a88602011-02-03 08:15:49 +00001292 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCall2d74de92009-12-01 22:10:20 +00001293 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1294 if (MD->isStatic()) {
1295 // "invalid use of member 'x' in static member function"
1296 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCallf3a88602011-02-03 08:15:49 +00001297 << Range << nameInfo.getName();
John McCall2d74de92009-12-01 22:10:20 +00001298 return;
1299 }
1300 }
1301
1302 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCallf3a88602011-02-03 08:15:49 +00001303 << nameInfo.getName() << Range;
John McCall2d74de92009-12-01 22:10:20 +00001304 return;
1305 }
1306
1307 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +00001308}
1309
John McCalld681c392009-12-16 08:11:27 +00001310/// Diagnose an empty lookup.
1311///
1312/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001313bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1314 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +00001315 DeclarationName Name = R.getLookupName();
1316
John McCalld681c392009-12-16 08:11:27 +00001317 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001318 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001319 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1320 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001321 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001322 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001323 diagnostic_suggest = diag::err_undeclared_use_suggest;
1324 }
John McCalld681c392009-12-16 08:11:27 +00001325
Douglas Gregor598b08f2009-12-31 05:20:13 +00001326 // If the original lookup was an unqualified lookup, fake an
1327 // unqualified lookup. This is useful when (for example) the
1328 // original lookup would not have found something because it was a
1329 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001330 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001331 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001332 if (isa<CXXRecordDecl>(DC)) {
1333 LookupQualifiedName(R, DC);
1334
1335 if (!R.empty()) {
1336 // Don't give errors about ambiguities in this lookup.
1337 R.suppressDiagnostics();
1338
1339 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1340 bool isInstance = CurMethod &&
1341 CurMethod->isInstance() &&
1342 DC == CurMethod->getParent();
1343
1344 // Give a code modification hint to insert 'this->'.
1345 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1346 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001347 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001348 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1349 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001350 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001351 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001352 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001353 Diag(R.getNameLoc(), diagnostic) << Name
1354 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1355 QualType DepThisType = DepMethod->getThisType(Context);
1356 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1357 R.getNameLoc(), DepThisType, false);
1358 TemplateArgumentListInfo TList;
1359 if (ULE->hasExplicitTemplateArgs())
1360 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001361
Douglas Gregore16af532011-02-28 18:50:33 +00001362 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001363 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001364 CXXDependentScopeMemberExpr *DepExpr =
1365 CXXDependentScopeMemberExpr::Create(
1366 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001367 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyfe712382010-08-20 20:54:15 +00001368 R.getLookupNameInfo(), &TList);
1369 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001370 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001371 // FIXME: we should be able to handle this case too. It is correct
1372 // to add this-> here. This is a workaround for PR7947.
1373 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001374 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001375 } else {
John McCalld681c392009-12-16 08:11:27 +00001376 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001377 }
John McCalld681c392009-12-16 08:11:27 +00001378
1379 // Do we really want to note all of these?
1380 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1381 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1382
1383 // Tell the callee to try to recover.
1384 return false;
1385 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001386
1387 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001388 }
1389 }
1390
Douglas Gregor598b08f2009-12-31 05:20:13 +00001391 // We didn't find anything, so try to correct for a typo.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001392 DeclarationName Corrected;
Daniel Dunbarf7ced252010-06-02 15:46:52 +00001393 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001394 if (!R.empty()) {
1395 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1396 if (SS.isEmpty())
1397 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1398 << FixItHint::CreateReplacement(R.getNameLoc(),
1399 R.getLookupName().getAsString());
1400 else
1401 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1402 << Name << computeDeclContext(SS, false) << R.getLookupName()
1403 << SS.getRange()
1404 << FixItHint::CreateReplacement(R.getNameLoc(),
1405 R.getLookupName().getAsString());
1406 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1407 Diag(ND->getLocation(), diag::note_previous_decl)
1408 << ND->getDeclName();
1409
1410 // Tell the callee to try to recover.
1411 return false;
1412 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001413
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001414 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1415 // FIXME: If we ended up with a typo for a type name or
1416 // Objective-C class name, we're in trouble because the parser
1417 // is in the wrong place to recover. Suggest the typo
1418 // correction, but don't make it a fix-it since we're not going
1419 // to recover well anyway.
1420 if (SS.isEmpty())
1421 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1422 else
1423 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1424 << Name << computeDeclContext(SS, false) << R.getLookupName()
1425 << SS.getRange();
1426
1427 // Don't try to recover; it won't work.
1428 return true;
1429 }
1430 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001431 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001432 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001433 if (SS.isEmpty())
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001434 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001435 else
Douglas Gregor25363982010-01-01 00:15:04 +00001436 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001437 << Name << computeDeclContext(SS, false) << Corrected
1438 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001439 return true;
1440 }
Douglas Gregor25363982010-01-01 00:15:04 +00001441 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001442 }
1443
1444 // Emit a special diagnostic for failed member lookups.
1445 // FIXME: computing the declaration context might fail here (?)
1446 if (!SS.isEmpty()) {
1447 Diag(R.getNameLoc(), diag::err_no_member)
1448 << Name << computeDeclContext(SS, false)
1449 << SS.getRange();
1450 return true;
1451 }
1452
John McCalld681c392009-12-16 08:11:27 +00001453 // Give up, we can't recover.
1454 Diag(R.getNameLoc(), diagnostic) << Name;
1455 return true;
1456}
1457
Douglas Gregor05fcf842010-11-02 20:36:02 +00001458ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1459 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001460 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1461 if (!IDecl)
1462 return 0;
1463 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1464 if (!ClassImpDecl)
1465 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001466 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001467 if (!property)
1468 return 0;
1469 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001470 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1471 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001472 return 0;
1473 return property;
1474}
1475
Douglas Gregor05fcf842010-11-02 20:36:02 +00001476bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1477 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1478 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1479 if (!IDecl)
1480 return false;
1481 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1482 if (!ClassImpDecl)
1483 return false;
1484 if (ObjCPropertyImplDecl *PIDecl
1485 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1486 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1487 PIDecl->getPropertyIvarDecl())
1488 return false;
1489
1490 return true;
1491}
1492
Fariborz Jahanian18722982010-07-17 00:59:30 +00001493static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001494 LookupResult &Lookup,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001495 IdentifierInfo *II,
1496 SourceLocation NameLoc) {
1497 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001498 bool LookForIvars;
1499 if (Lookup.empty())
1500 LookForIvars = true;
1501 else if (CurMeth->isClassMethod())
1502 LookForIvars = false;
1503 else
1504 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001505 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1506 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001507 if (!LookForIvars)
1508 return 0;
1509
Fariborz Jahanian18722982010-07-17 00:59:30 +00001510 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1511 if (!IDecl)
1512 return 0;
1513 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001514 if (!ClassImpDecl)
1515 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001516 bool DynamicImplSeen = false;
1517 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1518 if (!property)
1519 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001520 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001521 DynamicImplSeen =
1522 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001523 // property implementation has a designated ivar. No need to assume a new
1524 // one.
1525 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1526 return 0;
1527 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001528 if (!DynamicImplSeen) {
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001529 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1530 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001531 NameLoc, NameLoc,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001532 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001533 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001534 (Expr *)0, true);
1535 ClassImpDecl->addDecl(Ivar);
1536 IDecl->makeDeclVisibleInContext(Ivar, false);
1537 property->setPropertyIvarDecl(Ivar);
1538 return Ivar;
1539 }
1540 return 0;
1541}
1542
John McCalldadc5752010-08-24 06:29:42 +00001543ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001544 CXXScopeSpec &SS,
1545 UnqualifiedId &Id,
1546 bool HasTrailingLParen,
1547 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001548 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1549 "cannot be direct & operand and have a trailing lparen");
1550
1551 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001552 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001553
John McCall10eae182009-11-30 22:42:35 +00001554 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001555
1556 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001557 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001558 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001559 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001560
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001561 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001562 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001563 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001564
John McCalle66edc12009-11-24 19:00:30 +00001565 // C++ [temp.dep.expr]p3:
1566 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001567 // -- an identifier that was declared with a dependent type,
1568 // (note: handled after lookup)
1569 // -- a template-id that is dependent,
1570 // (note: handled in BuildTemplateIdExpr)
1571 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001572 // -- a nested-name-specifier that contains a class-name that
1573 // names a dependent type.
1574 // Determine whether this is a member of an unknown specialization;
1575 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001576 bool DependentID = false;
1577 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1578 Name.getCXXNameType()->isDependentType()) {
1579 DependentID = true;
1580 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001581 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001582 if (RequireCompleteDeclContext(SS, DC))
1583 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001584 } else {
1585 DependentID = true;
1586 }
1587 }
1588
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001589 if (DependentID)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001590 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001591 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001592
Fariborz Jahanian86151342010-07-22 23:33:21 +00001593 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001594 // Perform the required lookup.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001595 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001596 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001597 // Lookup the template name again to correctly establish the context in
1598 // which it was found. This is really unfortunate as we already did the
1599 // lookup to determine that it was a template name in the first place. If
1600 // this becomes a performance hit, we can work harder to preserve those
1601 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001602 bool MemberOfUnknownSpecialization;
1603 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1604 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001605
1606 if (MemberOfUnknownSpecialization ||
1607 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1608 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1609 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001610 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001611 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001612 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001613
Douglas Gregora5226932011-02-04 13:35:07 +00001614 // If the result might be in a dependent base class, this is a dependent
1615 // id-expression.
1616 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1617 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1618 TemplateArgs);
1619
John McCalle66edc12009-11-24 19:00:30 +00001620 // If this reference is in an Objective-C method, then we need to do
1621 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001622 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001623 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001624 if (E.isInvalid())
1625 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001626
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001627 if (Expr *Ex = E.takeAs<Expr>())
1628 return Owned(Ex);
1629
1630 // Synthesize ivars lazily.
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001631 if (getLangOptions().ObjCDefaultSynthProperties &&
1632 getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001633 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1634 if (const ObjCPropertyDecl *Property =
1635 canSynthesizeProvisionalIvar(II)) {
1636 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1637 Diag(Property->getLocation(), diag::note_property_declare);
1638 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001639 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1640 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001641 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001642 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001643 // for further use, this must be set to false if in class method.
1644 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001645 }
Chris Lattner59a25942008-03-31 00:36:02 +00001646 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001647
John McCalle66edc12009-11-24 19:00:30 +00001648 if (R.isAmbiguous())
1649 return ExprError();
1650
Douglas Gregor171c45a2009-02-18 21:56:37 +00001651 // Determine whether this name might be a candidate for
1652 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001653 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001654
John McCalle66edc12009-11-24 19:00:30 +00001655 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001656 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001657 // in C90, extension in C99, forbidden in C++).
1658 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1659 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1660 if (D) R.addDecl(D);
1661 }
1662
1663 // If this name wasn't predeclared and if this is not a function
1664 // call, diagnose the problem.
1665 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001666 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001667 return ExprError();
1668
1669 assert(!R.empty() &&
1670 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001671
1672 // If we found an Objective-C instance variable, let
1673 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001674 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001675 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1676 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001677 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001678 assert(E.isInvalid() || E.get());
1679 return move(E);
1680 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001681 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001682 }
Mike Stump11289f42009-09-09 15:08:12 +00001683
John McCalle66edc12009-11-24 19:00:30 +00001684 // This is guaranteed from this point on.
1685 assert(!R.empty() || ADL);
1686
John McCall2d74de92009-12-01 22:10:20 +00001687 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001688 // C++ [class.mfct.non-static]p3:
1689 // When an id-expression that is not part of a class member access
1690 // syntax and not used to form a pointer to member is used in the
1691 // body of a non-static member function of class X, if name lookup
1692 // resolves the name in the id-expression to a non-static non-type
1693 // member of some class C, the id-expression is transformed into a
1694 // class member access expression using (*this) as the
1695 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001696 //
1697 // But we don't actually need to do this for '&' operands if R
1698 // resolved to a function or overloaded function set, because the
1699 // expression is ill-formed if it actually works out to be a
1700 // non-static member function:
1701 //
1702 // C++ [expr.ref]p4:
1703 // Otherwise, if E1.E2 refers to a non-static member function. . .
1704 // [t]he expression can be used only as the left-hand operand of a
1705 // member function call.
1706 //
1707 // There are other safeguards against such uses, but it's important
1708 // to get this right here so that we don't end up making a
1709 // spuriously dependent expression if we're inside a dependent
1710 // instance method.
John McCall57500772009-12-16 12:17:52 +00001711 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001712 bool MightBeImplicitMember;
1713 if (!isAddressOfOperand)
1714 MightBeImplicitMember = true;
1715 else if (!SS.isEmpty())
1716 MightBeImplicitMember = false;
1717 else if (R.isOverloadedResult())
1718 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001719 else if (R.isUnresolvableResult())
1720 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001721 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001722 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1723 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001724
1725 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001726 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001727 }
1728
John McCalle66edc12009-11-24 19:00:30 +00001729 if (TemplateArgs)
1730 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001731
John McCalle66edc12009-11-24 19:00:30 +00001732 return BuildDeclarationNameExpr(SS, R, ADL);
1733}
1734
John McCall57500772009-12-16 12:17:52 +00001735/// Builds an expression which might be an implicit member expression.
John McCalldadc5752010-08-24 06:29:42 +00001736ExprResult
John McCall57500772009-12-16 12:17:52 +00001737Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1738 LookupResult &R,
1739 const TemplateArgumentListInfo *TemplateArgs) {
1740 switch (ClassifyImplicitMemberAccess(*this, R)) {
1741 case IMA_Instance:
1742 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1743
John McCall57500772009-12-16 12:17:52 +00001744 case IMA_Mixed:
1745 case IMA_Mixed_Unrelated:
1746 case IMA_Unresolved:
1747 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1748
1749 case IMA_Static:
1750 case IMA_Mixed_StaticContext:
1751 case IMA_Unresolved_StaticContext:
1752 if (TemplateArgs)
1753 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1754 return BuildDeclarationNameExpr(SS, R, false);
1755
1756 case IMA_Error_StaticContext:
1757 case IMA_Error_Unrelated:
John McCallf3a88602011-02-03 08:15:49 +00001758 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
1759 R.getLookupNameInfo());
John McCall57500772009-12-16 12:17:52 +00001760 return ExprError();
1761 }
1762
1763 llvm_unreachable("unexpected instance member access kind");
1764 return ExprError();
1765}
1766
John McCall10eae182009-11-30 22:42:35 +00001767/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1768/// declaration name, generally during template instantiation.
1769/// There's a large number of things which don't need to be done along
1770/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001771ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001772Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001773 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001774 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001775 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001776 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001777
John McCall0b66eb32010-05-01 00:40:08 +00001778 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001779 return ExprError();
1780
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001781 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001782 LookupQualifiedName(R, DC);
1783
1784 if (R.isAmbiguous())
1785 return ExprError();
1786
1787 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001788 Diag(NameInfo.getLoc(), diag::err_no_member)
1789 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001790 return ExprError();
1791 }
1792
1793 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1794}
1795
1796/// LookupInObjCMethod - The parser has read a name in, and Sema has
1797/// detected that we're currently inside an ObjC method. Perform some
1798/// additional lookup.
1799///
1800/// Ideally, most of this would be done by lookup, but there's
1801/// actually quite a lot of extra work involved.
1802///
1803/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001804ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001805Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001806 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001807 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001808 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001809
John McCalle66edc12009-11-24 19:00:30 +00001810 // There are two cases to handle here. 1) scoped lookup could have failed,
1811 // in which case we should look for an ivar. 2) scoped lookup could have
1812 // found a decl, but that decl is outside the current instance method (i.e.
1813 // a global variable). In these two cases, we do a lookup for an ivar with
1814 // this name, if the lookup sucedes, we replace it our current decl.
1815
1816 // If we're in a class method, we don't normally want to look for
1817 // ivars. But if we don't find anything else, and there's an
1818 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001819 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001820
1821 bool LookForIvars;
1822 if (Lookup.empty())
1823 LookForIvars = true;
1824 else if (IsClassMethod)
1825 LookForIvars = false;
1826 else
1827 LookForIvars = (Lookup.isSingleResult() &&
1828 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001829 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001830 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001831 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001832 ObjCInterfaceDecl *ClassDeclared;
1833 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1834 // Diagnose using an ivar in a class method.
1835 if (IsClassMethod)
1836 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1837 << IV->getDeclName());
1838
1839 // If we're referencing an invalid decl, just return this as a silent
1840 // error node. The error diagnostic was already emitted on the decl.
1841 if (IV->isInvalidDecl())
1842 return ExprError();
1843
1844 // Check if referencing a field with __attribute__((deprecated)).
1845 if (DiagnoseUseOfDecl(IV, Loc))
1846 return ExprError();
1847
1848 // Diagnose the use of an ivar outside of the declaring class.
1849 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1850 ClassDeclared != IFace)
1851 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1852
1853 // FIXME: This should use a new expr for a direct reference, don't
1854 // turn this into Self->ivar, just return a BareIVarExpr or something.
1855 IdentifierInfo &II = Context.Idents.get("self");
1856 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001857 SelfName.setIdentifier(&II, SourceLocation());
John McCalle66edc12009-11-24 19:00:30 +00001858 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001859 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001860 SelfName, false, false);
1861 if (SelfExpr.isInvalid())
1862 return ExprError();
1863
John McCall27584242010-12-06 20:48:59 +00001864 Expr *SelfE = SelfExpr.take();
1865 DefaultLvalueConversion(SelfE);
1866
John McCalle66edc12009-11-24 19:00:30 +00001867 MarkDeclarationReferenced(Loc, IV);
1868 return Owned(new (Context)
1869 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John McCall27584242010-12-06 20:48:59 +00001870 SelfE, true, true));
John McCalle66edc12009-11-24 19:00:30 +00001871 }
Chris Lattner87313662010-04-12 05:10:17 +00001872 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001873 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001874 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001875 ObjCInterfaceDecl *ClassDeclared;
1876 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1877 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1878 IFace == ClassDeclared)
1879 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1880 }
1881 }
1882
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001883 if (Lookup.empty() && II && AllowBuiltinCreation) {
1884 // FIXME. Consolidate this with similar code in LookupName.
1885 if (unsigned BuiltinID = II->getBuiltinID()) {
1886 if (!(getLangOptions().CPlusPlus &&
1887 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1888 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1889 S, Lookup.isForRedeclaration(),
1890 Lookup.getNameLoc());
1891 if (D) Lookup.addDecl(D);
1892 }
1893 }
1894 }
John McCalle66edc12009-11-24 19:00:30 +00001895 // Sentinel value saying that we didn't do anything special.
1896 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001897}
John McCalld14a8642009-11-21 08:51:07 +00001898
John McCall16df1e52010-03-30 21:47:33 +00001899/// \brief Cast a base object to a member's actual type.
1900///
1901/// Logically this happens in three phases:
1902///
1903/// * First we cast from the base type to the naming class.
1904/// The naming class is the class into which we were looking
1905/// when we found the member; it's the qualifier type if a
1906/// qualifier was provided, and otherwise it's the base type.
1907///
1908/// * Next we cast from the naming class to the declaring class.
1909/// If the member we found was brought into a class's scope by
1910/// a using declaration, this is that class; otherwise it's
1911/// the class declaring the member.
1912///
1913/// * Finally we cast from the declaring class to the "true"
1914/// declaring class of the member. This conversion does not
1915/// obey access control.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001916bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001917Sema::PerformObjectMemberConversion(Expr *&From,
1918 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001919 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001920 NamedDecl *Member) {
1921 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1922 if (!RD)
1923 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001924
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001925 QualType DestRecordType;
1926 QualType DestType;
1927 QualType FromRecordType;
1928 QualType FromType = From->getType();
1929 bool PointerConversions = false;
1930 if (isa<FieldDecl>(Member)) {
1931 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001932
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001933 if (FromType->getAs<PointerType>()) {
1934 DestType = Context.getPointerType(DestRecordType);
1935 FromRecordType = FromType->getPointeeType();
1936 PointerConversions = true;
1937 } else {
1938 DestType = DestRecordType;
1939 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001940 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001941 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1942 if (Method->isStatic())
1943 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001944
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001945 DestType = Method->getThisType(Context);
1946 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001947
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001948 if (FromType->getAs<PointerType>()) {
1949 FromRecordType = FromType->getPointeeType();
1950 PointerConversions = true;
1951 } else {
1952 FromRecordType = FromType;
1953 DestType = DestRecordType;
1954 }
1955 } else {
1956 // No conversion necessary.
1957 return false;
1958 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001959
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001960 if (DestType->isDependentType() || FromType->isDependentType())
1961 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001962
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001963 // If the unqualified types are the same, no conversion is necessary.
1964 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1965 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001966
John McCall16df1e52010-03-30 21:47:33 +00001967 SourceRange FromRange = From->getSourceRange();
1968 SourceLocation FromLoc = FromRange.getBegin();
1969
John McCall2536c6d2010-08-25 10:28:54 +00001970 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001971
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001972 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001973 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001974 // class name.
1975 //
1976 // If the member was a qualified name and the qualified referred to a
1977 // specific base subobject type, we'll cast to that intermediate type
1978 // first and then to the object in which the member is declared. That allows
1979 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1980 //
1981 // class Base { public: int x; };
1982 // class Derived1 : public Base { };
1983 // class Derived2 : public Base { };
1984 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1985 //
1986 // void VeryDerived::f() {
1987 // x = 17; // error: ambiguous base subobjects
1988 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1989 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001990 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00001991 QualType QType = QualType(Qualifier->getAsType(), 0);
1992 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1993 assert(QType->isRecordType() && "lookup done with non-record type");
1994
1995 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1996
1997 // In C++98, the qualifier type doesn't actually have to be a base
1998 // type of the object type, in which case we just ignore it.
1999 // Otherwise build the appropriate casts.
2000 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002001 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002002 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002003 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00002004 return true;
2005
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002006 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002007 QType = Context.getPointerType(QType);
John McCall2536c6d2010-08-25 10:28:54 +00002008 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2009 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00002010
2011 FromType = QType;
2012 FromRecordType = QRecordType;
2013
2014 // If the qualifier type was the same as the destination type,
2015 // we're done.
2016 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2017 return false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002018 }
2019 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002020
John McCall16df1e52010-03-30 21:47:33 +00002021 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002022
John McCall16df1e52010-03-30 21:47:33 +00002023 // If we actually found the member through a using declaration, cast
2024 // down to the using declaration's type.
2025 //
2026 // Pointer equality is fine here because only one declaration of a
2027 // class ever has member declarations.
2028 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2029 assert(isa<UsingShadowDecl>(FoundDecl));
2030 QualType URecordType = Context.getTypeDeclType(
2031 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2032
2033 // We only need to do this if the naming-class to declaring-class
2034 // conversion is non-trivial.
2035 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2036 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002037 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002038 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002039 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00002040 return true;
Alexis Huntc46382e2010-04-28 23:02:27 +00002041
John McCall16df1e52010-03-30 21:47:33 +00002042 QualType UType = URecordType;
2043 if (PointerConversions)
2044 UType = Context.getPointerType(UType);
John McCalle3027922010-08-25 11:45:40 +00002045 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00002046 VK, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00002047 FromType = UType;
2048 FromRecordType = URecordType;
2049 }
2050
2051 // We don't do access control for the conversion from the
2052 // declaring class to the true declaring class.
2053 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002054 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002055
John McCallcf142162010-08-07 06:22:56 +00002056 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002057 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2058 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002059 IgnoreAccess))
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002060 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002061
John McCalle3027922010-08-25 11:45:40 +00002062 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00002063 VK, &BasePath);
Fariborz Jahanian3f150832009-07-29 19:40:11 +00002064 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002065}
Douglas Gregor3256d042009-06-30 15:47:41 +00002066
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002067/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00002068static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00002069 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalla8ae2222010-04-06 21:38:20 +00002070 DeclAccessPair FoundDecl,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002071 const DeclarationNameInfo &MemberNameInfo,
2072 QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +00002073 ExprValueKind VK, ExprObjectKind OK,
John McCalle66edc12009-11-24 19:00:30 +00002074 const TemplateArgumentListInfo *TemplateArgs = 0) {
Douglas Gregorea972d32011-02-28 21:54:11 +00002075 return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002076 Member, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002077 TemplateArgs, Ty, VK, OK);
Douglas Gregorc1905232009-08-26 22:36:53 +00002078}
2079
John McCallfeb624a2010-11-23 20:48:44 +00002080static ExprResult
2081BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2082 const CXXScopeSpec &SS, FieldDecl *Field,
2083 DeclAccessPair FoundDecl,
2084 const DeclarationNameInfo &MemberNameInfo) {
2085 // x.a is an l-value if 'a' has a reference type. Otherwise:
2086 // x.a is an l-value/x-value/pr-value if the base is (and note
2087 // that *x is always an l-value), except that if the base isn't
2088 // an ordinary object then we must have an rvalue.
2089 ExprValueKind VK = VK_LValue;
2090 ExprObjectKind OK = OK_Ordinary;
2091 if (!IsArrow) {
2092 if (BaseExpr->getObjectKind() == OK_Ordinary)
2093 VK = BaseExpr->getValueKind();
2094 else
2095 VK = VK_RValue;
2096 }
2097 if (VK != VK_RValue && Field->isBitField())
2098 OK = OK_BitField;
2099
2100 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2101 QualType MemberType = Field->getType();
2102 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2103 MemberType = Ref->getPointeeType();
2104 VK = VK_LValue;
2105 } else {
2106 QualType BaseType = BaseExpr->getType();
2107 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2108
2109 Qualifiers BaseQuals = BaseType.getQualifiers();
2110
2111 // GC attributes are never picked up by members.
2112 BaseQuals.removeObjCGCAttr();
2113
2114 // CVR attributes from the base are picked up by members,
2115 // except that 'mutable' members don't pick up 'const'.
2116 if (Field->isMutable()) BaseQuals.removeConst();
2117
2118 Qualifiers MemberQuals
2119 = S.Context.getCanonicalType(MemberType).getQualifiers();
2120
2121 // TR 18037 does not allow fields to be declared with address spaces.
2122 assert(!MemberQuals.hasAddressSpace());
2123
2124 Qualifiers Combined = BaseQuals + MemberQuals;
2125 if (Combined != MemberQuals)
2126 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2127 }
2128
2129 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
2130 if (S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2131 FoundDecl, Field))
2132 return ExprError();
2133 return S.Owned(BuildMemberExpr(S.Context, BaseExpr, IsArrow, SS,
2134 Field, FoundDecl, MemberNameInfo,
2135 MemberType, VK, OK));
2136}
2137
John McCall2d74de92009-12-01 22:10:20 +00002138/// Builds an implicit member access expression. The current context
2139/// is known to be an instance method, and the given unqualified lookup
2140/// set is known to contain only instance members, at least one of which
2141/// is from an appropriate type.
John McCalldadc5752010-08-24 06:29:42 +00002142ExprResult
John McCall2d74de92009-12-01 22:10:20 +00002143Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2144 LookupResult &R,
2145 const TemplateArgumentListInfo *TemplateArgs,
2146 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00002147 assert(!R.empty() && !R.isAmbiguous());
2148
John McCallf3a88602011-02-03 08:15:49 +00002149 SourceLocation loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00002150
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002151 // We may have found a field within an anonymous union or struct
2152 // (C++ [class.union]).
John McCalle66edc12009-11-24 19:00:30 +00002153 // FIXME: template-ids inside anonymous structs?
Francois Pichet783dd6e2010-11-21 06:08:52 +00002154 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCallf3a88602011-02-03 08:15:49 +00002155 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002156
John McCallf3a88602011-02-03 08:15:49 +00002157 // If this is known to be an instance access, go ahead and build an
2158 // implicit 'this' expression now.
John McCall2d74de92009-12-01 22:10:20 +00002159 // 'this' expression now.
John McCallf3a88602011-02-03 08:15:49 +00002160 CXXMethodDecl *method = tryCaptureCXXThis();
2161 assert(method && "didn't correctly pre-flight capture of 'this'");
2162
2163 QualType thisType = method->getThisType(Context);
2164 Expr *baseExpr = 0; // null signifies implicit access
John McCall2d74de92009-12-01 22:10:20 +00002165 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00002166 SourceLocation Loc = R.getNameLoc();
2167 if (SS.getRange().isValid())
2168 Loc = SS.getRange().getBegin();
John McCallf3a88602011-02-03 08:15:49 +00002169 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002170 }
2171
John McCallf3a88602011-02-03 08:15:49 +00002172 return BuildMemberReferenceExpr(baseExpr, thisType,
John McCall2d74de92009-12-01 22:10:20 +00002173 /*OpLoc*/ SourceLocation(),
2174 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00002175 SS,
2176 /*FirstQualifierInScope*/ 0,
2177 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00002178}
2179
John McCalle66edc12009-11-24 19:00:30 +00002180bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002181 const LookupResult &R,
2182 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002183 // Only when used directly as the postfix-expression of a call.
2184 if (!HasTrailingLParen)
2185 return false;
2186
2187 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002188 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002189 return false;
2190
2191 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002192 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002193 return false;
2194
2195 // Turn off ADL when we find certain kinds of declarations during
2196 // normal lookup:
2197 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2198 NamedDecl *D = *I;
2199
2200 // C++0x [basic.lookup.argdep]p3:
2201 // -- a declaration of a class member
2202 // Since using decls preserve this property, we check this on the
2203 // original decl.
John McCall57500772009-12-16 12:17:52 +00002204 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002205 return false;
2206
2207 // C++0x [basic.lookup.argdep]p3:
2208 // -- a block-scope function declaration that is not a
2209 // using-declaration
2210 // NOTE: we also trigger this for function templates (in fact, we
2211 // don't check the decl type at all, since all other decl types
2212 // turn off ADL anyway).
2213 if (isa<UsingShadowDecl>(D))
2214 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2215 else if (D->getDeclContext()->isFunctionOrMethod())
2216 return false;
2217
2218 // C++0x [basic.lookup.argdep]p3:
2219 // -- a declaration that is neither a function or a function
2220 // template
2221 // And also for builtin functions.
2222 if (isa<FunctionDecl>(D)) {
2223 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2224
2225 // But also builtin functions.
2226 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2227 return false;
2228 } else if (!isa<FunctionTemplateDecl>(D))
2229 return false;
2230 }
2231
2232 return true;
2233}
2234
2235
John McCalld14a8642009-11-21 08:51:07 +00002236/// Diagnoses obvious problems with the use of the given declaration
2237/// as an expression. This is only actually called for lookups that
2238/// were not overloaded, and it doesn't promise that the declaration
2239/// will in fact be used.
2240static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2241 if (isa<TypedefDecl>(D)) {
2242 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2243 return true;
2244 }
2245
2246 if (isa<ObjCInterfaceDecl>(D)) {
2247 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2248 return true;
2249 }
2250
2251 if (isa<NamespaceDecl>(D)) {
2252 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2253 return true;
2254 }
2255
2256 return false;
2257}
2258
John McCalldadc5752010-08-24 06:29:42 +00002259ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002260Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002261 LookupResult &R,
2262 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002263 // If this is a single, fully-resolved result and we don't need ADL,
2264 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002265 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002266 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2267 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002268
2269 // We only need to check the declaration if there's exactly one
2270 // result, because in the overloaded case the results can only be
2271 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002272 if (R.isSingleResult() &&
2273 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002274 return ExprError();
2275
John McCall58cc69d2010-01-27 01:50:18 +00002276 // Otherwise, just build an unresolved lookup expression. Suppress
2277 // any lookup-related diagnostics; we'll hash these out later, when
2278 // we've picked a target.
2279 R.suppressDiagnostics();
2280
John McCalld14a8642009-11-21 08:51:07 +00002281 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002282 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002283 SS.getWithLocInContext(Context),
2284 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002285 NeedsADL, R.isOverloadedResult(),
2286 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002287
2288 return Owned(ULE);
2289}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002290
John McCalld14a8642009-11-21 08:51:07 +00002291/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002292ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002293Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002294 const DeclarationNameInfo &NameInfo,
2295 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002296 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002297 assert(!isa<FunctionTemplateDecl>(D) &&
2298 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002299
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002300 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002301 if (CheckDeclInExpr(*this, Loc, D))
2302 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002303
Douglas Gregore7488b92009-12-01 16:58:18 +00002304 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2305 // Specifically diagnose references to class templates that are missing
2306 // a template argument list.
2307 Diag(Loc, diag::err_template_decl_ref)
2308 << Template << SS.getRange();
2309 Diag(Template->getLocation(), diag::note_template_decl_here);
2310 return ExprError();
2311 }
2312
2313 // Make sure that we're referring to a value.
2314 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2315 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002316 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002317 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002318 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002319 return ExprError();
2320 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002321
Douglas Gregor171c45a2009-02-18 21:56:37 +00002322 // Check whether this declaration can be used. Note that we suppress
2323 // this check when we're going to perform argument-dependent lookup
2324 // on this function name, because this might not be the function
2325 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002326 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002327 return ExprError();
2328
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002329 // Only create DeclRefExpr's for valid Decl's.
2330 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002331 return ExprError();
2332
John McCallf3a88602011-02-03 08:15:49 +00002333 // Handle members of anonymous structs and unions. If we got here,
2334 // and the reference is to a class member indirect field, then this
2335 // must be the subject of a pointer-to-member expression.
2336 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2337 if (!indirectField->isCXXClassMember())
2338 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2339 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002340
Chris Lattner2a9d9892008-10-20 05:16:36 +00002341 // If the identifier reference is inside a block, and it refers to a value
2342 // that is outside the block, create a BlockDeclRefExpr instead of a
2343 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2344 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002345 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002346 // We do not do this for things like enum constants, global variables, etc,
2347 // as they do not get snapshotted.
2348 //
John McCall351762c2011-02-07 10:33:21 +00002349 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002350 case CR_Error:
2351 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002352
John McCallc63de662011-02-02 13:00:07 +00002353 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002354 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2355 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2356
2357 case CR_CaptureByRef:
2358 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2359 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002360
2361 case CR_NoCapture: {
2362 // If this reference is not in a block or if the referenced
2363 // variable is within the block, create a normal DeclRefExpr.
2364
2365 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002366 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002367
2368 switch (D->getKind()) {
2369 // Ignore all the non-ValueDecl kinds.
2370#define ABSTRACT_DECL(kind)
2371#define VALUE(type, base)
2372#define DECL(type, base) \
2373 case Decl::type:
2374#include "clang/AST/DeclNodes.inc"
2375 llvm_unreachable("invalid value decl kind");
2376 return ExprError();
2377
2378 // These shouldn't make it here.
2379 case Decl::ObjCAtDefsField:
2380 case Decl::ObjCIvar:
2381 llvm_unreachable("forming non-member reference to ivar?");
2382 return ExprError();
2383
2384 // Enum constants are always r-values and never references.
2385 // Unresolved using declarations are dependent.
2386 case Decl::EnumConstant:
2387 case Decl::UnresolvedUsingValue:
2388 valueKind = VK_RValue;
2389 break;
2390
2391 // Fields and indirect fields that got here must be for
2392 // pointer-to-member expressions; we just call them l-values for
2393 // internal consistency, because this subexpression doesn't really
2394 // exist in the high-level semantics.
2395 case Decl::Field:
2396 case Decl::IndirectField:
2397 assert(getLangOptions().CPlusPlus &&
2398 "building reference to field in C?");
2399
2400 // These can't have reference type in well-formed programs, but
2401 // for internal consistency we do this anyway.
2402 type = type.getNonReferenceType();
2403 valueKind = VK_LValue;
2404 break;
2405
2406 // Non-type template parameters are either l-values or r-values
2407 // depending on the type.
2408 case Decl::NonTypeTemplateParm: {
2409 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2410 type = reftype->getPointeeType();
2411 valueKind = VK_LValue; // even if the parameter is an r-value reference
2412 break;
2413 }
2414
2415 // For non-references, we need to strip qualifiers just in case
2416 // the template parameter was declared as 'const int' or whatever.
2417 valueKind = VK_RValue;
2418 type = type.getUnqualifiedType();
2419 break;
2420 }
2421
2422 case Decl::Var:
2423 // In C, "extern void blah;" is valid and is an r-value.
2424 if (!getLangOptions().CPlusPlus &&
2425 !type.hasQualifiers() &&
2426 type->isVoidType()) {
2427 valueKind = VK_RValue;
2428 break;
2429 }
2430 // fallthrough
2431
2432 case Decl::ImplicitParam:
2433 case Decl::ParmVar:
2434 // These are always l-values.
2435 valueKind = VK_LValue;
2436 type = type.getNonReferenceType();
2437 break;
2438
2439 case Decl::Function: {
2440 // Functions are l-values in C++.
2441 if (getLangOptions().CPlusPlus) {
2442 valueKind = VK_LValue;
2443 break;
2444 }
2445
2446 // C99 DR 316 says that, if a function type comes from a
2447 // function definition (without a prototype), that type is only
2448 // used for checking compatibility. Therefore, when referencing
2449 // the function, we pretend that we don't have the full function
2450 // type.
2451 if (!cast<FunctionDecl>(VD)->hasPrototype())
2452 if (const FunctionProtoType *proto = type->getAs<FunctionProtoType>())
2453 type = Context.getFunctionNoProtoType(proto->getResultType(),
2454 proto->getExtInfo());
2455
2456 // Functions are r-values in C.
2457 valueKind = VK_RValue;
2458 break;
2459 }
2460
2461 case Decl::CXXMethod:
2462 // C++ methods are l-values if static, r-values if non-static.
2463 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2464 valueKind = VK_LValue;
2465 break;
2466 }
2467 // fallthrough
2468
2469 case Decl::CXXConversion:
2470 case Decl::CXXDestructor:
2471 case Decl::CXXConstructor:
2472 valueKind = VK_RValue;
2473 break;
2474 }
2475
2476 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2477 }
2478
John McCallc63de662011-02-02 13:00:07 +00002479 }
John McCall7decc9e2010-11-18 06:31:45 +00002480
John McCall351762c2011-02-07 10:33:21 +00002481 llvm_unreachable("unknown capture result");
2482 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002483}
Chris Lattnere168f762006-11-10 05:29:30 +00002484
John McCalldadc5752010-08-24 06:29:42 +00002485ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Sebastian Redlffbcf962009-01-18 18:53:16 +00002486 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002487 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002488
Chris Lattnere168f762006-11-10 05:29:30 +00002489 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002490 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002491 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2492 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2493 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002494 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002495
Chris Lattnera81a0272008-01-12 08:14:25 +00002496 // Pre-defined identifiers are of type char[x], where x is the length of the
2497 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002498
Anders Carlsson2fb08242009-09-08 18:24:21 +00002499 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002500 if (!currentDecl && getCurBlock())
2501 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002502 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002503 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002504 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002505 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002506
Anders Carlsson0b209a82009-09-11 01:22:35 +00002507 QualType ResTy;
2508 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2509 ResTy = Context.DependentTy;
2510 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002511 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002512
Anders Carlsson0b209a82009-09-11 01:22:35 +00002513 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002514 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002515 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2516 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002517 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002518}
2519
John McCalldadc5752010-08-24 06:29:42 +00002520ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002521 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002522 bool Invalid = false;
2523 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2524 if (Invalid)
2525 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002526
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002527 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2528 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00002529 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002530 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002531
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002532 QualType Ty;
2533 if (!getLangOptions().CPlusPlus)
2534 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2535 else if (Literal.isWide())
2536 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002537 else if (Literal.isMultiChar())
2538 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002539 else
2540 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002541
Sebastian Redl20614a72009-01-20 22:23:13 +00002542 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2543 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002544 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002545}
2546
John McCalldadc5752010-08-24 06:29:42 +00002547ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002548 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002549 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2550 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002551 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002552 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002553 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002554 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002555 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002556
Chris Lattner23b7eb62007-06-15 23:05:46 +00002557 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002558 // Add padding so that NumericLiteralParser can overread by one character.
2559 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002560 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002561
Chris Lattner67ca9252007-05-21 01:08:44 +00002562 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002563 bool Invalid = false;
2564 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2565 if (Invalid)
2566 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002567
Mike Stump11289f42009-09-09 15:08:12 +00002568 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002569 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002570 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002571 return ExprError();
2572
Chris Lattner1c20a172007-08-26 03:42:43 +00002573 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002574
Chris Lattner1c20a172007-08-26 03:42:43 +00002575 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002576 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002577 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002578 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002579 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002580 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002581 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002582 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002583
2584 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2585
John McCall53b93a02009-12-24 09:08:04 +00002586 using llvm::APFloat;
2587 APFloat Val(Format);
2588
2589 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002590
2591 // Overflow is always an error, but underflow is only an error if
2592 // we underflowed to zero (APFloat reports denormals as underflow).
2593 if ((result & APFloat::opOverflow) ||
2594 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002595 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002596 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002597 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002598 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002599 APFloat::getLargest(Format).toString(buffer);
2600 } else {
John McCall62abc942010-02-26 23:35:57 +00002601 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002602 APFloat::getSmallest(Format).toString(buffer);
2603 }
2604
2605 Diag(Tok.getLocation(), diagnostic)
2606 << Ty
2607 << llvm::StringRef(buffer.data(), buffer.size());
2608 }
2609
2610 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002611 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002612
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002613 if (Ty == Context.DoubleTy) {
2614 if (getLangOptions().SinglePrecisionConstants) {
2615 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2616 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2617 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
2618 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2619 }
2620 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002621 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002622 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002623 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002624 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002625
Neil Boothac582c52007-08-29 22:00:19 +00002626 // long long is a C99 feature.
2627 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002628 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002629 Diag(Tok.getLocation(), diag::ext_longlong);
2630
Chris Lattner67ca9252007-05-21 01:08:44 +00002631 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002632 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002633
Chris Lattner67ca9252007-05-21 01:08:44 +00002634 if (Literal.GetIntegerValue(ResultVal)) {
2635 // If this value didn't fit into uintmax_t, warn and force to ull.
2636 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002637 Ty = Context.UnsignedLongLongTy;
2638 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002639 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002640 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002641 // If this value fits into a ULL, try to figure out what else it fits into
2642 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002643
Chris Lattner67ca9252007-05-21 01:08:44 +00002644 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2645 // be an unsigned int.
2646 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2647
2648 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002649 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002650 if (!Literal.isLong && !Literal.isLongLong) {
2651 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002652 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002653
Chris Lattner67ca9252007-05-21 01:08:44 +00002654 // Does it fit in a unsigned int?
2655 if (ResultVal.isIntN(IntSize)) {
2656 // Does it fit in a signed int?
2657 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002658 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002659 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002660 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002661 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002662 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002663 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002664
Chris Lattner67ca9252007-05-21 01:08:44 +00002665 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002666 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002667 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002668
Chris Lattner67ca9252007-05-21 01:08:44 +00002669 // Does it fit in a unsigned long?
2670 if (ResultVal.isIntN(LongSize)) {
2671 // Does it fit in a signed long?
2672 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002673 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002674 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002675 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002676 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002677 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002678 }
2679
Chris Lattner67ca9252007-05-21 01:08:44 +00002680 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002681 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002682 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002683
Chris Lattner67ca9252007-05-21 01:08:44 +00002684 // Does it fit in a unsigned long long?
2685 if (ResultVal.isIntN(LongLongSize)) {
2686 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002687 // To be compatible with MSVC, hex integer literals ending with the
2688 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002689 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2690 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002691 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002692 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002693 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002694 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002695 }
2696 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002697
Chris Lattner67ca9252007-05-21 01:08:44 +00002698 // If we still couldn't decide a type, we probably have something that
2699 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002700 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002701 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002702 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002703 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002704 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002705
Chris Lattner55258cf2008-05-09 05:59:00 +00002706 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002707 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002708 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002709 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002710 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002711
Chris Lattner1c20a172007-08-26 03:42:43 +00002712 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2713 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002714 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002715 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002716
2717 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002718}
2719
John McCalldadc5752010-08-24 06:29:42 +00002720ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002721 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002722 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002723 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002724}
2725
Steve Naroff71b59a92007-06-04 22:22:31 +00002726/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00002727/// See C99 6.3.2.1p[2-4] for more details.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002728bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2729 SourceLocation OpLoc,
2730 SourceRange ExprRange,
2731 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002732 if (exprType->isDependentType())
2733 return false;
2734
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002735 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2736 // the result is the size of the referenced type."
2737 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2738 // result shall be the alignment of the referenced type."
2739 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2740 exprType = Ref->getPointeeType();
2741
Peter Collingbournee190dee2011-03-11 19:24:49 +00002742 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2743 // scalar or vector data type argument..."
2744 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2745 // type (C99 6.2.5p18) or void.
2746 if (ExprKind == UETT_VecStep) {
2747 if (!(exprType->isArithmeticType() || exprType->isVoidType() ||
2748 exprType->isVectorType())) {
2749 Diag(OpLoc, diag::err_vecstep_non_scalar_vector_type)
2750 << exprType << ExprRange;
2751 return true;
2752 }
2753 }
2754
Steve Naroff043d45d2007-05-15 02:32:35 +00002755 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00002756 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002757 // alignof(function) is allowed as an extension.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002758 if (ExprKind == UETT_SizeOf)
2759 Diag(OpLoc, diag::ext_sizeof_function_type)
2760 << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00002761 return false;
2762 }
Mike Stump11289f42009-09-09 15:08:12 +00002763
Peter Collingbournee190dee2011-03-11 19:24:49 +00002764 // Allow sizeof(void)/alignof(void) as an extension. vec_step(void) is not
2765 // an extension, as void is a built-in scalar type (OpenCL 1.1 6.1.1).
Chris Lattnerb1355b12009-01-24 19:46:37 +00002766 if (exprType->isVoidType()) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002767 if (ExprKind != UETT_VecStep)
2768 Diag(OpLoc, diag::ext_sizeof_void_type)
2769 << ExprKind << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00002770 return false;
2771 }
Mike Stump11289f42009-09-09 15:08:12 +00002772
Chris Lattner62975a72009-04-24 00:30:45 +00002773 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002774 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002775 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002776 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002777
Chris Lattner62975a72009-04-24 00:30:45 +00002778 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCall8b07ec22010-05-15 11:32:37 +00002779 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002780 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002781 << exprType << (ExprKind == UETT_SizeOf)
2782 << ExprRange;
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002783 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00002784 }
Mike Stump11289f42009-09-09 15:08:12 +00002785
Chris Lattner62975a72009-04-24 00:30:45 +00002786 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002787}
2788
John McCall36e7fe32010-10-12 00:20:44 +00002789static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2790 SourceRange ExprRange) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002791 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002792
Mike Stump11289f42009-09-09 15:08:12 +00002793 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002794 if (isa<DeclRefExpr>(E))
2795 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002796
2797 // Cannot know anything else if the expression is dependent.
2798 if (E->isTypeDependent())
2799 return false;
2800
Douglas Gregor71235ec2009-05-02 02:18:30 +00002801 if (E->getBitField()) {
John McCall36e7fe32010-10-12 00:20:44 +00002802 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor71235ec2009-05-02 02:18:30 +00002803 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002804 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002805
2806 // Alignment of a field access is always okay, so long as it isn't a
2807 // bit-field.
2808 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002809 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002810 return false;
2811
Peter Collingbournee190dee2011-03-11 19:24:49 +00002812 return S.CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
2813 UETT_AlignOf);
2814}
2815
2816bool Sema::CheckVecStepExpr(Expr *E, SourceLocation OpLoc,
2817 SourceRange ExprRange) {
2818 E = E->IgnoreParens();
2819
2820 // Cannot know anything else if the expression is dependent.
2821 if (E->isTypeDependent())
2822 return false;
2823
2824 return CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
2825 UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002826}
2827
Douglas Gregor0950e412009-03-13 21:01:28 +00002828/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002829ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002830Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2831 SourceLocation OpLoc,
2832 UnaryExprOrTypeTrait ExprKind,
2833 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002834 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002835 return ExprError();
2836
John McCallbcd03502009-12-07 02:54:59 +00002837 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002838
Douglas Gregor0950e412009-03-13 21:01:28 +00002839 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002840 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002841 return ExprError();
2842
2843 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002844 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2845 Context.getSizeType(),
2846 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002847}
2848
2849/// \brief Build a sizeof or alignof expression given an expression
2850/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002851ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002852Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2853 UnaryExprOrTypeTrait ExprKind,
2854 SourceRange R) {
Douglas Gregor0950e412009-03-13 21:01:28 +00002855 // Verify that the operand is valid.
2856 bool isInvalid = false;
2857 if (E->isTypeDependent()) {
2858 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002859 } else if (ExprKind == UETT_AlignOf) {
John McCall36e7fe32010-10-12 00:20:44 +00002860 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002861 } else if (ExprKind == UETT_VecStep) {
2862 isInvalid = CheckVecStepExpr(E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002863 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00002864 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2865 isInvalid = true;
John McCall36226622010-10-12 02:09:17 +00002866 } else if (E->getType()->isPlaceholderType()) {
2867 ExprResult PE = CheckPlaceholderExpr(E, OpLoc);
2868 if (PE.isInvalid()) return ExprError();
Peter Collingbournee190dee2011-03-11 19:24:49 +00002869 return CreateUnaryExprOrTypeTraitExpr(PE.take(), OpLoc, ExprKind, R);
Douglas Gregor0950e412009-03-13 21:01:28 +00002870 } else {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002871 isInvalid = CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, R,
2872 UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00002873 }
2874
2875 if (isInvalid)
2876 return ExprError();
2877
2878 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002879 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, E,
2880 Context.getSizeType(),
2881 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002882}
2883
Peter Collingbournee190dee2011-03-11 19:24:49 +00002884/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2885/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00002886/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002887ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002888Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2889 UnaryExprOrTypeTrait ExprKind, bool isType,
2890 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002891 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002892 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002893
Sebastian Redl6f282892008-11-11 17:56:53 +00002894 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002895 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002896 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002897 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002898 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002899
Douglas Gregor0950e412009-03-13 21:01:28 +00002900 Expr *ArgEx = (Expr *)TyOrEx;
John McCalldadc5752010-08-24 06:29:42 +00002901 ExprResult Result
Peter Collingbournee190dee2011-03-11 19:24:49 +00002902 = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind,
2903 ArgEx->getSourceRange());
Douglas Gregor0950e412009-03-13 21:01:28 +00002904
Douglas Gregor0950e412009-03-13 21:01:28 +00002905 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002906}
2907
John McCall4bc41ae2010-11-18 19:01:18 +00002908static QualType CheckRealImagOperand(Sema &S, Expr *&V, SourceLocation Loc,
2909 bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002910 if (V->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002911 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002912
John McCall34376a62010-12-04 03:47:34 +00002913 // _Real and _Imag are only l-values for normal l-values.
2914 if (V->getObjectKind() != OK_Ordinary)
John McCall27584242010-12-06 20:48:59 +00002915 S.DefaultLvalueConversion(V);
John McCall34376a62010-12-04 03:47:34 +00002916
Chris Lattnere267f5d2007-08-26 05:39:26 +00002917 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00002918 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002919 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002920
Chris Lattnere267f5d2007-08-26 05:39:26 +00002921 // Otherwise they pass through real integer and floating point types here.
2922 if (V->getType()->isArithmeticType())
2923 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002924
John McCall36226622010-10-12 02:09:17 +00002925 // Test for placeholders.
John McCall4bc41ae2010-11-18 19:01:18 +00002926 ExprResult PR = S.CheckPlaceholderExpr(V, Loc);
John McCall36226622010-10-12 02:09:17 +00002927 if (PR.isInvalid()) return QualType();
2928 if (PR.take() != V) {
2929 V = PR.take();
John McCall4bc41ae2010-11-18 19:01:18 +00002930 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00002931 }
2932
Chris Lattnere267f5d2007-08-26 05:39:26 +00002933 // Reject anything else.
John McCall4bc41ae2010-11-18 19:01:18 +00002934 S.Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00002935 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002936 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002937}
2938
2939
Chris Lattnere168f762006-11-10 05:29:30 +00002940
John McCalldadc5752010-08-24 06:29:42 +00002941ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002942Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002943 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002944 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002945 switch (Kind) {
2946 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002947 case tok::plusplus: Opc = UO_PostInc; break;
2948 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002949 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002950
John McCallb268a282010-08-23 23:25:46 +00002951 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002952}
2953
John McCall4bc41ae2010-11-18 19:01:18 +00002954/// Expressions of certain arbitrary types are forbidden by C from
2955/// having l-value type. These are:
2956/// - 'void', but not qualified void
2957/// - function types
2958///
2959/// The exact rule here is C99 6.3.2.1:
2960/// An lvalue is an expression with an object type or an incomplete
2961/// type other than void.
2962static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
2963 return ((T->isVoidType() && !T.hasQualifiers()) ||
2964 T->isFunctionType());
2965}
2966
John McCalldadc5752010-08-24 06:29:42 +00002967ExprResult
John McCallb268a282010-08-23 23:25:46 +00002968Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2969 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002970 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002971 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002972 if (Result.isInvalid()) return ExprError();
2973 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002974
John McCallb268a282010-08-23 23:25:46 +00002975 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00002976
Douglas Gregor40412ac2008-11-19 17:17:41 +00002977 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002978 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002979 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002980 Context.DependentTy,
2981 VK_LValue, OK_Ordinary,
2982 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002983 }
2984
Mike Stump11289f42009-09-09 15:08:12 +00002985 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002986 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002987 LHSExp->getType()->isEnumeralType() ||
2988 RHSExp->getType()->isRecordType() ||
2989 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00002990 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00002991 }
2992
John McCallb268a282010-08-23 23:25:46 +00002993 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00002994}
2995
2996
John McCalldadc5752010-08-24 06:29:42 +00002997ExprResult
John McCallb268a282010-08-23 23:25:46 +00002998Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2999 Expr *Idx, SourceLocation RLoc) {
3000 Expr *LHSExp = Base;
3001 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003002
Chris Lattner36d572b2007-07-16 00:14:47 +00003003 // Perform default conversions.
Douglas Gregorb92a1562010-02-03 00:27:59 +00003004 if (!LHSExp->getType()->getAs<VectorType>())
3005 DefaultFunctionArrayLvalueConversion(LHSExp);
3006 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003007
Chris Lattner36d572b2007-07-16 00:14:47 +00003008 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003009 ExprValueKind VK = VK_LValue;
3010 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003011
Steve Naroffc1aadb12007-03-28 21:49:40 +00003012 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003013 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003014 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003015 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003016 Expr *BaseExpr, *IndexExpr;
3017 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003018 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3019 BaseExpr = LHSExp;
3020 IndexExpr = RHSExp;
3021 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003022 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003023 BaseExpr = LHSExp;
3024 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003025 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003026 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003027 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003028 BaseExpr = RHSExp;
3029 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003030 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003031 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003032 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003033 BaseExpr = LHSExp;
3034 IndexExpr = RHSExp;
3035 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003036 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003037 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003038 // Handle the uncommon case of "123[Ptr]".
3039 BaseExpr = RHSExp;
3040 IndexExpr = LHSExp;
3041 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003042 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003043 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003044 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003045 VK = LHSExp->getValueKind();
3046 if (VK != VK_RValue)
3047 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003048
Chris Lattner36d572b2007-07-16 00:14:47 +00003049 // FIXME: need to deal with const...
3050 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003051 } else if (LHSTy->isArrayType()) {
3052 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003053 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003054 // wasn't promoted because of the C90 rule that doesn't
3055 // allow promoting non-lvalue arrays. Warn, then
3056 // force the promotion here.
3057 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3058 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003059 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
John McCalle3027922010-08-25 11:45:40 +00003060 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00003061 LHSTy = LHSExp->getType();
3062
3063 BaseExpr = LHSExp;
3064 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003065 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003066 } else if (RHSTy->isArrayType()) {
3067 // Same as previous, except for 123[f().a] case
3068 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3069 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003070 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
John McCalle3027922010-08-25 11:45:40 +00003071 CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00003072 RHSTy = RHSExp->getType();
3073
3074 BaseExpr = RHSExp;
3075 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003076 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003077 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003078 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3079 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003080 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003081 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003082 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003083 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3084 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003085
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003086 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003087 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3088 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003089 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3090
Douglas Gregorac1fb652009-03-24 19:52:54 +00003091 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003092 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3093 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003094 // incomplete types are not object types.
3095 if (ResultType->isFunctionType()) {
3096 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3097 << ResultType << BaseExpr->getSourceRange();
3098 return ExprError();
3099 }
Mike Stump11289f42009-09-09 15:08:12 +00003100
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003101 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3102 // GNU extension: subscripting on pointer to void
3103 Diag(LLoc, diag::ext_gnu_void_ptr)
3104 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003105
3106 // C forbids expressions of unqualified void type from being l-values.
3107 // See IsCForbiddenLValueType.
3108 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003109 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003110 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003111 PDiag(diag::err_subscript_incomplete_type)
3112 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003113 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003114
Chris Lattner62975a72009-04-24 00:30:45 +00003115 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003116 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003117 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3118 << ResultType << BaseExpr->getSourceRange();
3119 return ExprError();
3120 }
Mike Stump11289f42009-09-09 15:08:12 +00003121
John McCall4bc41ae2010-11-18 19:01:18 +00003122 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3123 !IsCForbiddenLValueType(Context, ResultType));
3124
Mike Stump4e1f26a2009-02-19 03:04:26 +00003125 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003126 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003127}
3128
John McCall4bc41ae2010-11-18 19:01:18 +00003129/// Check an ext-vector component access expression.
3130///
3131/// VK should be set in advance to the value kind of the base
3132/// expression.
3133static QualType
3134CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3135 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00003136 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00003137 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3138 // see FIXME there.
3139 //
3140 // FIXME: This logic can be greatly simplified by splitting it along
3141 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00003142 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00003143
Steve Narofff8fd09e2007-07-27 22:15:19 +00003144 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003145 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003146
Mike Stump4e1f26a2009-02-19 03:04:26 +00003147 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00003148 // special names that indicate a subset of exactly half the elements are
3149 // to be selected.
3150 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003151
Nate Begemanbb70bf62009-01-18 01:47:54 +00003152 // This flag determines whether or not CompName has an 's' char prefix,
3153 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00003154 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00003155
John McCall4bc41ae2010-11-18 19:01:18 +00003156 bool HasRepeated = false;
3157 bool HasIndex[16] = {};
3158
3159 int Idx;
3160
Nate Begemanf322eab2008-05-09 06:41:27 +00003161 // Check that we've found one of the special components, or that the component
3162 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003163 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00003164 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3165 HalvingSwizzle = true;
John McCall4bc41ae2010-11-18 19:01:18 +00003166 } else if (!HexSwizzle &&
3167 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3168 do {
3169 if (HasIndex[Idx]) HasRepeated = true;
3170 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003171 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003172 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3173 } else {
3174 if (HexSwizzle) compStr++;
3175 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3176 if (HasIndex[Idx]) HasRepeated = true;
3177 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003178 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003179 }
Chris Lattner7e152db2007-08-02 22:33:49 +00003180 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00003181
Mike Stump4e1f26a2009-02-19 03:04:26 +00003182 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00003183 // We didn't get to the end of the string. This means the component names
3184 // didn't come from the same set *or* we encountered an illegal name.
John McCall4bc41ae2010-11-18 19:01:18 +00003185 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramere8394df2010-08-11 14:47:12 +00003186 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00003187 return QualType();
3188 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003189
Nate Begemanbb70bf62009-01-18 01:47:54 +00003190 // Ensure no component accessor exceeds the width of the vector type it
3191 // operates on.
3192 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003193 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003194
3195 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00003196 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00003197
3198 while (*compStr) {
3199 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall4bc41ae2010-11-18 19:01:18 +00003200 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begemanbb70bf62009-01-18 01:47:54 +00003201 << baseType << SourceRange(CompLoc);
3202 return QualType();
3203 }
3204 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00003205 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003206
Steve Narofff8fd09e2007-07-27 22:15:19 +00003207 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003208 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00003209 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00003210 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00003211 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00003212 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00003213 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003214 if (HexSwizzle)
3215 CompSize--;
3216
Steve Narofff8fd09e2007-07-27 22:15:19 +00003217 if (CompSize == 1)
3218 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003219
John McCall4bc41ae2010-11-18 19:01:18 +00003220 if (HasRepeated) VK = VK_RValue;
3221
3222 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003223 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00003224 // diagostics look bad. We want extended vector types to appear built-in.
John McCall4bc41ae2010-11-18 19:01:18 +00003225 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3226 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3227 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00003228 }
3229 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00003230}
3231
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003232static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00003233 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003234 const Selector &Sel,
3235 ASTContext &Context) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003236 if (Member)
3237 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3238 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003239 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003240 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00003241
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003242 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3243 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003244 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3245 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003246 return D;
3247 }
3248 return 0;
3249}
3250
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003251static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3252 IdentifierInfo *Member,
3253 const Selector &Sel,
3254 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003255 // Check protocols on qualified interfaces.
3256 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00003257 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003258 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003259 if (Member)
3260 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3261 GDecl = PD;
3262 break;
3263 }
3264 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003265 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003266 GDecl = OMD;
3267 break;
3268 }
3269 }
3270 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00003271 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003272 E = QIdTy->qual_end(); I != E; ++I) {
3273 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003274 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3275 Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003276 if (GDecl)
3277 return GDecl;
3278 }
3279 }
3280 return GDecl;
3281}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00003282
John McCalldadc5752010-08-24 06:29:42 +00003283ExprResult
John McCallb268a282010-08-23 23:25:46 +00003284Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCall2d74de92009-12-01 22:10:20 +00003285 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003286 const CXXScopeSpec &SS,
3287 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003288 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003289 const TemplateArgumentListInfo *TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00003290 // Even in dependent contexts, try to diagnose base expressions with
3291 // obviously wrong types, e.g.:
3292 //
3293 // T* t;
3294 // t.f;
3295 //
3296 // In Obj-C++, however, the above expression is valid, since it could be
3297 // accessing the 'f' property if T is an Obj-C interface. The extra check
3298 // allows this, while still reporting an error if T is a struct pointer.
3299 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00003300 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00003301 if (PT && (!getLangOptions().ObjC1 ||
3302 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00003303 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003304 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00003305 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00003306 return ExprError();
3307 }
3308 }
3309
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003310 assert(BaseType->isDependentType() ||
3311 NameInfo.getName().isDependentName() ||
Douglas Gregor41f90302010-04-12 20:54:26 +00003312 isDependentScopeSpecifier(SS));
John McCall10eae182009-11-30 22:42:35 +00003313
3314 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3315 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00003316 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003317 IsArrow, OpLoc,
Douglas Gregore16af532011-02-28 18:50:33 +00003318 SS.getWithLocInContext(Context),
John McCall10eae182009-11-30 22:42:35 +00003319 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003320 NameInfo, TemplateArgs));
John McCall10eae182009-11-30 22:42:35 +00003321}
3322
3323/// We know that the given qualified member reference points only to
3324/// declarations which do not belong to the static type of the base
3325/// expression. Diagnose the problem.
3326static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3327 Expr *BaseExpr,
3328 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003329 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00003330 NamedDecl *rep,
3331 const DeclarationNameInfo &nameInfo) {
John McCallcd4b4772009-12-02 03:53:29 +00003332 // If this is an implicit member access, use a different set of
3333 // diagnostics.
3334 if (!BaseExpr)
John McCallf3a88602011-02-03 08:15:49 +00003335 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall10eae182009-11-30 22:42:35 +00003336
John McCallf3a88602011-02-03 08:15:49 +00003337 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3338 << SS.getRange() << rep << BaseType;
John McCall10eae182009-11-30 22:42:35 +00003339}
3340
3341// Check whether the declarations we found through a nested-name
3342// specifier in a member expression are actually members of the base
3343// type. The restriction here is:
3344//
3345// C++ [expr.ref]p2:
3346// ... In these cases, the id-expression shall name a
3347// member of the class or of one of its base classes.
3348//
3349// So it's perfectly legitimate for the nested-name specifier to name
3350// an unrelated class, and for us to find an overload set including
3351// decls from classes which are not superclasses, as long as the decl
3352// we actually pick through overload resolution is from a superclass.
3353bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3354 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003355 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003356 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00003357 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3358 if (!BaseRT) {
3359 // We can't check this yet because the base type is still
3360 // dependent.
3361 assert(BaseType->isDependentType());
3362 return false;
3363 }
3364 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00003365
3366 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00003367 // If this is an implicit member reference and we find a
3368 // non-instance member, it's not an error.
John McCalla8ae2222010-04-06 21:38:20 +00003369 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCall2d74de92009-12-01 22:10:20 +00003370 return false;
John McCall10eae182009-11-30 22:42:35 +00003371
John McCall2d74de92009-12-01 22:10:20 +00003372 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman75300492010-07-27 20:51:02 +00003373 DeclContext *DC = (*I)->getDeclContext();
3374 while (DC->isTransparentContext())
3375 DC = DC->getParent();
John McCall2d74de92009-12-01 22:10:20 +00003376
Douglas Gregora9c3e822010-07-28 22:27:52 +00003377 if (!DC->isRecord())
3378 continue;
3379
John McCall2d74de92009-12-01 22:10:20 +00003380 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman75300492010-07-27 20:51:02 +00003381 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCall2d74de92009-12-01 22:10:20 +00003382
3383 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3384 return false;
3385 }
3386
John McCallf3a88602011-02-03 08:15:49 +00003387 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3388 R.getRepresentativeDecl(),
3389 R.getLookupNameInfo());
John McCall2d74de92009-12-01 22:10:20 +00003390 return true;
3391}
3392
3393static bool
3394LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3395 SourceRange BaseRange, const RecordType *RTy,
John McCalle9cccd82010-06-16 08:42:20 +00003396 SourceLocation OpLoc, CXXScopeSpec &SS,
3397 bool HasTemplateArgs) {
John McCall2d74de92009-12-01 22:10:20 +00003398 RecordDecl *RDecl = RTy->getDecl();
3399 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor89336232010-03-29 23:34:08 +00003400 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCall2d74de92009-12-01 22:10:20 +00003401 << BaseRange))
3402 return true;
3403
John McCalle9cccd82010-06-16 08:42:20 +00003404 if (HasTemplateArgs) {
3405 // LookupTemplateName doesn't expect these both to exist simultaneously.
3406 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3407
3408 bool MOUS;
3409 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3410 return false;
3411 }
3412
John McCall2d74de92009-12-01 22:10:20 +00003413 DeclContext *DC = RDecl;
3414 if (SS.isSet()) {
3415 // If the member name was a qualified-id, look into the
3416 // nested-name-specifier.
3417 DC = SemaRef.computeDeclContext(SS, false);
3418
John McCall0b66eb32010-05-01 00:40:08 +00003419 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCallcd4b4772009-12-02 03:53:29 +00003420 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3421 << SS.getRange() << DC;
3422 return true;
3423 }
3424
John McCall2d74de92009-12-01 22:10:20 +00003425 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003426
John McCall2d74de92009-12-01 22:10:20 +00003427 if (!isa<TypeDecl>(DC)) {
3428 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3429 << DC << SS.getRange();
3430 return true;
John McCall10eae182009-11-30 22:42:35 +00003431 }
3432 }
3433
John McCall2d74de92009-12-01 22:10:20 +00003434 // The record definition is complete, now look up the member.
3435 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00003436
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003437 if (!R.empty())
3438 return false;
3439
3440 // We didn't find anything with the given name, so try to correct
3441 // for typos.
3442 DeclarationName Name = R.getLookupName();
Alexis Huntc46382e2010-04-28 23:02:27 +00003443 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003444 !R.empty() &&
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003445 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3446 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3447 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003448 << FixItHint::CreateReplacement(R.getNameLoc(),
3449 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003450 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3451 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3452 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003453 return false;
3454 } else {
3455 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003456 R.setLookupName(Name);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003457 }
3458
John McCall10eae182009-11-30 22:42:35 +00003459 return false;
3460}
3461
John McCalldadc5752010-08-24 06:29:42 +00003462ExprResult
John McCallb268a282010-08-23 23:25:46 +00003463Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00003464 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003465 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003466 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003467 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003468 const TemplateArgumentListInfo *TemplateArgs) {
John McCallcd4b4772009-12-02 03:53:29 +00003469 if (BaseType->isDependentType() ||
3470 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallb268a282010-08-23 23:25:46 +00003471 return ActOnDependentMemberExpr(Base, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003472 IsArrow, OpLoc,
3473 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003474 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003475
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003476 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00003477
John McCall2d74de92009-12-01 22:10:20 +00003478 // Implicit member accesses.
3479 if (!Base) {
3480 QualType RecordTy = BaseType;
3481 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3482 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3483 RecordTy->getAs<RecordType>(),
John McCalle9cccd82010-06-16 08:42:20 +00003484 OpLoc, SS, TemplateArgs != 0))
John McCall2d74de92009-12-01 22:10:20 +00003485 return ExprError();
3486
3487 // Explicit member accesses.
3488 } else {
John McCalldadc5752010-08-24 06:29:42 +00003489 ExprResult Result =
John McCall2d74de92009-12-01 22:10:20 +00003490 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCall48871652010-08-21 09:40:31 +00003491 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCall2d74de92009-12-01 22:10:20 +00003492
3493 if (Result.isInvalid()) {
3494 Owned(Base);
3495 return ExprError();
3496 }
3497
3498 if (Result.get())
3499 return move(Result);
Sebastian Redlfa1f70f2010-05-07 09:25:11 +00003500
3501 // LookupMemberExpr can modify Base, and thus change BaseType
3502 BaseType = Base->getType();
John McCall10eae182009-11-30 22:42:35 +00003503 }
3504
John McCallb268a282010-08-23 23:25:46 +00003505 return BuildMemberReferenceExpr(Base, BaseType,
John McCall38836f02010-01-15 08:34:02 +00003506 OpLoc, IsArrow, SS, FirstQualifierInScope,
3507 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003508}
3509
John McCalldadc5752010-08-24 06:29:42 +00003510ExprResult
John McCallb268a282010-08-23 23:25:46 +00003511Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCall2d74de92009-12-01 22:10:20 +00003512 SourceLocation OpLoc, bool IsArrow,
3513 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00003514 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00003515 LookupResult &R,
Douglas Gregorb139cd52010-05-01 20:49:11 +00003516 const TemplateArgumentListInfo *TemplateArgs,
3517 bool SuppressQualifierCheck) {
John McCall2d74de92009-12-01 22:10:20 +00003518 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00003519 if (IsArrow) {
3520 assert(BaseType->isPointerType());
3521 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3522 }
John McCalla8ae2222010-04-06 21:38:20 +00003523 R.setBaseObjectType(BaseType);
John McCall10eae182009-11-30 22:42:35 +00003524
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003525 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3526 DeclarationName MemberName = MemberNameInfo.getName();
3527 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall10eae182009-11-30 22:42:35 +00003528
3529 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00003530 return ExprError();
3531
John McCall10eae182009-11-30 22:42:35 +00003532 if (R.empty()) {
3533 // Rederive where we looked up.
3534 DeclContext *DC = (SS.isSet()
3535 ? computeDeclContext(SS, false)
3536 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00003537
John McCall10eae182009-11-30 22:42:35 +00003538 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00003539 << MemberName << DC
3540 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00003541 return ExprError();
3542 }
3543
John McCall38836f02010-01-15 08:34:02 +00003544 // Diagnose lookups that find only declarations from a non-base
3545 // type. This is possible for either qualified lookups (which may
3546 // have been qualified with an unrelated type) or implicit member
3547 // expressions (which were found with unqualified lookup and thus
3548 // may have come from an enclosing scope). Note that it's okay for
3549 // lookup to find declarations from a non-base type as long as those
3550 // aren't the ones picked by overload resolution.
3551 if ((SS.isSet() || !BaseExpr ||
3552 (isa<CXXThisExpr>(BaseExpr) &&
3553 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00003554 !SuppressQualifierCheck &&
John McCall38836f02010-01-15 08:34:02 +00003555 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00003556 return ExprError();
3557
3558 // Construct an unresolved result if we in fact got an unresolved
3559 // result.
3560 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall58cc69d2010-01-27 01:50:18 +00003561 // Suppress any lookup-related diagnostics; we'll do these when we
3562 // pick a member.
3563 R.suppressDiagnostics();
3564
John McCall10eae182009-11-30 22:42:35 +00003565 UnresolvedMemberExpr *MemExpr
Douglas Gregora6e053e2010-12-15 01:34:56 +00003566 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00003567 BaseExpr, BaseExprType,
3568 IsArrow, OpLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00003569 SS.getWithLocInContext(Context),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003570 MemberNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003571 TemplateArgs, R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00003572
3573 return Owned(MemExpr);
3574 }
3575
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003576 assert(R.isSingleResult());
John McCalla8ae2222010-04-06 21:38:20 +00003577 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall10eae182009-11-30 22:42:35 +00003578 NamedDecl *MemberDecl = R.getFoundDecl();
3579
3580 // FIXME: diagnose the presence of template arguments now.
3581
3582 // If the decl being referenced had an error, return an error for this
3583 // sub-expr without emitting another error, in order to avoid cascading
3584 // error cases.
3585 if (MemberDecl->isInvalidDecl())
3586 return ExprError();
3587
John McCall2d74de92009-12-01 22:10:20 +00003588 // Handle the implicit-member-access case.
3589 if (!BaseExpr) {
3590 // If this is not an instance member, convert to a non-member access.
John McCalla8ae2222010-04-06 21:38:20 +00003591 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003592 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCall2d74de92009-12-01 22:10:20 +00003593
Douglas Gregorb15af892010-01-07 23:12:05 +00003594 SourceLocation Loc = R.getNameLoc();
3595 if (SS.getRange().isValid())
3596 Loc = SS.getRange().getBegin();
3597 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003598 }
3599
John McCall10eae182009-11-30 22:42:35 +00003600 bool ShouldCheckUse = true;
3601 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3602 // Don't diagnose the use of a virtual member function unless it's
3603 // explicitly qualified.
3604 if (MD->isVirtual() && !SS.isSet())
3605 ShouldCheckUse = false;
3606 }
3607
3608 // Check the use of this member.
3609 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3610 Owned(BaseExpr);
3611 return ExprError();
3612 }
3613
John McCall34376a62010-12-04 03:47:34 +00003614 // Perform a property load on the base regardless of whether we
3615 // actually need it for the declaration.
3616 if (BaseExpr->getObjectKind() == OK_ObjCProperty)
3617 ConvertPropertyForRValue(BaseExpr);
3618
John McCallfeb624a2010-11-23 20:48:44 +00003619 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3620 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3621 SS, FD, FoundDecl, MemberNameInfo);
John McCall10eae182009-11-30 22:42:35 +00003622
Francois Pichet783dd6e2010-11-21 06:08:52 +00003623 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3624 // We may have found a field within an anonymous union or struct
3625 // (C++ [class.union]).
John McCallf3a88602011-02-03 08:15:49 +00003626 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCall34376a62010-12-04 03:47:34 +00003627 BaseExpr, OpLoc);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003628
John McCall10eae182009-11-30 22:42:35 +00003629 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3630 MarkDeclarationReferenced(MemberLoc, Var);
3631 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003632 Var, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003633 Var->getType().getNonReferenceType(),
John McCall4bc41ae2010-11-18 19:01:18 +00003634 VK_LValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003635 }
3636
John McCall7decc9e2010-11-18 06:31:45 +00003637 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall10eae182009-11-30 22:42:35 +00003638 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3639 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003640 MemberFn, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003641 MemberFn->getType(),
3642 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3643 OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003644 }
John McCall7decc9e2010-11-18 06:31:45 +00003645 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall10eae182009-11-30 22:42:35 +00003646
3647 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3648 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3649 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003650 Enum, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003651 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003652 }
3653
3654 Owned(BaseExpr);
3655
Douglas Gregor861eb802010-04-25 20:55:08 +00003656 // We found something that we didn't expect. Complain.
John McCall10eae182009-11-30 22:42:35 +00003657 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003658 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregor861eb802010-04-25 20:55:08 +00003659 << MemberName << BaseType << int(IsArrow);
3660 else
3661 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3662 << MemberName << BaseType << int(IsArrow);
John McCall10eae182009-11-30 22:42:35 +00003663
Douglas Gregor861eb802010-04-25 20:55:08 +00003664 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3665 << MemberName;
Douglas Gregor516d6722010-04-25 21:15:30 +00003666 R.suppressDiagnostics();
Douglas Gregor861eb802010-04-25 20:55:08 +00003667 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00003668}
3669
John McCall68fc88ec2010-12-15 16:46:44 +00003670/// Given that normal member access failed on the given expression,
3671/// and given that the expression's type involves builtin-id or
3672/// builtin-Class, decide whether substituting in the redefinition
3673/// types would be profitable. The redefinition type is whatever
3674/// this translation unit tried to typedef to id/Class; we store
3675/// it to the side and then re-use it in places like this.
3676static bool ShouldTryAgainWithRedefinitionType(Sema &S, Expr *&base) {
3677 const ObjCObjectPointerType *opty
3678 = base->getType()->getAs<ObjCObjectPointerType>();
3679 if (!opty) return false;
3680
3681 const ObjCObjectType *ty = opty->getObjectType();
3682
3683 QualType redef;
3684 if (ty->isObjCId()) {
3685 redef = S.Context.ObjCIdRedefinitionType;
3686 } else if (ty->isObjCClass()) {
3687 redef = S.Context.ObjCClassRedefinitionType;
3688 } else {
3689 return false;
3690 }
3691
3692 // Do the substitution as long as the redefinition type isn't just a
3693 // possibly-qualified pointer to builtin-id or builtin-Class again.
3694 opty = redef->getAs<ObjCObjectPointerType>();
3695 if (opty && !opty->getObjectType()->getInterface() != 0)
3696 return false;
3697
3698 S.ImpCastExprToType(base, redef, CK_BitCast);
3699 return true;
3700}
3701
John McCall10eae182009-11-30 22:42:35 +00003702/// Look up the given member of the given non-type-dependent
3703/// expression. This can return in one of two ways:
3704/// * If it returns a sentinel null-but-valid result, the caller will
3705/// assume that lookup was performed and the results written into
3706/// the provided structure. It will take over from there.
3707/// * Otherwise, the returned expression will be produced in place of
3708/// an ordinary member expression.
3709///
3710/// The ObjCImpDecl bit is a gross hack that will need to be properly
3711/// fixed for ObjC++.
John McCalldadc5752010-08-24 06:29:42 +00003712ExprResult
John McCall10eae182009-11-30 22:42:35 +00003713Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00003714 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003715 CXXScopeSpec &SS,
John McCall48871652010-08-21 09:40:31 +00003716 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003717 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00003718
Steve Naroffeaaae462007-12-16 21:42:28 +00003719 // Perform default conversions.
3720 DefaultFunctionArrayConversion(BaseExpr);
John McCall15317a22010-12-15 04:42:30 +00003721 if (IsArrow) DefaultLvalueConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003722
Steve Naroff185616f2007-07-26 03:11:44 +00003723 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00003724 assert(!BaseType->isDependentType());
3725
3726 DeclarationName MemberName = R.getLookupName();
3727 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00003728
John McCall68fc88ec2010-12-15 16:46:44 +00003729 // For later type-checking purposes, turn arrow accesses into dot
3730 // accesses. The only access type we support that doesn't follow
3731 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
3732 // and those never use arrows, so this is unaffected.
3733 if (IsArrow) {
3734 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3735 BaseType = Ptr->getPointeeType();
3736 else if (const ObjCObjectPointerType *Ptr
3737 = BaseType->getAs<ObjCObjectPointerType>())
3738 BaseType = Ptr->getPointeeType();
3739 else if (BaseType->isRecordType()) {
3740 // Recover from arrow accesses to records, e.g.:
3741 // struct MyRecord foo;
3742 // foo->bar
3743 // This is actually well-formed in C++ if MyRecord has an
3744 // overloaded operator->, but that should have been dealt with
3745 // by now.
3746 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3747 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3748 << FixItHint::CreateReplacement(OpLoc, ".");
3749 IsArrow = false;
3750 } else {
3751 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3752 << BaseType << BaseExpr->getSourceRange();
3753 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00003754 }
3755 }
3756
John McCall68fc88ec2010-12-15 16:46:44 +00003757 // Handle field access to simple records.
3758 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
3759 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
3760 RTy, OpLoc, SS, HasTemplateArgs))
3761 return ExprError();
3762
3763 // Returning valid-but-null is how we indicate to the caller that
3764 // the lookup result was filled in.
3765 return Owned((Expr*) 0);
David Chisnall9f57c292009-08-17 16:35:33 +00003766 }
John McCall10eae182009-11-30 22:42:35 +00003767
John McCall68fc88ec2010-12-15 16:46:44 +00003768 // Handle ivar access to Objective-C objects.
3769 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003770 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall68fc88ec2010-12-15 16:46:44 +00003771
3772 // There are three cases for the base type:
3773 // - builtin id (qualified or unqualified)
3774 // - builtin Class (qualified or unqualified)
3775 // - an interface
3776 ObjCInterfaceDecl *IDecl = OTy->getInterface();
3777 if (!IDecl) {
3778 // There's an implicit 'isa' ivar on all objects.
3779 // But we only actually find it this way on objects of type 'id',
3780 // apparently.
3781 if (OTy->isObjCId() && Member->isStr("isa"))
3782 return Owned(new (Context) ObjCIsaExpr(BaseExpr, IsArrow, MemberLoc,
3783 Context.getObjCClassType()));
3784
3785 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3786 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3787 ObjCImpDecl, HasTemplateArgs);
3788 goto fail;
3789 }
3790
3791 ObjCInterfaceDecl *ClassDeclared;
3792 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
3793
3794 if (!IV) {
3795 // Attempt to correct for typos in ivar names.
3796 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3797 LookupMemberName);
3798 if (CorrectTypo(Res, 0, 0, IDecl, false,
3799 IsArrow ? CTC_ObjCIvarLookup
3800 : CTC_ObjCPropertyLookup) &&
3801 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
3802 Diag(R.getNameLoc(),
3803 diag::err_typecheck_member_reference_ivar_suggest)
3804 << IDecl->getDeclName() << MemberName << IV->getDeclName()
3805 << FixItHint::CreateReplacement(R.getNameLoc(),
3806 IV->getNameAsString());
3807 Diag(IV->getLocation(), diag::note_previous_decl)
3808 << IV->getDeclName();
3809 } else {
3810 Res.clear();
3811 Res.setLookupName(Member);
3812
3813 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
3814 << IDecl->getDeclName() << MemberName
3815 << BaseExpr->getSourceRange();
3816 return ExprError();
3817 }
3818 }
3819
3820 // If the decl being referenced had an error, return an error for this
3821 // sub-expr without emitting another error, in order to avoid cascading
3822 // error cases.
3823 if (IV->isInvalidDecl())
3824 return ExprError();
3825
3826 // Check whether we can reference this field.
3827 if (DiagnoseUseOfDecl(IV, MemberLoc))
3828 return ExprError();
3829 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3830 IV->getAccessControl() != ObjCIvarDecl::Package) {
3831 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3832 if (ObjCMethodDecl *MD = getCurMethodDecl())
3833 ClassOfMethodDecl = MD->getClassInterface();
3834 else if (ObjCImpDecl && getCurFunctionDecl()) {
3835 // Case of a c-function declared inside an objc implementation.
3836 // FIXME: For a c-style function nested inside an objc implementation
3837 // class, there is no implementation context available, so we pass
3838 // down the context as argument to this routine. Ideally, this context
3839 // need be passed down in the AST node and somehow calculated from the
3840 // AST for a function decl.
3841 if (ObjCImplementationDecl *IMPD =
3842 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
3843 ClassOfMethodDecl = IMPD->getClassInterface();
3844 else if (ObjCCategoryImplDecl* CatImplClass =
3845 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
3846 ClassOfMethodDecl = CatImplClass->getClassInterface();
3847 }
3848
3849 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3850 if (ClassDeclared != IDecl ||
3851 ClassOfMethodDecl != ClassDeclared)
3852 Diag(MemberLoc, diag::error_private_ivar_access)
3853 << IV->getDeclName();
3854 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3855 // @protected
3856 Diag(MemberLoc, diag::error_protected_ivar_access)
3857 << IV->getDeclName();
3858 }
3859
3860 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3861 MemberLoc, BaseExpr,
3862 IsArrow));
3863 }
3864
3865 // Objective-C property access.
3866 const ObjCObjectPointerType *OPT;
3867 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
3868 // This actually uses the base as an r-value.
3869 DefaultLvalueConversion(BaseExpr);
3870 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr->getType()));
3871
3872 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3873
3874 const ObjCObjectType *OT = OPT->getObjectType();
3875
3876 // id, with and without qualifiers.
3877 if (OT->isObjCId()) {
3878 // Check protocols on qualified interfaces.
3879 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3880 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
3881 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3882 // Check the use of this declaration
3883 if (DiagnoseUseOfDecl(PD, MemberLoc))
3884 return ExprError();
3885
3886 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3887 VK_LValue,
3888 OK_ObjCProperty,
3889 MemberLoc,
3890 BaseExpr));
3891 }
3892
3893 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3894 // Check the use of this method.
3895 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3896 return ExprError();
3897 Selector SetterSel =
3898 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3899 PP.getSelectorTable(), Member);
3900 ObjCMethodDecl *SMD = 0;
3901 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
3902 SetterSel, Context))
3903 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3904 QualType PType = OMD->getSendResultType();
3905
3906 ExprValueKind VK = VK_LValue;
3907 if (!getLangOptions().CPlusPlus &&
3908 IsCForbiddenLValueType(Context, PType))
3909 VK = VK_RValue;
3910 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3911
3912 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
3913 VK, OK,
3914 MemberLoc, BaseExpr));
3915 }
3916 }
Fariborz Jahanianb03a4c22011-03-15 17:27:48 +00003917 // Use of id.member can only be for a property reference. Do not
3918 // use the 'id' redefinition in this case.
3919 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
John McCall68fc88ec2010-12-15 16:46:44 +00003920 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3921 ObjCImpDecl, HasTemplateArgs);
3922
3923 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3924 << MemberName << BaseType);
3925 }
3926
3927 // 'Class', unqualified only.
3928 if (OT->isObjCClass()) {
3929 // Only works in a method declaration (??!).
3930 ObjCMethodDecl *MD = getCurMethodDecl();
3931 if (!MD) {
3932 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3933 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3934 ObjCImpDecl, HasTemplateArgs);
3935
3936 goto fail;
3937 }
3938
3939 // Also must look for a getter name which uses property syntax.
3940 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003941 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3942 ObjCMethodDecl *Getter;
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003943 if ((Getter = IFace->lookupClassMethod(Sel))) {
3944 // Check the use of this method.
3945 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3946 return ExprError();
John McCall68fc88ec2010-12-15 16:46:44 +00003947 } else
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00003948 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003949 // If we found a getter then this may be a valid dot-reference, we
3950 // will look for the matching setter, in case it is needed.
3951 Selector SetterSel =
John McCall68fc88ec2010-12-15 16:46:44 +00003952 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3953 PP.getSelectorTable(), Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003954 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3955 if (!Setter) {
3956 // If this reference is in an @implementation, also check for 'private'
3957 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00003958 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003959 }
3960 // Look through local category implementations associated with the class.
3961 if (!Setter)
3962 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003963
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003964 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3965 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003966
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003967 if (Getter || Setter) {
3968 QualType PType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003969
John McCall4bc41ae2010-11-18 19:01:18 +00003970 ExprValueKind VK = VK_LValue;
3971 if (Getter) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00003972 PType = Getter->getSendResultType();
John McCall4bc41ae2010-11-18 19:01:18 +00003973 if (!getLangOptions().CPlusPlus &&
3974 IsCForbiddenLValueType(Context, PType))
3975 VK = VK_RValue;
3976 } else {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003977 // Get the expression type from Setter's incoming parameter.
3978 PType = (*(Setter->param_end() -1))->getType();
John McCall4bc41ae2010-11-18 19:01:18 +00003979 }
3980 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3981
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003982 // FIXME: we must check that the setter has property type.
John McCallb7bd14f2010-12-02 01:19:52 +00003983 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
3984 PType, VK, OK,
3985 MemberLoc, BaseExpr));
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003986 }
John McCall68fc88ec2010-12-15 16:46:44 +00003987
3988 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3989 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3990 ObjCImpDecl, HasTemplateArgs);
3991
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003992 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall68fc88ec2010-12-15 16:46:44 +00003993 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003994 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003995
John McCall68fc88ec2010-12-15 16:46:44 +00003996 // Normal property access.
3997 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc,
3998 SourceLocation(), QualType(), false);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003999 }
Alexis Huntc46382e2010-04-28 23:02:27 +00004000
Chris Lattnerb63a7452008-07-21 04:28:12 +00004001 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00004002 if (BaseType->isExtVectorType()) {
John McCall15317a22010-12-15 04:42:30 +00004003 // FIXME: this expr should store IsArrow.
Anders Carlssonf571c112009-08-26 18:25:21 +00004004 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall15317a22010-12-15 04:42:30 +00004005 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr->getValueKind());
John McCall4bc41ae2010-11-18 19:01:18 +00004006 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
4007 Member, MemberLoc);
Chris Lattnerb63a7452008-07-21 04:28:12 +00004008 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004009 return ExprError();
John McCall4bc41ae2010-11-18 19:01:18 +00004010
4011 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr,
4012 *Member, MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00004013 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004014
John McCall68fc88ec2010-12-15 16:46:44 +00004015 // Adjust builtin-sel to the appropriate redefinition type if that's
4016 // not just a pointer to builtin-sel again.
4017 if (IsArrow &&
4018 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
4019 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
4020 ImpCastExprToType(BaseExpr, Context.ObjCSelRedefinitionType, CK_BitCast);
4021 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4022 ObjCImpDecl, HasTemplateArgs);
4023 }
4024
4025 // Failure cases.
4026 fail:
4027
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004028 // Recover from dot accesses to pointers, e.g.:
4029 // type *foo;
4030 // foo.bar
4031 // This is actually well-formed in two cases:
4032 // - 'type' is an Objective C type
4033 // - 'bar' is a pseudo-destructor name which happens to refer to
4034 // the appropriate pointer type
John McCall68fc88ec2010-12-15 16:46:44 +00004035 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004036 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
4037 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
John McCall68fc88ec2010-12-15 16:46:44 +00004038 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004039 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
4040 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall68fc88ec2010-12-15 16:46:44 +00004041
4042 // Recurse as an -> access.
4043 IsArrow = true;
4044 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4045 ObjCImpDecl, HasTemplateArgs);
4046 }
John McCall68fc88ec2010-12-15 16:46:44 +00004047 }
4048
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004049 // If the user is trying to apply -> or . to a function name, it's probably
4050 // because they forgot parentheses to call that function.
4051 bool TryCall = false;
4052 bool Overloaded = false;
4053 UnresolvedSet<8> AllOverloads;
4054 if (const OverloadExpr *Overloads = dyn_cast<OverloadExpr>(BaseExpr)) {
4055 AllOverloads.append(Overloads->decls_begin(), Overloads->decls_end());
4056 TryCall = true;
4057 Overloaded = true;
4058 } else if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(BaseExpr)) {
4059 if (FunctionDecl* Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
4060 AllOverloads.addDecl(Fun);
4061 TryCall = true;
4062 }
4063 }
John McCall68fc88ec2010-12-15 16:46:44 +00004064
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004065 if (TryCall) {
4066 // Plunder the overload set for something that would make the member
4067 // expression valid.
4068 UnresolvedSet<4> ViableOverloads;
4069 bool HasViableZeroArgOverload = false;
4070 for (OverloadExpr::decls_iterator it = AllOverloads.begin(),
4071 DeclsEnd = AllOverloads.end(); it != DeclsEnd; ++it) {
Matt Beaumont-Gayf8bb45f2011-03-05 02:42:30 +00004072 // Our overload set may include TemplateDecls, which we'll ignore for the
4073 // purposes of determining whether we can issue a '()' fixit.
4074 if (const FunctionDecl *OverloadDecl = dyn_cast<FunctionDecl>(*it)) {
4075 QualType ResultTy = OverloadDecl->getResultType();
4076 if ((!IsArrow && ResultTy->isRecordType()) ||
4077 (IsArrow && ResultTy->isPointerType() &&
4078 ResultTy->getPointeeType()->isRecordType())) {
4079 ViableOverloads.addDecl(*it);
4080 if (OverloadDecl->getMinRequiredArguments() == 0) {
4081 HasViableZeroArgOverload = true;
4082 }
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004083 }
John McCall68fc88ec2010-12-15 16:46:44 +00004084 }
4085 }
4086
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004087 if (!HasViableZeroArgOverload || ViableOverloads.size() != 1) {
4088 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gayf8bb45f2011-03-05 02:42:30 +00004089 << (AllOverloads.size() > 1) << 0
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004090 << BaseExpr->getSourceRange();
4091 int ViableOverloadCount = ViableOverloads.size();
4092 int I;
4093 for (I = 0; I < ViableOverloadCount; ++I) {
4094 // FIXME: Magic number for max shown overloads stolen from
4095 // OverloadCandidateSet::NoteCandidates.
4096 if (I >= 4 && Diags.getShowOverloads() == Diagnostic::Ovl_Best) {
4097 break;
4098 }
4099 Diag(ViableOverloads[I].getDecl()->getSourceRange().getBegin(),
4100 diag::note_member_ref_possible_intended_overload);
4101 }
4102 if (I != ViableOverloadCount) {
4103 Diag(BaseExpr->getExprLoc(), diag::note_ovl_too_many_candidates)
4104 << int(ViableOverloadCount - I);
4105 }
4106 return ExprError();
4107 }
4108 } else {
4109 // We don't have an expression that's convenient to get a Decl from, but we
4110 // can at least check if the type is "function of 0 arguments which returns
4111 // an acceptable type".
4112 const FunctionType *Fun = NULL;
4113 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4114 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
4115 TryCall = true;
4116 }
4117 } else if ((Fun = BaseType->getAs<FunctionType>())) {
4118 TryCall = true;
4119 }
John McCall68fc88ec2010-12-15 16:46:44 +00004120
4121 if (TryCall) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004122 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
4123 if (FPT->getNumArgs() == 0) {
4124 QualType ResultTy = Fun->getResultType();
4125 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
4126 (IsArrow && ResultTy->isPointerType() &&
4127 ResultTy->getPointeeType()->isRecordType());
4128 }
Matt Beaumont-Gay956fc1c2011-02-17 02:54:17 +00004129 }
John McCall68fc88ec2010-12-15 16:46:44 +00004130 }
4131 }
4132
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004133 if (TryCall) {
4134 // At this point, we know BaseExpr looks like it's potentially callable with
4135 // 0 arguments, and that it returns something of a reasonable type, so we
4136 // can emit a fixit and carry on pretending that BaseExpr was actually a
4137 // CallExpr.
4138 SourceLocation ParenInsertionLoc =
4139 PP.getLocForEndOfToken(BaseExpr->getLocEnd());
4140 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
4141 << int(Overloaded) << 1
4142 << BaseExpr->getSourceRange()
4143 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
4144 ExprResult NewBase = ActOnCallExpr(0, BaseExpr, ParenInsertionLoc,
4145 MultiExprArg(*this, 0, 0),
4146 ParenInsertionLoc);
4147 if (NewBase.isInvalid())
4148 return ExprError();
4149 BaseExpr = NewBase.takeAs<Expr>();
4150 DefaultFunctionArrayConversion(BaseExpr);
4151 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4152 ObjCImpDecl, HasTemplateArgs);
4153 }
4154
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004155 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
4156 << BaseType << BaseExpr->getSourceRange();
4157
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004158 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00004159}
4160
John McCall10eae182009-11-30 22:42:35 +00004161/// The main callback when the parser finds something like
4162/// expression . [nested-name-specifier] identifier
4163/// expression -> [nested-name-specifier] identifier
4164/// where 'identifier' encompasses a fairly broad spectrum of
4165/// possibilities, including destructor and operator references.
4166///
4167/// \param OpKind either tok::arrow or tok::period
4168/// \param HasTrailingLParen whether the next token is '(', which
4169/// is used to diagnose mis-uses of special members that can
4170/// only be called
4171/// \param ObjCImpDecl the current ObjC @implementation decl;
4172/// this is an ugly hack around the fact that ObjC @implementations
4173/// aren't properly put in the context chain
John McCalldadc5752010-08-24 06:29:42 +00004174ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall15317a22010-12-15 04:42:30 +00004175 SourceLocation OpLoc,
4176 tok::TokenKind OpKind,
4177 CXXScopeSpec &SS,
4178 UnqualifiedId &Id,
4179 Decl *ObjCImpDecl,
4180 bool HasTrailingLParen) {
John McCall10eae182009-11-30 22:42:35 +00004181 if (SS.isSet() && SS.isInvalid())
4182 return ExprError();
4183
Francois Pichet64225792011-01-18 05:04:39 +00004184 // Warn about the explicit constructor calls Microsoft extension.
4185 if (getLangOptions().Microsoft &&
4186 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4187 Diag(Id.getSourceRange().getBegin(),
4188 diag::ext_ms_explicit_constructor_call);
4189
John McCall10eae182009-11-30 22:42:35 +00004190 TemplateArgumentListInfo TemplateArgsBuffer;
4191
4192 // Decompose the name into its component parts.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004193 DeclarationNameInfo NameInfo;
John McCall10eae182009-11-30 22:42:35 +00004194 const TemplateArgumentListInfo *TemplateArgs;
4195 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004196 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004197
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004198 DeclarationName Name = NameInfo.getName();
John McCall10eae182009-11-30 22:42:35 +00004199 bool IsArrow = (OpKind == tok::arrow);
4200
4201 NamedDecl *FirstQualifierInScope
4202 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4203 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4204
4205 // This is a postfix expression, so get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004206 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00004207 if (Result.isInvalid()) return ExprError();
4208 Base = Result.take();
John McCall10eae182009-11-30 22:42:35 +00004209
Douglas Gregor41f90302010-04-12 20:54:26 +00004210 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4211 isDependentScopeSpecifier(SS)) {
John McCallb268a282010-08-23 23:25:46 +00004212 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00004213 IsArrow, OpLoc,
4214 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004215 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004216 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004217 LookupResult R(*this, NameInfo, LookupMemberName);
John McCalle9cccd82010-06-16 08:42:20 +00004218 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
4219 SS, ObjCImpDecl, TemplateArgs != 0);
Alexis Huntc46382e2010-04-28 23:02:27 +00004220
John McCalle9cccd82010-06-16 08:42:20 +00004221 if (Result.isInvalid()) {
4222 Owned(Base);
4223 return ExprError();
4224 }
John McCall10eae182009-11-30 22:42:35 +00004225
John McCalle9cccd82010-06-16 08:42:20 +00004226 if (Result.get()) {
4227 // The only way a reference to a destructor can be used is to
4228 // immediately call it, which falls into this case. If the
4229 // next token is not a '(', produce a diagnostic and build the
4230 // call now.
4231 if (!HasTrailingLParen &&
4232 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCallb268a282010-08-23 23:25:46 +00004233 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall10eae182009-11-30 22:42:35 +00004234
John McCalle9cccd82010-06-16 08:42:20 +00004235 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00004236 }
4237
John McCallb268a282010-08-23 23:25:46 +00004238 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00004239 OpLoc, IsArrow, SS, FirstQualifierInScope,
4240 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004241 }
4242
4243 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00004244}
4245
John McCalldadc5752010-08-24 06:29:42 +00004246ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00004247 FunctionDecl *FD,
4248 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00004249 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004250 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00004251 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00004252 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004253 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00004254 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004255 return ExprError();
4256 }
4257
4258 if (Param->hasUninstantiatedDefaultArg()) {
4259 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00004260
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004261 // Instantiate the expression.
4262 MultiLevelTemplateArgumentList ArgList
4263 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00004264
Nico Weber44887f62010-11-29 18:19:25 +00004265 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004266 = ArgList.getInnermost();
4267 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4268 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00004269
Nico Weber44887f62010-11-29 18:19:25 +00004270 ExprResult Result;
4271 {
4272 // C++ [dcl.fct.default]p5:
4273 // The names in the [default argument] expression are bound, and
4274 // the semantic constraints are checked, at the point where the
4275 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00004276 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00004277 Result = SubstExpr(UninstExpr, ArgList);
4278 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004279 if (Result.isInvalid())
4280 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004281
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004282 // Check the expression as an initializer for the parameter.
4283 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004284 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004285 InitializationKind Kind
4286 = InitializationKind::CreateCopy(Param->getLocation(),
4287 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4288 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00004289
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004290 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4291 Result = InitSeq.Perform(*this, Entity, Kind,
4292 MultiExprArg(*this, &ResultE, 1));
4293 if (Result.isInvalid())
4294 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004295
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004296 // Build the default argument expression.
4297 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4298 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00004299 }
4300
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004301 // If the default expression creates temporaries, we need to
4302 // push them to the current stack of expression temporaries so they'll
4303 // be properly destroyed.
4304 // FIXME: We should really be rebuilding the default argument with new
4305 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00004306 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4307 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4308 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4309 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4310 ExprTemporaries.push_back(Temporary);
4311 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004312
4313 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00004314 // Just mark all of the declarations in this potentially-evaluated expression
4315 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004316 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00004317 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00004318}
4319
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004320/// ConvertArgumentsForCall - Converts the arguments specified in
4321/// Args/NumArgs to the parameter types of the function FDecl with
4322/// function prototype Proto. Call is the call expression itself, and
4323/// Fn is the function expression. For a C++ member function, this
4324/// routine does not attempt to convert the object argument. Returns
4325/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004326bool
4327Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004328 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004329 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004330 Expr **Args, unsigned NumArgs,
4331 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00004332 // Bail out early if calling a builtin with custom typechecking.
4333 // We don't need to do this in the
4334 if (FDecl)
4335 if (unsigned ID = FDecl->getBuiltinID())
4336 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4337 return false;
4338
Mike Stump4e1f26a2009-02-19 03:04:26 +00004339 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004340 // assignment, to the types of the corresponding parameter, ...
4341 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00004342 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004343
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004344 // If too few arguments are available (and we don't have default
4345 // arguments for the remaining parameters), don't make the call.
4346 if (NumArgs < NumArgsInProto) {
4347 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4348 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004349 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00004350 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00004351 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004352 }
4353
4354 // If too many are passed and not variadic, error on the extras and drop
4355 // them.
4356 if (NumArgs > NumArgsInProto) {
4357 if (!Proto->isVariadic()) {
4358 Diag(Args[NumArgsInProto]->getLocStart(),
4359 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004360 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004361 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004362 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4363 Args[NumArgs-1]->getLocEnd());
4364 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00004365 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004366 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004367 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004368 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004369 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004370 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004371 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4372 if (Fn->getType()->isBlockPointerType())
4373 CallType = VariadicBlock; // Block
4374 else if (isa<MemberExpr>(Fn))
4375 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004376 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004377 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004378 if (Invalid)
4379 return true;
4380 unsigned TotalNumArgs = AllArgs.size();
4381 for (unsigned i = 0; i < TotalNumArgs; ++i)
4382 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004383
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004384 return false;
4385}
Mike Stump4e1f26a2009-02-19 03:04:26 +00004386
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004387bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4388 FunctionDecl *FDecl,
4389 const FunctionProtoType *Proto,
4390 unsigned FirstProtoArg,
4391 Expr **Args, unsigned NumArgs,
4392 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004393 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004394 unsigned NumArgsInProto = Proto->getNumArgs();
4395 unsigned NumArgsToCheck = NumArgs;
4396 bool Invalid = false;
4397 if (NumArgs != NumArgsInProto)
4398 // Use default arguments for missing arguments
4399 NumArgsToCheck = NumArgsInProto;
4400 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004401 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004402 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004403 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004404
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004405 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004406 if (ArgIx < NumArgs) {
4407 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004408
Eli Friedman3164fb12009-03-22 22:00:50 +00004409 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4410 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00004411 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004412 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00004413 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004414
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004415 // Pass the argument
4416 ParmVarDecl *Param = 0;
4417 if (FDecl && i < FDecl->getNumParams())
4418 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00004419
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004420 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004421 Param? InitializedEntity::InitializeParameter(Context, Param)
4422 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCalldadc5752010-08-24 06:29:42 +00004423 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00004424 SourceLocation(),
4425 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004426 if (ArgE.isInvalid())
4427 return true;
4428
4429 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004430 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00004431 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004432
John McCalldadc5752010-08-24 06:29:42 +00004433 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004434 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004435 if (ArgExpr.isInvalid())
4436 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004437
Anders Carlsson355933d2009-08-25 03:49:14 +00004438 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004439 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004440 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004441 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004442
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004443 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004444 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004445 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004446 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004447 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00004448 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004449 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004450 }
4451 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00004452 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004453}
4454
Steve Naroff83895f72007-09-16 03:34:24 +00004455/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00004456/// This provides the location of the left/right parens and a list of comma
4457/// locations.
John McCalldadc5752010-08-24 06:29:42 +00004458ExprResult
John McCallb268a282010-08-23 23:25:46 +00004459Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004460 MultiExprArg args, SourceLocation RParenLoc,
4461 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004462 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00004463
4464 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004465 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00004466 if (Result.isInvalid()) return ExprError();
4467 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00004468
John McCallb268a282010-08-23 23:25:46 +00004469 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00004470
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004471 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00004472 // If this is a pseudo-destructor expression, build the call immediately.
4473 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4474 if (NumArgs > 0) {
4475 // Pseudo-destructor calls should not have any arguments.
4476 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00004477 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00004478 SourceRange(Args[0]->getLocStart(),
4479 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00004480
Douglas Gregorad8a3362009-09-04 17:36:40 +00004481 NumArgs = 0;
4482 }
Mike Stump11289f42009-09-09 15:08:12 +00004483
Douglas Gregorad8a3362009-09-04 17:36:40 +00004484 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00004485 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00004486 }
Mike Stump11289f42009-09-09 15:08:12 +00004487
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004488 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00004489 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00004490 // FIXME: Will need to cache the results of name lookup (including ADL) in
4491 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004492 bool Dependent = false;
4493 if (Fn->isTypeDependent())
4494 Dependent = true;
4495 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4496 Dependent = true;
4497
Peter Collingbourne41f85462011-02-09 21:07:24 +00004498 if (Dependent) {
4499 if (ExecConfig) {
4500 return Owned(new (Context) CUDAKernelCallExpr(
4501 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4502 Context.DependentTy, VK_RValue, RParenLoc));
4503 } else {
4504 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4505 Context.DependentTy, VK_RValue,
4506 RParenLoc));
4507 }
4508 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004509
4510 // Determine whether this is a call to an object (C++ [over.call.object]).
4511 if (Fn->getType()->isRecordType())
4512 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004513 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004514
John McCall10eae182009-11-30 22:42:35 +00004515 Expr *NakedFn = Fn->IgnoreParens();
4516
4517 // Determine whether this is a call to an unresolved member function.
4518 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4519 // If lookup was unresolved but not dependent (i.e. didn't find
4520 // an unresolved using declaration), it has to be an overloaded
4521 // function set, which means it must contain either multiple
4522 // declarations (all methods or method templates) or a single
4523 // method template.
4524 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor516d6722010-04-25 21:15:30 +00004525 isa<FunctionTemplateDecl>(
4526 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00004527 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00004528
John McCall2d74de92009-12-01 22:10:20 +00004529 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004530 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00004531 }
4532
Douglas Gregore254f902009-02-04 00:32:51 +00004533 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00004534 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004535 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00004536 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00004537 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004538 RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004539 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004540
Anders Carlsson61914b52009-10-03 17:40:22 +00004541 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00004542 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
John McCalle3027922010-08-25 11:45:40 +00004543 if (BO->getOpcode() == BO_PtrMemD ||
4544 BO->getOpcode() == BO_PtrMemI) {
Douglas Gregorc8be9522010-05-04 18:18:31 +00004545 if (const FunctionProtoType *FPT
4546 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00004547 QualType ResultTy = FPT->getCallResultType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00004548 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004549
Douglas Gregor125fa402011-02-04 12:57:49 +00004550 // Check that the object type isn't more qualified than the
4551 // member function we're calling.
4552 Qualifiers FuncQuals = Qualifiers::fromCVRMask(FPT->getTypeQuals());
4553 Qualifiers ObjectQuals
4554 = BO->getOpcode() == BO_PtrMemD
4555 ? BO->getLHS()->getType().getQualifiers()
4556 : BO->getLHS()->getType()->getAs<PointerType>()
4557 ->getPointeeType().getQualifiers();
4558
4559 Qualifiers Difference = ObjectQuals - FuncQuals;
4560 Difference.removeObjCGCAttr();
4561 Difference.removeAddressSpace();
4562 if (Difference) {
4563 std::string QualsString = Difference.getAsString();
4564 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
4565 << BO->getType().getUnqualifiedType()
4566 << QualsString
4567 << (QualsString.find(' ') == std::string::npos? 1 : 2);
4568 }
4569
John McCallb268a282010-08-23 23:25:46 +00004570 CXXMemberCallExpr *TheCall
Abramo Bagnara21e9d862010-12-03 21:39:42 +00004571 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
John McCall7decc9e2010-11-18 06:31:45 +00004572 NumArgs, ResultTy, VK,
John McCallb268a282010-08-23 23:25:46 +00004573 RParenLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004574
4575 if (CheckCallReturnType(FPT->getResultType(),
4576 BO->getRHS()->getSourceRange().getBegin(),
John McCallb268a282010-08-23 23:25:46 +00004577 TheCall, 0))
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004578 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00004579
John McCallb268a282010-08-23 23:25:46 +00004580 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004581 RParenLoc))
4582 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00004583
John McCallb268a282010-08-23 23:25:46 +00004584 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian42f66632009-10-28 16:49:46 +00004585 }
Anders Carlsson61914b52009-10-03 17:40:22 +00004586 }
4587 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004588 }
4589
Douglas Gregore254f902009-02-04 00:32:51 +00004590 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004591 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00004592 // lookup and whether there were any explicitly-specified template arguments.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004593
Eli Friedmane14b1992009-12-26 03:35:45 +00004594 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00004595 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4596 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4597 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004598 RParenLoc, ExecConfig);
Douglas Gregor928479e2010-11-09 20:03:54 +00004599 }
4600
John McCall57500772009-12-16 12:17:52 +00004601 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00004602 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4603 if (UnOp->getOpcode() == UO_AddrOf)
4604 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4605
John McCall57500772009-12-16 12:17:52 +00004606 if (isa<DeclRefExpr>(NakedFn))
4607 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4608
Peter Collingbourne41f85462011-02-09 21:07:24 +00004609 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
4610 ExecConfig);
4611}
4612
4613ExprResult
4614Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4615 MultiExprArg execConfig, SourceLocation GGGLoc) {
4616 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4617 if (!ConfigDecl)
4618 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4619 << "cudaConfigureCall");
4620 QualType ConfigQTy = ConfigDecl->getType();
4621
4622 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4623 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
4624
4625 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00004626}
4627
John McCall57500772009-12-16 12:17:52 +00004628/// BuildResolvedCallExpr - Build a call to a resolved expression,
4629/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00004630/// unary-convert to an expression of function-pointer or
4631/// block-pointer type.
4632///
4633/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00004634ExprResult
John McCall2d74de92009-12-01 22:10:20 +00004635Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4636 SourceLocation LParenLoc,
4637 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004638 SourceLocation RParenLoc,
4639 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00004640 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4641
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004642 // Promote the function operand.
4643 UsualUnaryConversions(Fn);
4644
Chris Lattner08464942007-12-28 05:29:59 +00004645 // Make the call expr early, before semantic checks. This guarantees cleanup
4646 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00004647 CallExpr *TheCall;
4648 if (Config) {
4649 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4650 cast<CallExpr>(Config),
4651 Args, NumArgs,
4652 Context.BoolTy,
4653 VK_RValue,
4654 RParenLoc);
4655 } else {
4656 TheCall = new (Context) CallExpr(Context, Fn,
4657 Args, NumArgs,
4658 Context.BoolTy,
4659 VK_RValue,
4660 RParenLoc);
4661 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004662
John McCallbebede42011-02-26 05:39:39 +00004663 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4664
4665 // Bail out early if calling a builtin with custom typechecking.
4666 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4667 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4668
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004669 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00004670 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004671 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4672 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00004673 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00004674 if (FuncT == 0)
4675 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4676 << Fn->getType() << Fn->getSourceRange());
4677 } else if (const BlockPointerType *BPT =
4678 Fn->getType()->getAs<BlockPointerType>()) {
4679 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4680 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004681 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4682 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00004683 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004684
Peter Collingbourne4b66c472011-02-23 01:53:29 +00004685 if (getLangOptions().CUDA) {
4686 if (Config) {
4687 // CUDA: Kernel calls must be to global functions
4688 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4689 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4690 << FDecl->getName() << Fn->getSourceRange());
4691
4692 // CUDA: Kernel function must have 'void' return type
4693 if (!FuncT->getResultType()->isVoidType())
4694 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4695 << Fn->getType() << Fn->getSourceRange());
4696 }
4697 }
4698
Eli Friedman3164fb12009-03-22 22:00:50 +00004699 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004700 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00004701 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004702 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00004703 return ExprError();
4704
Chris Lattner08464942007-12-28 05:29:59 +00004705 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004706 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00004707 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004708
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004709 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00004710 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004711 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004712 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00004713 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004714 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004715
Douglas Gregord8e97de2009-04-02 15:37:10 +00004716 if (FDecl) {
4717 // Check if we have too few/too many template arguments, based
4718 // on our knowledge of the function definition.
4719 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00004720 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004721 const FunctionProtoType *Proto
4722 = Def->getType()->getAs<FunctionProtoType>();
4723 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004724 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4725 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004726 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00004727
4728 // If the function we're calling isn't a function prototype, but we have
4729 // a function prototype from a prior declaratiom, use that prototype.
4730 if (!FDecl->hasPrototype())
4731 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00004732 }
4733
Steve Naroff0b661582007-08-28 23:30:39 +00004734 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00004735 for (unsigned i = 0; i != NumArgs; i++) {
4736 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00004737
4738 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004739 InitializedEntity Entity
4740 = InitializedEntity::InitializeParameter(Context,
4741 Proto->getArgType(i));
4742 ExprResult ArgE = PerformCopyInitialization(Entity,
4743 SourceLocation(),
4744 Owned(Arg));
4745 if (ArgE.isInvalid())
4746 return true;
4747
4748 Arg = ArgE.takeAs<Expr>();
4749
4750 } else {
4751 DefaultArgumentPromotion(Arg);
Douglas Gregor8e09a722010-10-25 20:39:23 +00004752 }
4753
Douglas Gregor83025412010-10-26 05:45:40 +00004754 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4755 Arg->getType(),
4756 PDiag(diag::err_call_incomplete_argument)
4757 << Arg->getSourceRange()))
4758 return ExprError();
4759
Chris Lattner08464942007-12-28 05:29:59 +00004760 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00004761 }
Steve Naroffae4143e2007-04-26 20:39:23 +00004762 }
Chris Lattner08464942007-12-28 05:29:59 +00004763
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004764 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4765 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004766 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4767 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004768
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00004769 // Check for sentinels
4770 if (NDecl)
4771 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004772
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004773 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004774 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00004775 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004776 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004777
John McCallbebede42011-02-26 05:39:39 +00004778 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00004779 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004780 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00004781 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004782 return ExprError();
4783 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004784
John McCallb268a282010-08-23 23:25:46 +00004785 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00004786}
4787
John McCalldadc5752010-08-24 06:29:42 +00004788ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004789Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004790 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00004791 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00004792 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00004793 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00004794
4795 TypeSourceInfo *TInfo;
4796 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4797 if (!TInfo)
4798 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4799
John McCallb268a282010-08-23 23:25:46 +00004800 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00004801}
4802
John McCalldadc5752010-08-24 06:29:42 +00004803ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00004804Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00004805 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00004806 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00004807
Eli Friedman37a186d2008-05-20 05:22:08 +00004808 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004809 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4810 PDiag(diag::err_illegal_decl_array_incomplete_type)
4811 << SourceRange(LParenLoc,
4812 literalExpr->getSourceRange().getEnd())))
4813 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00004814 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004815 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4816 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00004817 } else if (!literalType->isDependentType() &&
4818 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00004819 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00004820 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00004821 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004822 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00004823
Douglas Gregor85dabae2009-12-16 01:38:02 +00004824 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00004825 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004826 InitializationKind Kind
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004827 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004828 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00004829 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00004830 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00004831 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00004832 &literalType);
4833 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004834 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00004835 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00004836
Chris Lattner79413952008-12-04 23:50:19 +00004837 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00004838 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00004839 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004840 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004841 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004842
John McCall7decc9e2010-11-18 06:31:45 +00004843 // In C, compound literals are l-values for some reason.
4844 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
4845
John McCall5d7aa7f2010-01-19 22:33:45 +00004846 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCall7decc9e2010-11-18 06:31:45 +00004847 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004848}
4849
John McCalldadc5752010-08-24 06:29:42 +00004850ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00004851Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004852 SourceLocation RBraceLoc) {
4853 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00004854 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00004855
Steve Naroff30d242c2007-09-15 18:49:24 +00004856 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004857 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004858
Ted Kremenekac034612010-04-13 23:39:13 +00004859 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4860 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004861 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004862 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004863}
4864
John McCalld7646252010-11-14 08:17:51 +00004865/// Prepares for a scalar cast, performing all the necessary stages
4866/// except the final cast and returning the kind required.
4867static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
4868 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4869 // Also, callers should have filtered out the invalid cases with
4870 // pointers. Everything else should be possible.
4871
Abramo Bagnaraba854972011-01-04 09:50:03 +00004872 QualType SrcTy = Src->getType();
John McCalld7646252010-11-14 08:17:51 +00004873 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004874 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004875
John McCall8cb679e2010-11-15 09:13:47 +00004876 switch (SrcTy->getScalarTypeKind()) {
4877 case Type::STK_MemberPointer:
4878 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00004879
John McCall8cb679e2010-11-15 09:13:47 +00004880 case Type::STK_Pointer:
4881 switch (DestTy->getScalarTypeKind()) {
4882 case Type::STK_Pointer:
4883 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00004884 CK_AnyPointerToObjCPointerCast :
4885 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00004886 case Type::STK_Bool:
4887 return CK_PointerToBoolean;
4888 case Type::STK_Integral:
4889 return CK_PointerToIntegral;
4890 case Type::STK_Floating:
4891 case Type::STK_FloatingComplex:
4892 case Type::STK_IntegralComplex:
4893 case Type::STK_MemberPointer:
4894 llvm_unreachable("illegal cast from pointer");
4895 }
4896 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004897
John McCall8cb679e2010-11-15 09:13:47 +00004898 case Type::STK_Bool: // casting from bool is like casting from an integer
4899 case Type::STK_Integral:
4900 switch (DestTy->getScalarTypeKind()) {
4901 case Type::STK_Pointer:
John McCalld7646252010-11-14 08:17:51 +00004902 if (Src->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004903 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004904 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004905 case Type::STK_Bool:
4906 return CK_IntegralToBoolean;
4907 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004908 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004909 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004910 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004911 case Type::STK_IntegralComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004912 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallfcef3cf2010-12-14 17:51:41 +00004913 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004914 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004915 case Type::STK_FloatingComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004916 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004917 CK_IntegralToFloating);
4918 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004919 case Type::STK_MemberPointer:
4920 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004921 }
4922 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004923
John McCall8cb679e2010-11-15 09:13:47 +00004924 case Type::STK_Floating:
4925 switch (DestTy->getScalarTypeKind()) {
4926 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004927 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004928 case Type::STK_Bool:
4929 return CK_FloatingToBoolean;
4930 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004931 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004932 case Type::STK_FloatingComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004933 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCallfcef3cf2010-12-14 17:51:41 +00004934 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004935 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004936 case Type::STK_IntegralComplex:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004937 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004938 CK_FloatingToIntegral);
4939 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004940 case Type::STK_Pointer:
4941 llvm_unreachable("valid float->pointer cast?");
4942 case Type::STK_MemberPointer:
4943 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004944 }
4945 break;
4946
John McCall8cb679e2010-11-15 09:13:47 +00004947 case Type::STK_FloatingComplex:
4948 switch (DestTy->getScalarTypeKind()) {
4949 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004950 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004951 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004952 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004953 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00004954 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00004955 if (S.Context.hasSameType(ET, DestTy))
4956 return CK_FloatingComplexToReal;
4957 S.ImpCastExprToType(Src, ET, CK_FloatingComplexToReal);
4958 return CK_FloatingCast;
4959 }
John McCall8cb679e2010-11-15 09:13:47 +00004960 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004961 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004962 case Type::STK_Integral:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004963 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004964 CK_FloatingComplexToReal);
4965 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004966 case Type::STK_Pointer:
4967 llvm_unreachable("valid complex float->pointer cast?");
4968 case Type::STK_MemberPointer:
4969 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004970 }
4971 break;
4972
John McCall8cb679e2010-11-15 09:13:47 +00004973 case Type::STK_IntegralComplex:
4974 switch (DestTy->getScalarTypeKind()) {
4975 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004976 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004977 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004978 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004979 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00004980 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00004981 if (S.Context.hasSameType(ET, DestTy))
4982 return CK_IntegralComplexToReal;
4983 S.ImpCastExprToType(Src, ET, CK_IntegralComplexToReal);
4984 return CK_IntegralCast;
4985 }
John McCall8cb679e2010-11-15 09:13:47 +00004986 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004987 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004988 case Type::STK_Floating:
Abramo Bagnaraba854972011-01-04 09:50:03 +00004989 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
John McCalld7646252010-11-14 08:17:51 +00004990 CK_IntegralComplexToReal);
4991 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004992 case Type::STK_Pointer:
4993 llvm_unreachable("valid complex int->pointer cast?");
4994 case Type::STK_MemberPointer:
4995 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004996 }
4997 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00004998 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004999
John McCalld7646252010-11-14 08:17:51 +00005000 llvm_unreachable("Unhandled scalar cast");
5001 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00005002}
5003
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005004/// CheckCastTypes - Check type constraints for casting between types.
John McCall7decc9e2010-11-18 06:31:45 +00005005bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
5006 Expr *&castExpr, CastKind& Kind, ExprValueKind &VK,
5007 CXXCastPath &BasePath, bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00005008 if (getLangOptions().CPlusPlus)
Douglas Gregor15417cf2010-11-03 00:35:38 +00005009 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
5010 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00005011 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00005012 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00005013
John McCall7decc9e2010-11-18 06:31:45 +00005014 // We only support r-value casts in C.
5015 VK = VK_RValue;
5016
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005017 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
5018 // type needs to be scalar.
5019 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00005020 // We don't necessarily do lvalue-to-rvalue conversions on this.
5021 IgnoredValueConversions(castExpr);
5022
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005023 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00005024 Kind = CK_ToVoid;
Anders Carlssonef918ac2009-10-16 02:35:04 +00005025 return false;
5026 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005027
John McCall34376a62010-12-04 03:47:34 +00005028 DefaultFunctionArrayLvalueConversion(castExpr);
5029
Eli Friedmane98194d2010-07-17 20:43:49 +00005030 if (RequireCompleteType(TyR.getBegin(), castType,
5031 diag::err_typecheck_cast_to_incomplete))
5032 return true;
5033
Anders Carlssonef918ac2009-10-16 02:35:04 +00005034 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005035 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005036 (castType->isStructureType() || castType->isUnionType())) {
5037 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00005038 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005039 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
5040 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005041 Kind = CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00005042 return false;
5043 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005044
Anders Carlsson525b76b2009-10-16 02:48:28 +00005045 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005046 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005047 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005048 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005049 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005050 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005051 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00005052 castExpr->getType()) &&
5053 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005054 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
5055 << castExpr->getSourceRange();
5056 break;
5057 }
5058 }
5059 if (Field == FieldEnd)
5060 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
5061 << castExpr->getType() << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005062 Kind = CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00005063 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005064 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005065
Anders Carlsson525b76b2009-10-16 02:48:28 +00005066 // Reject any other conversions to non-scalar types.
5067 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
5068 << castType << castExpr->getSourceRange();
5069 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005070
John McCalld7646252010-11-14 08:17:51 +00005071 // The type we're casting to is known to be a scalar or vector.
5072
5073 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005074 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00005075 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00005076 return Diag(castExpr->getLocStart(),
5077 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005078 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00005079 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005080
5081 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00005082 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005083
Anders Carlsson525b76b2009-10-16 02:48:28 +00005084 if (castType->isVectorType())
5085 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
5086 if (castExpr->getType()->isVectorType())
5087 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
5088
John McCalld7646252010-11-14 08:17:51 +00005089 // The source and target types are both scalars, i.e.
5090 // - arithmetic types (fundamental, enum, and complex)
5091 // - all kinds of pointers
5092 // Note that member pointers were filtered out with C++, above.
5093
Anders Carlsson43d70f82009-10-16 05:23:41 +00005094 if (isa<ObjCSelectorExpr>(castExpr))
5095 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005096
John McCalld7646252010-11-14 08:17:51 +00005097 // If either type is a pointer, the other type has to be either an
5098 // integer or a pointer.
Anders Carlsson525b76b2009-10-16 02:48:28 +00005099 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005100 QualType castExprType = castExpr->getType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005101 if (!castExprType->isIntegralType(Context) &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005102 castExprType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005103 return Diag(castExpr->getLocStart(),
5104 diag::err_cast_pointer_from_non_pointer_int)
5105 << castExprType << castExpr->getSourceRange();
5106 } else if (!castExpr->getType()->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00005107 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005108 return Diag(castExpr->getLocStart(),
5109 diag::err_cast_pointer_to_non_pointer_int)
5110 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005111 }
Anders Carlsson094c4592009-10-18 18:12:03 +00005112
John McCalld7646252010-11-14 08:17:51 +00005113 Kind = PrepareScalarCast(*this, castExpr, castType);
John McCall2b5c1b22010-08-12 21:44:57 +00005114
John McCalld7646252010-11-14 08:17:51 +00005115 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00005116 CheckCastAlign(castExpr, castType, TyR);
5117
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005118 return false;
5119}
5120
Anders Carlsson525b76b2009-10-16 02:48:28 +00005121bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00005122 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00005123 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005124
Anders Carlssonde71adf2007-11-27 05:51:55 +00005125 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00005126 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00005127 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00005128 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00005129 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00005130 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005131 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005132 } else
5133 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00005134 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005135 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005136
John McCalle3027922010-08-25 11:45:40 +00005137 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005138 return false;
5139}
5140
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005141bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
John McCalle3027922010-08-25 11:45:40 +00005142 CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00005143 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005144
Anders Carlsson43d70f82009-10-16 05:23:41 +00005145 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005146
Nate Begemanc8961a42009-06-27 22:05:55 +00005147 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5148 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00005149 if (SrcTy->isVectorType()) {
5150 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
5151 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5152 << DestTy << SrcTy << R;
John McCalle3027922010-08-25 11:45:40 +00005153 Kind = CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00005154 return false;
5155 }
5156
Nate Begemanbd956c42009-06-28 02:36:38 +00005157 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00005158 // conversion will take place first from scalar to elt type, and then
5159 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00005160 if (SrcTy->isPointerType())
5161 return Diag(R.getBegin(),
5162 diag::err_invalid_conversion_between_vector_and_scalar)
5163 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00005164
5165 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5166 ImpCastExprToType(CastExpr, DestElemTy,
John McCalld7646252010-11-14 08:17:51 +00005167 PrepareScalarCast(*this, CastExpr, DestElemTy));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005168
John McCalle3027922010-08-25 11:45:40 +00005169 Kind = CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00005170 return false;
5171}
5172
John McCalldadc5752010-08-24 06:29:42 +00005173ExprResult
John McCallba7bf592010-08-24 05:47:05 +00005174Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00005175 SourceLocation RParenLoc, Expr *castExpr) {
5176 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00005177 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00005178
John McCall97513962010-01-15 18:39:57 +00005179 TypeSourceInfo *castTInfo;
5180 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5181 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00005182 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00005183
Nate Begeman5ec4b312009-08-10 23:49:36 +00005184 // If the Expr being casted is a ParenListExpr, handle it specially.
5185 if (isa<ParenListExpr>(castExpr))
John McCallb268a282010-08-23 23:25:46 +00005186 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCalle15bbff2010-01-18 19:35:47 +00005187 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00005188
John McCallb268a282010-08-23 23:25:46 +00005189 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00005190}
5191
John McCalldadc5752010-08-24 06:29:42 +00005192ExprResult
John McCallebe54742010-01-15 18:56:44 +00005193Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00005194 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00005195 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00005196 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00005197 CXXCastPath BasePath;
John McCallebe54742010-01-15 18:56:44 +00005198 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
John McCall7decc9e2010-11-18 06:31:45 +00005199 Kind, VK, BasePath))
Sebastian Redlb5d49352009-01-19 22:31:54 +00005200 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00005201
John McCallcf142162010-08-07 06:22:56 +00005202 return Owned(CStyleCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +00005203 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00005204 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00005205 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00005206}
5207
Nate Begeman5ec4b312009-08-10 23:49:36 +00005208/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5209/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00005210ExprResult
John McCallb268a282010-08-23 23:25:46 +00005211Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005212 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5213 if (!E)
5214 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00005215
John McCalldadc5752010-08-24 06:29:42 +00005216 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00005217
Nate Begeman5ec4b312009-08-10 23:49:36 +00005218 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00005219 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5220 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00005221
John McCallb268a282010-08-23 23:25:46 +00005222 if (Result.isInvalid()) return ExprError();
5223
5224 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005225}
5226
John McCalldadc5752010-08-24 06:29:42 +00005227ExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00005228Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00005229 SourceLocation RParenLoc, Expr *Op,
John McCalle15bbff2010-01-18 19:35:47 +00005230 TypeSourceInfo *TInfo) {
John McCallb268a282010-08-23 23:25:46 +00005231 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCalle15bbff2010-01-18 19:35:47 +00005232 QualType Ty = TInfo->getType();
John Thompson781ad172010-06-30 22:55:51 +00005233 bool isAltiVecLiteral = false;
Mike Stump11289f42009-09-09 15:08:12 +00005234
John Thompson781ad172010-06-30 22:55:51 +00005235 // Check for an altivec literal,
5236 // i.e. all the elements are integer constants.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005237 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5238 if (PE->getNumExprs() == 0) {
5239 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5240 return ExprError();
5241 }
John Thompson781ad172010-06-30 22:55:51 +00005242 if (PE->getNumExprs() == 1) {
5243 if (!PE->getExpr(0)->getType()->isVectorType())
5244 isAltiVecLiteral = true;
5245 }
5246 else
5247 isAltiVecLiteral = true;
5248 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00005249
John Thompson781ad172010-06-30 22:55:51 +00005250 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
5251 // then handle it as such.
5252 if (isAltiVecLiteral) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005253 llvm::SmallVector<Expr *, 8> initExprs;
5254 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5255 initExprs.push_back(PE->getExpr(i));
5256
5257 // FIXME: This means that pretty-printing the final AST will produce curly
5258 // braces instead of the original commas.
Ted Kremenekac034612010-04-13 23:39:13 +00005259 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5260 &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00005261 initExprs.size(), RParenLoc);
5262 E->setType(Ty);
John McCallb268a282010-08-23 23:25:46 +00005263 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005264 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005265 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00005266 // sequence of BinOp comma operators.
John McCalldadc5752010-08-24 06:29:42 +00005267 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCallb268a282010-08-23 23:25:46 +00005268 if (Result.isInvalid()) return ExprError();
5269 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005270 }
5271}
5272
John McCalldadc5752010-08-24 06:29:42 +00005273ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00005274 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005275 MultiExprArg Val,
John McCallba7bf592010-08-24 05:47:05 +00005276 ParsedType TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005277 unsigned nexprs = Val.size();
5278 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005279 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5280 Expr *expr;
5281 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5282 expr = new (Context) ParenExpr(L, R, exprs[0]);
5283 else
5284 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005285 return Owned(expr);
5286}
5287
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005288/// \brief Emit a specialized diagnostic when one expression is a null pointer
5289/// constant and the other is not a pointer.
5290bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5291 SourceLocation QuestionLoc) {
5292 Expr *NullExpr = LHS;
5293 Expr *NonPointerExpr = RHS;
5294 Expr::NullPointerConstantKind NullKind =
5295 NullExpr->isNullPointerConstant(Context,
5296 Expr::NPC_ValueDependentIsNotNull);
5297
5298 if (NullKind == Expr::NPCK_NotNull) {
5299 NullExpr = RHS;
5300 NonPointerExpr = LHS;
5301 NullKind =
5302 NullExpr->isNullPointerConstant(Context,
5303 Expr::NPC_ValueDependentIsNotNull);
5304 }
5305
5306 if (NullKind == Expr::NPCK_NotNull)
5307 return false;
5308
5309 if (NullKind == Expr::NPCK_ZeroInteger) {
5310 // In this case, check to make sure that we got here from a "NULL"
5311 // string in the source code.
5312 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00005313 SourceLocation loc = NullExpr->getExprLoc();
5314 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005315 return false;
5316 }
5317
5318 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5319 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5320 << NonPointerExpr->getType() << DiagType
5321 << NonPointerExpr->getSourceRange();
5322 return true;
5323}
5324
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005325/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5326/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00005327/// C99 6.5.15
5328QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005329 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00005330 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00005331
5332 // If either LHS or RHS are overloaded functions, try to resolve them.
5333 if (LHS->getType() == Context.OverloadTy ||
5334 RHS->getType() == Context.OverloadTy) {
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005335 ExprResult LHSResult = CheckPlaceholderExpr(LHS, QuestionLoc);
5336 if (LHSResult.isInvalid())
5337 return QualType();
5338
5339 ExprResult RHSResult = CheckPlaceholderExpr(RHS, QuestionLoc);
5340 if (RHSResult.isInvalid())
5341 return QualType();
5342
5343 LHS = LHSResult.take();
5344 RHS = RHSResult.take();
5345 }
5346
Sebastian Redl1a99f442009-04-16 17:51:27 +00005347 // C++ is sufficiently different to merit its own checker.
5348 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00005349 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00005350
5351 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005352 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005353
Chris Lattner432cff52009-02-18 04:28:32 +00005354 UsualUnaryConversions(Cond);
John McCallc07a0c72011-02-17 10:25:35 +00005355 UsualUnaryConversions(LHS);
Chris Lattner432cff52009-02-18 04:28:32 +00005356 UsualUnaryConversions(RHS);
5357 QualType CondTy = Cond->getType();
5358 QualType LHSTy = LHS->getType();
5359 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00005360
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005361 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005362 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00005363 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5364 // Throw an error if its not either.
5365 if (getLangOptions().OpenCL) {
5366 if (!CondTy->isVectorType()) {
5367 Diag(Cond->getLocStart(),
5368 diag::err_typecheck_cond_expect_scalar_or_vector)
5369 << CondTy;
5370 return QualType();
5371 }
5372 }
5373 else {
5374 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5375 << CondTy;
5376 return QualType();
5377 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005378 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005379
Chris Lattnere2949f42008-01-06 22:42:25 +00005380 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005381 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5382 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00005383
Nate Begemanabb5a732010-09-20 22:41:17 +00005384 // OpenCL: If the condition is a vector, and both operands are scalar,
5385 // attempt to implicity convert them to the vector type to act like the
5386 // built in select.
5387 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5388 // Both operands should be of scalar type.
5389 if (!LHSTy->isScalarType()) {
5390 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5391 << CondTy;
5392 return QualType();
5393 }
5394 if (!RHSTy->isScalarType()) {
5395 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5396 << CondTy;
5397 return QualType();
5398 }
5399 // Implicity convert these scalars to the type of the condition.
5400 ImpCastExprToType(LHS, CondTy, CK_IntegralCast);
5401 ImpCastExprToType(RHS, CondTy, CK_IntegralCast);
5402 }
5403
Chris Lattnere2949f42008-01-06 22:42:25 +00005404 // If both operands have arithmetic type, do the usual arithmetic conversions
5405 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00005406 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5407 UsualArithmeticConversions(LHS, RHS);
5408 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00005409 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005410
Chris Lattnere2949f42008-01-06 22:42:25 +00005411 // If both operands are the same structure or union type, the result is that
5412 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005413 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5414 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00005415 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005416 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00005417 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00005418 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00005419 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005420 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005421
Chris Lattnere2949f42008-01-06 22:42:25 +00005422 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00005423 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00005424 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5425 if (!LHSTy->isVoidType())
5426 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5427 << RHS->getSourceRange();
5428 if (!RHSTy->isVoidType())
5429 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5430 << LHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005431 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid);
5432 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00005433 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00005434 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00005435 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5436 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00005437 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005438 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005439 // promote the null to a pointer.
John McCall8cb679e2010-11-15 09:13:47 +00005440 ImpCastExprToType(RHS, LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005441 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005442 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005443 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005444 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00005445 ImpCastExprToType(LHS, RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005446 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005447 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005448
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005449 // All objective-c pointer type analysis is done here.
5450 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5451 QuestionLoc);
5452 if (!compositeType.isNull())
5453 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005454
5455
Steve Naroff05efa972009-07-01 14:36:47 +00005456 // Handle block pointer types.
5457 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5458 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5459 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5460 QualType destType = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005461 ImpCastExprToType(LHS, destType, CK_BitCast);
5462 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005463 return destType;
5464 }
5465 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005466 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00005467 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00005468 }
Steve Naroff05efa972009-07-01 14:36:47 +00005469 // We have 2 block pointer types.
5470 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5471 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00005472 return LHSTy;
5473 }
Steve Naroff05efa972009-07-01 14:36:47 +00005474 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005475 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5476 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005477
Steve Naroff05efa972009-07-01 14:36:47 +00005478 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5479 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00005480 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005481 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00005482 // In this situation, we assume void* type. No especially good
5483 // reason, but this is what gcc does, and we do have to pick
5484 // to get a consistent AST.
5485 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005486 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5487 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00005488 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005489 }
Steve Naroff05efa972009-07-01 14:36:47 +00005490 // The block pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00005491 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5492 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00005493 return LHSTy;
5494 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005495
Steve Naroff05efa972009-07-01 14:36:47 +00005496 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5497 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5498 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005499 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5500 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00005501
5502 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5503 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5504 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00005505 QualType destPointee
5506 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005507 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005508 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005509 ImpCastExprToType(LHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005510 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005511 ImpCastExprToType(RHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005512 return destType;
5513 }
5514 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00005515 QualType destPointee
5516 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005517 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005518 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005519 ImpCastExprToType(RHS, destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005520 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005521 ImpCastExprToType(LHS, destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005522 return destType;
5523 }
5524
5525 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5526 // Two identical pointer types are always compatible.
5527 return LHSTy;
5528 }
5529 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5530 rhptee.getUnqualifiedType())) {
5531 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5532 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5533 // In this situation, we assume void* type. No especially good
5534 // reason, but this is what gcc does, and we do have to pick
5535 // to get a consistent AST.
5536 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John McCalle3027922010-08-25 11:45:40 +00005537 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5538 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005539 return incompatTy;
5540 }
5541 // The pointer types are compatible.
5542 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5543 // differently qualified versions of compatible types, the result type is
5544 // a pointer to an appropriately qualified version of the *composite*
5545 // type.
5546 // FIXME: Need to calculate the composite type.
5547 // FIXME: Need to add qualifiers
John McCalle3027922010-08-25 11:45:40 +00005548 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5549 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005550 return LHSTy;
5551 }
Mike Stump11289f42009-09-09 15:08:12 +00005552
John McCalle84af4e2010-11-13 01:35:44 +00005553 // GCC compatibility: soften pointer/integer mismatch. Note that
5554 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00005555 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5556 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5557 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005558 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005559 return RHSTy;
5560 }
5561 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5562 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5563 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005564 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005565 return LHSTy;
5566 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00005567
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005568 // Emit a better diagnostic if one of the expressions is a null pointer
5569 // constant and the other is not a pointer type. In this case, the user most
5570 // likely forgot to take the address of the other expression.
5571 if (DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
5572 return QualType();
5573
Chris Lattnere2949f42008-01-06 22:42:25 +00005574 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00005575 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5576 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005577 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00005578}
5579
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005580/// FindCompositeObjCPointerType - Helper method to find composite type of
5581/// two objective-c pointer types of the two input expressions.
5582QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
5583 SourceLocation QuestionLoc) {
5584 QualType LHSTy = LHS->getType();
5585 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005586
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005587 // Handle things like Class and struct objc_class*. Here we case the result
5588 // to the pseudo-builtin, because that will be implicitly cast back to the
5589 // redefinition type if an attempt is made to access its fields.
5590 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005591 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005592 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005593 return LHSTy;
5594 }
5595 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005596 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005597 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005598 return RHSTy;
5599 }
5600 // And the same for struct objc_object* / id
5601 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005602 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005603 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005604 return LHSTy;
5605 }
5606 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005607 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005608 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005609 return RHSTy;
5610 }
5611 // And the same for struct objc_selector* / SEL
5612 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005613 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005614 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005615 return LHSTy;
5616 }
5617 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005618 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John McCalle3027922010-08-25 11:45:40 +00005619 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005620 return RHSTy;
5621 }
5622 // Check constraints for Objective-C object pointers types.
5623 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005624
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005625 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5626 // Two identical object pointer types are always compatible.
5627 return LHSTy;
5628 }
5629 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5630 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5631 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005632
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005633 // If both operands are interfaces and either operand can be
5634 // assigned to the other, use that type as the composite
5635 // type. This allows
5636 // xxx ? (A*) a : (B*) b
5637 // where B is a subclass of A.
5638 //
5639 // Additionally, as for assignment, if either type is 'id'
5640 // allow silent coercion. Finally, if the types are
5641 // incompatible then make sure to use 'id' as the composite
5642 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005643
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005644 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5645 // It could return the composite type.
5646 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5647 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5648 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5649 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5650 } else if ((LHSTy->isObjCQualifiedIdType() ||
5651 RHSTy->isObjCQualifiedIdType()) &&
5652 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5653 // Need to handle "id<xx>" explicitly.
5654 // GCC allows qualified id and any Objective-C type to devolve to
5655 // id. Currently localizing to here until clear this should be
5656 // part of ObjCQualifiedIdTypesAreCompatible.
5657 compositeType = Context.getObjCIdType();
5658 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5659 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005660 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005661 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5662 ;
5663 else {
5664 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5665 << LHSTy << RHSTy
5666 << LHS->getSourceRange() << RHS->getSourceRange();
5667 QualType incompatTy = Context.getObjCIdType();
John McCalle3027922010-08-25 11:45:40 +00005668 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5669 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005670 return incompatTy;
5671 }
5672 // The object pointer types are compatible.
John McCalle3027922010-08-25 11:45:40 +00005673 ImpCastExprToType(LHS, compositeType, CK_BitCast);
5674 ImpCastExprToType(RHS, compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005675 return compositeType;
5676 }
5677 // Check Objective-C object pointer types and 'void *'
5678 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5679 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5680 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5681 QualType destPointee
5682 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5683 QualType destType = Context.getPointerType(destPointee);
5684 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005685 ImpCastExprToType(LHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005686 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005687 ImpCastExprToType(RHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005688 return destType;
5689 }
5690 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5691 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5692 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5693 QualType destPointee
5694 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5695 QualType destType = Context.getPointerType(destPointee);
5696 // Add qualifiers if necessary.
John McCalle3027922010-08-25 11:45:40 +00005697 ImpCastExprToType(RHS, destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005698 // Promote to void*.
John McCalle3027922010-08-25 11:45:40 +00005699 ImpCastExprToType(LHS, destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005700 return destType;
5701 }
5702 return QualType();
5703}
5704
Steve Naroff83895f72007-09-16 03:34:24 +00005705/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005706/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005707ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005708 SourceLocation ColonLoc,
5709 Expr *CondExpr, Expr *LHSExpr,
5710 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005711 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5712 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005713 OpaqueValueExpr *opaqueValue = 0;
5714 Expr *commonExpr = 0;
5715 if (LHSExpr == 0) {
5716 commonExpr = CondExpr;
5717
5718 // We usually want to apply unary conversions *before* saving, except
5719 // in the special case of a C++ l-value conditional.
5720 if (!(getLangOptions().CPlusPlus
5721 && !commonExpr->isTypeDependent()
5722 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5723 && commonExpr->isGLValue()
5724 && commonExpr->isOrdinaryOrBitFieldObject()
5725 && RHSExpr->isOrdinaryOrBitFieldObject()
5726 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5727 UsualUnaryConversions(commonExpr);
5728 }
5729
5730 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5731 commonExpr->getType(),
5732 commonExpr->getValueKind(),
5733 commonExpr->getObjectKind());
5734 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005735 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005736
John McCall7decc9e2010-11-18 06:31:45 +00005737 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005738 ExprObjectKind OK = OK_Ordinary;
Fariborz Jahanian2b1d88a2010-09-18 19:38:38 +00005739 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr,
John McCallc07a0c72011-02-17 10:25:35 +00005740 VK, OK, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00005741 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005742 return ExprError();
5743
John McCallc07a0c72011-02-17 10:25:35 +00005744 if (!commonExpr)
5745 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
5746 LHSExpr, ColonLoc,
5747 RHSExpr, result, VK, OK));
5748
5749 return Owned(new (Context)
5750 BinaryConditionalOperator(commonExpr, opaqueValue, CondExpr, LHSExpr,
5751 RHSExpr, QuestionLoc, ColonLoc, result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005752}
5753
John McCallaba90822011-01-31 23:13:11 +00005754// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005755// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005756// routine is it effectively iqnores the qualifiers on the top level pointee.
5757// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5758// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005759static Sema::AssignConvertType
5760checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5761 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5762 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005763
Steve Naroff1f4d7272007-05-11 04:00:31 +00005764 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005765 const Type *lhptee, *rhptee;
5766 Qualifiers lhq, rhq;
5767 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5768 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005769
John McCallaba90822011-01-31 23:13:11 +00005770 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005771
5772 // C99 6.5.16.1p1: This following citation is common to constraints
5773 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5774 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005775 Qualifiers lq;
5776
5777 if (!lhq.compatiblyIncludes(rhq)) {
5778 // Treat address-space mismatches as fatal. TODO: address subspaces
5779 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5780 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5781
5782 // For GCC compatibility, other qualifier mismatches are treated
5783 // as still compatible in C.
5784 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5785 }
Steve Naroff3f597292007-05-11 22:18:03 +00005786
Mike Stump4e1f26a2009-02-19 03:04:26 +00005787 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5788 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005789 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005790 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005791 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005792 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005793
Chris Lattner0a788432008-01-03 22:56:36 +00005794 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005795 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005796 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005797 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005798
Chris Lattner0a788432008-01-03 22:56:36 +00005799 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005800 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005801 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005802
5803 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005804 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005805 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005806 }
John McCall4fff8f62011-02-01 00:10:29 +00005807
Mike Stump4e1f26a2009-02-19 03:04:26 +00005808 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005809 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005810 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5811 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005812 // Check if the pointee types are compatible ignoring the sign.
5813 // We explicitly check for char so that we catch "char" vs
5814 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005815 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005816 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005817 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005818 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005819
Chris Lattnerec3a1562009-10-17 20:33:28 +00005820 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005821 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005822 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005823 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005824
John McCall4fff8f62011-02-01 00:10:29 +00005825 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005826 // Types are compatible ignoring the sign. Qualifier incompatibility
5827 // takes priority over sign incompatibility because the sign
5828 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005829 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005830 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005831
John McCallaba90822011-01-31 23:13:11 +00005832 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005833 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005834
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005835 // If we are a multi-level pointer, it's possible that our issue is simply
5836 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5837 // the eventual target type is the same and the pointers have the same
5838 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005839 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005840 do {
John McCall4fff8f62011-02-01 00:10:29 +00005841 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5842 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005843 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005844
John McCall4fff8f62011-02-01 00:10:29 +00005845 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005846 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005847 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005848
Eli Friedman80160bd2009-03-22 23:59:44 +00005849 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005850 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005851 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005852 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005853}
5854
John McCallaba90822011-01-31 23:13:11 +00005855/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005856/// block pointer types are compatible or whether a block and normal pointer
5857/// are compatible. It is more restrict than comparing two function pointer
5858// types.
John McCallaba90822011-01-31 23:13:11 +00005859static Sema::AssignConvertType
5860checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5861 QualType rhsType) {
5862 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5863 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5864
Steve Naroff081c7422008-09-04 15:10:53 +00005865 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005866
Steve Naroff081c7422008-09-04 15:10:53 +00005867 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00005868 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5869 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005870
John McCallaba90822011-01-31 23:13:11 +00005871 // In C++, the types have to match exactly.
5872 if (S.getLangOptions().CPlusPlus)
5873 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005874
John McCallaba90822011-01-31 23:13:11 +00005875 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005876
Steve Naroff081c7422008-09-04 15:10:53 +00005877 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005878 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5879 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005880
John McCallaba90822011-01-31 23:13:11 +00005881 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5882 return Sema::IncompatibleBlockPointer;
5883
Steve Naroff081c7422008-09-04 15:10:53 +00005884 return ConvTy;
5885}
5886
John McCallaba90822011-01-31 23:13:11 +00005887/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005888/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005889static Sema::AssignConvertType
5890checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5891 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5892 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5893
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005894 if (lhsType->isObjCBuiltinType()) {
5895 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005896 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5897 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005898 return Sema::IncompatiblePointer;
5899 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005900 }
5901 if (rhsType->isObjCBuiltinType()) {
5902 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005903 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5904 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005905 return Sema::IncompatiblePointer;
5906 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005907 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005908 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005909 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005910 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005911 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005912
John McCallaba90822011-01-31 23:13:11 +00005913 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5914 return Sema::CompatiblePointerDiscardsQualifiers;
5915
5916 if (S.Context.typesAreCompatible(lhsType, rhsType))
5917 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005918 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005919 return Sema::IncompatibleObjCQualifiedId;
5920 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005921}
5922
John McCall29600e12010-11-16 02:32:08 +00005923Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005924Sema::CheckAssignmentConstraints(SourceLocation Loc,
5925 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00005926 // Fake up an opaque expression. We don't actually care about what
5927 // cast operations are required, so if CheckAssignmentConstraints
5928 // adds casts to this they'll be wasted, but fortunately that doesn't
5929 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00005930 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John McCall29600e12010-11-16 02:32:08 +00005931 Expr *rhsPtr = &rhs;
5932 CastKind K = CK_Invalid;
5933
5934 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5935}
5936
Mike Stump4e1f26a2009-02-19 03:04:26 +00005937/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5938/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005939/// pointers. Here are some objectionable examples that GCC considers warnings:
5940///
5941/// int a, *pint;
5942/// short *pshort;
5943/// struct foo *pfoo;
5944///
5945/// pint = pshort; // warning: assignment from incompatible pointer type
5946/// a = pint; // warning: assignment makes integer from pointer without a cast
5947/// pint = a; // warning: assignment makes pointer from integer without a cast
5948/// pint = pfoo; // warning: assignment from incompatible pointer type
5949///
5950/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005951/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005952///
John McCall8cb679e2010-11-15 09:13:47 +00005953/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005954Sema::AssignConvertType
John McCall29600e12010-11-16 02:32:08 +00005955Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs,
John McCall8cb679e2010-11-15 09:13:47 +00005956 CastKind &Kind) {
John McCall29600e12010-11-16 02:32:08 +00005957 QualType rhsType = rhs->getType();
5958
Chris Lattnera52c2f22008-01-04 23:18:45 +00005959 // Get canonical types. We're not formatting these types, just comparing
5960 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00005961 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5962 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005963
John McCalle5255932011-01-31 22:28:28 +00005964 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00005965 if (lhsType == rhsType) {
5966 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005967 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005968 }
5969
Douglas Gregor6b754842008-10-28 00:22:11 +00005970 // If the left-hand side is a reference type, then we are in a
5971 // (rare!) case where we've allowed the use of references in C,
5972 // e.g., as a parameter type in a built-in function. In this case,
5973 // just make sure that the type referenced is compatible with the
5974 // right-hand side type. The caller is responsible for adjusting
5975 // lhsType so that the resulting expression does not have reference
5976 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005977 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005978 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5979 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005980 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005981 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005982 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005983 }
John McCalle5255932011-01-31 22:28:28 +00005984
Nate Begemanbd956c42009-06-28 02:36:38 +00005985 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5986 // to the same ExtVector type.
5987 if (lhsType->isExtVectorType()) {
5988 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005989 return Incompatible;
5990 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005991 // CK_VectorSplat does T -> vector T, so first cast to the
5992 // element type.
5993 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5994 if (elType != rhsType) {
5995 Kind = PrepareScalarCast(*this, rhs, elType);
5996 ImpCastExprToType(rhs, elType, Kind);
5997 }
5998 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005999 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006000 }
Nate Begemanbd956c42009-06-28 02:36:38 +00006001 }
Mike Stump11289f42009-09-09 15:08:12 +00006002
John McCalle5255932011-01-31 22:28:28 +00006003 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00006004 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006005 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00006006 // Allow assignments of an AltiVec vector type to an equivalent GCC
6007 // vector type and vice versa
6008 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
6009 Kind = CK_BitCast;
6010 return Compatible;
6011 }
6012
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006013 // If we are allowing lax vector conversions, and LHS and RHS are both
6014 // vectors, the total size only needs to be the same. This is a bitcast;
6015 // no bits are changed but the result type is different.
6016 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00006017 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00006018 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006019 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00006020 }
Chris Lattner881a2122008-01-04 23:32:24 +00006021 }
6022 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006023 }
Eli Friedman3360d892008-05-30 18:07:22 +00006024
John McCalle5255932011-01-31 22:28:28 +00006025 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00006026 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00006027 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00006028 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00006029 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006030 }
Eli Friedman3360d892008-05-30 18:07:22 +00006031
John McCalle5255932011-01-31 22:28:28 +00006032 // Conversions to normal pointers.
6033 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
6034 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00006035 if (isa<PointerType>(rhsType)) {
6036 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006037 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00006038 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006039
John McCalle5255932011-01-31 22:28:28 +00006040 // int -> T*
6041 if (rhsType->isIntegerType()) {
6042 Kind = CK_IntegralToPointer; // FIXME: null?
6043 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006044 }
John McCalle5255932011-01-31 22:28:28 +00006045
6046 // C pointers are not compatible with ObjC object pointers,
6047 // with two exceptions:
6048 if (isa<ObjCObjectPointerType>(rhsType)) {
6049 // - conversions to void*
6050 if (lhsPointer->getPointeeType()->isVoidType()) {
6051 Kind = CK_AnyPointerToObjCPointerCast;
6052 return Compatible;
6053 }
6054
6055 // - conversions from 'Class' to the redefinition type
6056 if (rhsType->isObjCClassType() &&
6057 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006058 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006059 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006060 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006061
John McCalle5255932011-01-31 22:28:28 +00006062 Kind = CK_BitCast;
6063 return IncompatiblePointer;
6064 }
6065
6066 // U^ -> void*
6067 if (rhsType->getAs<BlockPointerType>()) {
6068 if (lhsPointer->getPointeeType()->isVoidType()) {
6069 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006070 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006071 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006072 }
John McCalle5255932011-01-31 22:28:28 +00006073
Steve Naroff081c7422008-09-04 15:10:53 +00006074 return Incompatible;
6075 }
6076
John McCalle5255932011-01-31 22:28:28 +00006077 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00006078 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006079 // U^ -> T^
6080 if (rhsType->isBlockPointerType()) {
6081 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00006082 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006083 }
6084
6085 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006086 if (rhsType->isIntegerType()) {
6087 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00006088 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006089 }
6090
John McCalle5255932011-01-31 22:28:28 +00006091 // id -> T^
6092 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6093 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006094 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006095 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006096
John McCalle5255932011-01-31 22:28:28 +00006097 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006098 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00006099 if (RHSPT->getPointeeType()->isVoidType()) {
6100 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006101 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006102 }
John McCall8cb679e2010-11-15 09:13:47 +00006103
Chris Lattnera52c2f22008-01-04 23:18:45 +00006104 return Incompatible;
6105 }
6106
John McCalle5255932011-01-31 22:28:28 +00006107 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006108 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006109 // A* -> B*
6110 if (rhsType->isObjCObjectPointerType()) {
6111 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006112 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006113 }
6114
6115 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00006116 if (rhsType->isIntegerType()) {
6117 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00006118 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006119 }
6120
John McCalle5255932011-01-31 22:28:28 +00006121 // In general, C pointers are not compatible with ObjC object pointers,
6122 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00006123 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006124 // - conversions from 'void*'
6125 if (rhsType->isVoidPointerType()) {
6126 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006127 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006128 }
6129
6130 // - conversions to 'Class' from its redefinition type
6131 if (lhsType->isObjCClassType() &&
6132 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6133 Kind = CK_BitCast;
6134 return Compatible;
6135 }
6136
6137 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006138 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006139 }
John McCalle5255932011-01-31 22:28:28 +00006140
6141 // T^ -> A*
6142 if (rhsType->isBlockPointerType()) {
6143 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006144 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006145 }
6146
Steve Naroff7cae42b2009-07-10 23:34:53 +00006147 return Incompatible;
6148 }
John McCalle5255932011-01-31 22:28:28 +00006149
6150 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00006151 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006152 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006153 if (lhsType == Context.BoolTy) {
6154 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00006155 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006156 }
Eli Friedman3360d892008-05-30 18:07:22 +00006157
John McCalle5255932011-01-31 22:28:28 +00006158 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006159 if (lhsType->isIntegerType()) {
6160 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006161 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006162 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006163
Chris Lattnera52c2f22008-01-04 23:18:45 +00006164 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00006165 }
John McCalle5255932011-01-31 22:28:28 +00006166
6167 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006168 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006169 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006170 if (lhsType == Context.BoolTy) {
6171 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006172 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006173 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006174
John McCalle5255932011-01-31 22:28:28 +00006175 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006176 if (lhsType->isIntegerType()) {
6177 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006178 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006179 }
6180
Steve Naroff7cae42b2009-07-10 23:34:53 +00006181 return Incompatible;
6182 }
Eli Friedman3360d892008-05-30 18:07:22 +00006183
John McCalle5255932011-01-31 22:28:28 +00006184 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00006185 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006186 if (Context.typesAreCompatible(lhsType, rhsType)) {
6187 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00006188 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006189 }
Bill Wendling216423b2007-05-30 06:30:29 +00006190 }
John McCalle5255932011-01-31 22:28:28 +00006191
Steve Naroff98cf3e92007-06-06 18:38:38 +00006192 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00006193}
6194
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006195/// \brief Constructs a transparent union from an expression that is
6196/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00006197static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006198 QualType UnionType, FieldDecl *Field) {
6199 // Build an initializer list that designates the appropriate member
6200 // of the transparent union.
Ted Kremenekac034612010-04-13 23:39:13 +00006201 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00006202 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006203 SourceLocation());
6204 Initializer->setType(UnionType);
6205 Initializer->setInitializedFieldInUnion(Field);
6206
6207 // Build a compound literal constructing a value of the transparent
6208 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00006209 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall5d7aa7f2010-01-19 22:33:45 +00006210 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCall7decc9e2010-11-18 06:31:45 +00006211 VK_RValue, Initializer, false);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006212}
6213
6214Sema::AssignConvertType
6215Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
6216 QualType FromType = rExpr->getType();
6217
Mike Stump11289f42009-09-09 15:08:12 +00006218 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006219 // transparent_union GCC extension.
6220 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006221 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006222 return Incompatible;
6223
6224 // The field to initialize within the transparent union.
6225 RecordDecl *UD = UT->getDecl();
6226 FieldDecl *InitField = 0;
6227 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006228 for (RecordDecl::field_iterator it = UD->field_begin(),
6229 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006230 it != itend; ++it) {
6231 if (it->getType()->isPointerType()) {
6232 // If the transparent union contains a pointer type, we allow:
6233 // 1) void pointer
6234 // 2) null pointer constant
6235 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006236 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John McCalle3027922010-08-25 11:45:40 +00006237 ImpCastExprToType(rExpr, it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006238 InitField = *it;
6239 break;
6240 }
Mike Stump11289f42009-09-09 15:08:12 +00006241
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006242 if (rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006243 Expr::NPC_ValueDependentIsNull)) {
John McCalle84af4e2010-11-13 01:35:44 +00006244 ImpCastExprToType(rExpr, it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006245 InitField = *it;
6246 break;
6247 }
6248 }
6249
John McCall29600e12010-11-16 02:32:08 +00006250 Expr *rhs = rExpr;
John McCall8cb679e2010-11-15 09:13:47 +00006251 CastKind Kind = CK_Invalid;
John McCall29600e12010-11-16 02:32:08 +00006252 if (CheckAssignmentConstraints(it->getType(), rhs, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006253 == Compatible) {
John McCall29600e12010-11-16 02:32:08 +00006254 ImpCastExprToType(rhs, it->getType(), Kind);
6255 rExpr = rhs;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006256 InitField = *it;
6257 break;
6258 }
6259 }
6260
6261 if (!InitField)
6262 return Incompatible;
6263
6264 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
6265 return Compatible;
6266}
6267
Chris Lattner9bad62c2008-01-04 18:04:52 +00006268Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006269Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00006270 if (getLangOptions().CPlusPlus) {
6271 if (!lhsType->isRecordType()) {
6272 // C++ 5.17p3: If the left operand is not of class type, the
6273 // expression is implicitly converted (C++ 4) to the
6274 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00006275 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006276 AA_Assigning))
Douglas Gregor9a657932008-10-21 23:43:52 +00006277 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00006278 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00006279 }
6280
6281 // FIXME: Currently, we fall through and treat C++ classes like C
6282 // structures.
John McCall34376a62010-12-04 03:47:34 +00006283 }
Douglas Gregor9a657932008-10-21 23:43:52 +00006284
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006285 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6286 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00006287 if ((lhsType->isPointerType() ||
6288 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00006289 lhsType->isBlockPointerType())
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006290 && rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006291 Expr::NPC_ValueDependentIsNull)) {
John McCall8cb679e2010-11-15 09:13:47 +00006292 ImpCastExprToType(rExpr, lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006293 return Compatible;
6294 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006295
Chris Lattnere6dcd502007-10-16 02:55:40 +00006296 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006297 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00006298 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00006299 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00006300 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00006301 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00006302 if (!lhsType->isReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00006303 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006304
John McCall8cb679e2010-11-15 09:13:47 +00006305 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006306 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00006307 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006308
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006309 // C99 6.5.16.1p2: The value of the right operand is converted to the
6310 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00006311 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6312 // so that we can use references in built-in functions even in C.
6313 // The getNonReferenceType() call makes sure that the resulting expression
6314 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006315 if (result != Incompatible && rExpr->getType() != lhsType)
John McCall8cb679e2010-11-15 09:13:47 +00006316 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006317 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006318}
6319
Chris Lattner326f7572008-11-18 01:30:42 +00006320QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006321 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006322 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00006323 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00006324 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00006325}
6326
Chris Lattnerfaa54172010-01-12 21:23:57 +00006327QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00006328 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006329 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00006330 QualType lhsType =
6331 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
6332 QualType rhsType =
6333 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006334
Nate Begeman191a6b12008-07-14 18:02:46 +00006335 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006336 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00006337 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00006338
Nate Begeman191a6b12008-07-14 18:02:46 +00006339 // Handle the case of a vector & extvector type of the same size and element
6340 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006341 if (getLangOptions().LaxVectorConversions) {
John McCall9dd450b2009-09-21 23:43:11 +00006342 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006343 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006344 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006345 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006346 if (lhsType->isExtVectorType()) {
John McCalle3027922010-08-25 11:45:40 +00006347 ImpCastExprToType(rex, lhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006348 return lhsType;
6349 }
6350
John McCalle3027922010-08-25 11:45:40 +00006351 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006352 return rhsType;
Eric Christophera613f562010-08-26 00:42:16 +00006353 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6354 // If we are allowing lax vector conversions, and LHS and RHS are both
6355 // vectors, the total size only needs to be the same. This is a
6356 // bitcast; no bits are changed but the result type is different.
6357 ImpCastExprToType(rex, lhsType, CK_BitCast);
6358 return lhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006359 }
Eric Christophera613f562010-08-26 00:42:16 +00006360 }
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006361 }
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006362 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006363
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006364 // Handle the case of equivalent AltiVec and GCC vector types
6365 if (lhsType->isVectorType() && rhsType->isVectorType() &&
6366 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John McCalle3027922010-08-25 11:45:40 +00006367 ImpCastExprToType(lex, rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006368 return rhsType;
6369 }
6370
Nate Begemanbd956c42009-06-28 02:36:38 +00006371 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6372 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6373 bool swapped = false;
6374 if (rhsType->isExtVectorType()) {
6375 swapped = true;
6376 std::swap(rex, lex);
6377 std::swap(rhsType, lhsType);
6378 }
Mike Stump11289f42009-09-09 15:08:12 +00006379
Nate Begeman886448d2009-06-28 19:12:57 +00006380 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00006381 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006382 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00006383 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00006384 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6385 if (order > 0)
6386 ImpCastExprToType(rex, EltTy, CK_IntegralCast);
6387 if (order >= 0) {
6388 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006389 if (swapped) std::swap(rex, lex);
6390 return lhsType;
6391 }
6392 }
6393 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6394 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00006395 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6396 if (order > 0)
6397 ImpCastExprToType(rex, EltTy, CK_FloatingCast);
6398 if (order >= 0) {
6399 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006400 if (swapped) std::swap(rex, lex);
6401 return lhsType;
6402 }
Nate Begeman330aaa72007-12-30 02:59:45 +00006403 }
6404 }
Mike Stump11289f42009-09-09 15:08:12 +00006405
Nate Begeman886448d2009-06-28 19:12:57 +00006406 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00006407 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006408 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00006409 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00006410 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00006411}
6412
Chris Lattnerfaa54172010-01-12 21:23:57 +00006413QualType Sema::CheckMultiplyDivideOperands(
6414 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00006415 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006416 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006417
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006418 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006419
Chris Lattnerfaa54172010-01-12 21:23:57 +00006420 if (!lex->getType()->isArithmeticType() ||
6421 !rex->getType()->isArithmeticType())
6422 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006423
Chris Lattnerfaa54172010-01-12 21:23:57 +00006424 // Check for division by zero.
6425 if (isDiv &&
6426 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Ted Kremenek55ae3192011-02-23 01:51:43 +00006427 DiagRuntimeBehavior(Loc, rex, PDiag(diag::warn_division_by_zero)
6428 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006429
Chris Lattnerfaa54172010-01-12 21:23:57 +00006430 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006431}
6432
Chris Lattnerfaa54172010-01-12 21:23:57 +00006433QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00006434 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006435 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006436 if (lex->getType()->hasIntegerRepresentation() &&
6437 rex->getType()->hasIntegerRepresentation())
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006438 return CheckVectorOperands(Loc, lex, rex);
6439 return InvalidOperands(Loc, lex, rex);
6440 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006441
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006442 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006443
Chris Lattnerfaa54172010-01-12 21:23:57 +00006444 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
6445 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006446
Chris Lattnerfaa54172010-01-12 21:23:57 +00006447 // Check for remainder by zero.
6448 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Ted Kremenek55ae3192011-02-23 01:51:43 +00006449 DiagRuntimeBehavior(Loc, rex, PDiag(diag::warn_remainder_by_zero)
6450 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006451
Chris Lattnerfaa54172010-01-12 21:23:57 +00006452 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006453}
6454
Chris Lattnerfaa54172010-01-12 21:23:57 +00006455QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00006456 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006457 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6458 QualType compType = CheckVectorOperands(Loc, lex, rex);
6459 if (CompLHSTy) *CompLHSTy = compType;
6460 return compType;
6461 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006462
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006463 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006464
Steve Naroffe4718892007-04-27 18:30:00 +00006465 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006466 if (lex->getType()->isArithmeticType() &&
6467 rex->getType()->isArithmeticType()) {
6468 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006469 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006470 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006471
Eli Friedman8e122982008-05-18 18:08:51 +00006472 // Put any potential pointer into PExp
6473 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00006474 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006475 std::swap(PExp, IExp);
6476
Steve Naroff6b712a72009-07-14 18:25:06 +00006477 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006478
Eli Friedman8e122982008-05-18 18:08:51 +00006479 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006480 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006481
Chris Lattner12bdebb2009-04-24 23:50:08 +00006482 // Check for arithmetic on pointers to incomplete types.
6483 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006484 if (getLangOptions().CPlusPlus) {
6485 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00006486 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00006487 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006488 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006489
6490 // GNU extension: arithmetic on pointer to void
6491 Diag(Loc, diag::ext_gnu_void_ptr)
6492 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00006493 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006494 if (getLangOptions().CPlusPlus) {
6495 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6496 << lex->getType() << lex->getSourceRange();
6497 return QualType();
6498 }
6499
6500 // GNU extension: arithmetic on pointer to function
6501 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6502 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00006503 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006504 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00006505 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00006506 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006507 PExp->getType()->isObjCObjectPointerType()) &&
6508 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00006509 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6510 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006511 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006512 return QualType();
6513 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00006514 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006515 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006516 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6517 << PointeeTy << PExp->getSourceRange();
6518 return QualType();
6519 }
Mike Stump11289f42009-09-09 15:08:12 +00006520
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006521 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00006522 QualType LHSTy = Context.isPromotableBitField(lex);
6523 if (LHSTy.isNull()) {
6524 LHSTy = lex->getType();
6525 if (LHSTy->isPromotableIntegerType())
6526 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00006527 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006528 *CompLHSTy = LHSTy;
6529 }
Eli Friedman8e122982008-05-18 18:08:51 +00006530 return PExp->getType();
6531 }
6532 }
6533
Chris Lattner326f7572008-11-18 01:30:42 +00006534 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006535}
6536
Chris Lattner2a3569b2008-04-07 05:30:13 +00006537// C99 6.5.6
6538QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006539 SourceLocation Loc, QualType* CompLHSTy) {
6540 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6541 QualType compType = CheckVectorOperands(Loc, lex, rex);
6542 if (CompLHSTy) *CompLHSTy = compType;
6543 return compType;
6544 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006545
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006546 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006547
Chris Lattner4d62f422007-12-09 21:53:25 +00006548 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006549
Chris Lattner4d62f422007-12-09 21:53:25 +00006550 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00006551 if (lex->getType()->isArithmeticType()
6552 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006553 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006554 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006555 }
Mike Stump11289f42009-09-09 15:08:12 +00006556
Chris Lattner4d62f422007-12-09 21:53:25 +00006557 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00006558 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00006559 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006560
Douglas Gregorac1fb652009-03-24 19:52:54 +00006561 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006562
Douglas Gregorac1fb652009-03-24 19:52:54 +00006563 bool ComplainAboutVoid = false;
6564 Expr *ComplainAboutFunc = 0;
6565 if (lpointee->isVoidType()) {
6566 if (getLangOptions().CPlusPlus) {
6567 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6568 << lex->getSourceRange() << rex->getSourceRange();
6569 return QualType();
6570 }
6571
6572 // GNU C extension: arithmetic on pointer to void
6573 ComplainAboutVoid = true;
6574 } else if (lpointee->isFunctionType()) {
6575 if (getLangOptions().CPlusPlus) {
6576 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006577 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006578 return QualType();
6579 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006580
6581 // GNU C extension: arithmetic on pointer to function
6582 ComplainAboutFunc = lex;
6583 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00006584 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006585 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00006586 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006587 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006588 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006589
Chris Lattner12bdebb2009-04-24 23:50:08 +00006590 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006591 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006592 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6593 << lpointee << lex->getSourceRange();
6594 return QualType();
6595 }
Mike Stump11289f42009-09-09 15:08:12 +00006596
Chris Lattner4d62f422007-12-09 21:53:25 +00006597 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00006598 if (rex->getType()->isIntegerType()) {
6599 if (ComplainAboutVoid)
6600 Diag(Loc, diag::ext_gnu_void_ptr)
6601 << lex->getSourceRange() << rex->getSourceRange();
6602 if (ComplainAboutFunc)
6603 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006604 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006605 << ComplainAboutFunc->getSourceRange();
6606
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006607 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006608 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006609 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006610
Chris Lattner4d62f422007-12-09 21:53:25 +00006611 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006612 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006613 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006614
Douglas Gregorac1fb652009-03-24 19:52:54 +00006615 // RHS must be a completely-type object type.
6616 // Handle the GNU void* extension.
6617 if (rpointee->isVoidType()) {
6618 if (getLangOptions().CPlusPlus) {
6619 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6620 << lex->getSourceRange() << rex->getSourceRange();
6621 return QualType();
6622 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006623
Douglas Gregorac1fb652009-03-24 19:52:54 +00006624 ComplainAboutVoid = true;
6625 } else if (rpointee->isFunctionType()) {
6626 if (getLangOptions().CPlusPlus) {
6627 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006628 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006629 return QualType();
6630 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006631
6632 // GNU extension: arithmetic on pointer to function
6633 if (!ComplainAboutFunc)
6634 ComplainAboutFunc = rex;
6635 } else if (!rpointee->isDependentType() &&
6636 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006637 PDiag(diag::err_typecheck_sub_ptr_object)
6638 << rex->getSourceRange()
6639 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006640 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006641
Eli Friedman168fe152009-05-16 13:54:38 +00006642 if (getLangOptions().CPlusPlus) {
6643 // Pointee types must be the same: C++ [expr.add]
6644 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6645 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6646 << lex->getType() << rex->getType()
6647 << lex->getSourceRange() << rex->getSourceRange();
6648 return QualType();
6649 }
6650 } else {
6651 // Pointee types must be compatible C99 6.5.6p3
6652 if (!Context.typesAreCompatible(
6653 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6654 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6655 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6656 << lex->getType() << rex->getType()
6657 << lex->getSourceRange() << rex->getSourceRange();
6658 return QualType();
6659 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006660 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006661
Douglas Gregorac1fb652009-03-24 19:52:54 +00006662 if (ComplainAboutVoid)
6663 Diag(Loc, diag::ext_gnu_void_ptr)
6664 << lex->getSourceRange() << rex->getSourceRange();
6665 if (ComplainAboutFunc)
6666 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006667 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006668 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006669
6670 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006671 return Context.getPointerDiffType();
6672 }
6673 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006674
Chris Lattner326f7572008-11-18 01:30:42 +00006675 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006676}
6677
Douglas Gregor0bf31402010-10-08 23:50:27 +00006678static bool isScopedEnumerationType(QualType T) {
6679 if (const EnumType *ET = dyn_cast<EnumType>(T))
6680 return ET->getDecl()->isScoped();
6681 return false;
6682}
6683
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006684static void DiagnoseBadShiftValues(Sema& S, Expr *&lex, Expr *&rex,
6685 SourceLocation Loc, unsigned Opc,
6686 QualType LHSTy) {
6687 llvm::APSInt Right;
6688 // Check right/shifter operand
6689 if (rex->isValueDependent() || !rex->isIntegerConstantExpr(Right, S.Context))
6690 return;
6691
6692 if (Right.isNegative()) {
Ted Kremenek63657fe2011-03-01 18:09:31 +00006693 S.DiagRuntimeBehavior(Loc, rex,
6694 S.PDiag(diag::warn_shift_negative)
6695 << rex->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006696 return;
6697 }
6698 llvm::APInt LeftBits(Right.getBitWidth(),
6699 S.Context.getTypeSize(lex->getType()));
6700 if (Right.uge(LeftBits)) {
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006701 S.DiagRuntimeBehavior(Loc, rex,
6702 S.PDiag(diag::warn_shift_gt_typewidth)
6703 << rex->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006704 return;
6705 }
6706 if (Opc != BO_Shl)
6707 return;
6708
6709 // When left shifting an ICE which is signed, we can check for overflow which
6710 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6711 // integers have defined behavior modulo one more than the maximum value
6712 // representable in the result type, so never warn for those.
6713 llvm::APSInt Left;
Chandler Carruth60ed89d2011-02-24 00:03:53 +00006714 if (lex->isValueDependent() || !lex->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006715 LHSTy->hasUnsignedIntegerRepresentation())
6716 return;
6717 llvm::APInt ResultBits =
6718 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6719 if (LeftBits.uge(ResultBits))
6720 return;
6721 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6722 Result = Result.shl(Right);
6723
6724 // If we are only missing a sign bit, this is less likely to result in actual
6725 // bugs -- if the result is cast back to an unsigned type, it will have the
6726 // expected value. Thus we place this behind a different warning that can be
6727 // turned off separately if needed.
6728 if (LeftBits == ResultBits - 1) {
6729 S.Diag(Loc, diag::warn_shift_result_overrides_sign_bit)
6730 << Result.toString(10) << LHSTy
6731 << lex->getSourceRange() << rex->getSourceRange();
6732 return;
6733 }
6734
6735 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
6736 << Result.toString(10) << Result.getMinSignedBits() << LHSTy
6737 << Left.getBitWidth() << lex->getSourceRange() << rex->getSourceRange();
6738}
6739
Chris Lattner2a3569b2008-04-07 05:30:13 +00006740// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00006741QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006742 unsigned Opc, bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00006743 // C99 6.5.7p2: Each of the operands shall have integer type.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006744 if (!lex->getType()->hasIntegerRepresentation() ||
6745 !rex->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006746 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006747
Douglas Gregor0bf31402010-10-08 23:50:27 +00006748 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6749 // hasIntegerRepresentation() above instead of this.
6750 if (isScopedEnumerationType(lex->getType()) ||
6751 isScopedEnumerationType(rex->getType())) {
6752 return InvalidOperands(Loc, lex, rex);
6753 }
6754
Nate Begemane46ee9a2009-10-25 02:26:48 +00006755 // Vector shifts promote their scalar inputs to vector type.
6756 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6757 return CheckVectorOperands(Loc, lex, rex);
6758
Chris Lattner5c11c412007-12-12 05:47:28 +00006759 // Shifts don't perform usual arithmetic conversions, they just do integer
6760 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006761
John McCall57cdd882010-12-16 19:28:59 +00006762 // For the LHS, do usual unary conversions, but then reset them away
6763 // if this is a compound assignment.
6764 Expr *old_lex = lex;
6765 UsualUnaryConversions(lex);
6766 QualType LHSTy = lex->getType();
6767 if (isCompAssign) lex = old_lex;
6768
6769 // The RHS is simpler.
Chris Lattner5c11c412007-12-12 05:47:28 +00006770 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006771
Ryan Flynnf53fab82009-08-07 16:20:20 +00006772 // Sanity-check shift operands
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006773 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006774
Chris Lattner5c11c412007-12-12 05:47:28 +00006775 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006776 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006777}
6778
Chandler Carruth17773fc2010-07-10 12:30:03 +00006779static bool IsWithinTemplateSpecialization(Decl *D) {
6780 if (DeclContext *DC = D->getDeclContext()) {
6781 if (isa<ClassTemplateSpecializationDecl>(DC))
6782 return true;
6783 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6784 return FD->isFunctionTemplateSpecialization();
6785 }
6786 return false;
6787}
6788
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006789// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00006790QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006791 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00006792 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006793
Chris Lattner9a152e22009-12-05 05:40:13 +00006794 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00006795 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006796 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006797
Steve Naroff31090012007-07-16 21:54:35 +00006798 QualType lType = lex->getType();
6799 QualType rType = rex->getType();
Douglas Gregor1beec452011-03-12 01:48:56 +00006800
Chandler Carruth712563b2011-02-17 08:37:06 +00006801 Expr *LHSStripped = lex->IgnoreParenImpCasts();
6802 Expr *RHSStripped = rex->IgnoreParenImpCasts();
6803 QualType LHSStrippedType = LHSStripped->getType();
6804 QualType RHSStrippedType = RHSStripped->getType();
6805
Douglas Gregor1beec452011-03-12 01:48:56 +00006806
6807
Chandler Carruth712563b2011-02-17 08:37:06 +00006808 // Two different enums will raise a warning when compared.
6809 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
6810 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
6811 if (LHSEnumType->getDecl()->getIdentifier() &&
6812 RHSEnumType->getDecl()->getIdentifier() &&
6813 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
6814 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6815 << LHSStrippedType << RHSStrippedType
6816 << lex->getSourceRange() << rex->getSourceRange();
6817 }
6818 }
6819 }
6820
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006821 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00006822 !(lType->isBlockPointerType() && isRelational) &&
6823 !lex->getLocStart().isMacroID() &&
6824 !rex->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006825 // For non-floating point types, check for self-comparisons of the form
6826 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6827 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006828 //
6829 // NOTE: Don't warn about comparison expressions resulting from macro
6830 // expansion. Also don't warn about comparisons which are only self
6831 // comparisons within a template specialization. The warnings should catch
6832 // obvious cases in the definition of the template anyways. The idea is to
6833 // warn when the typed comparison operator will always evaluate to the same
6834 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006835 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006836 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006837 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006838 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006839 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006840 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006841 << (Opc == BO_EQ
6842 || Opc == BO_LE
6843 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00006844 } else if (lType->isArrayType() && rType->isArrayType() &&
6845 !DRL->getDecl()->getType()->isReferenceType() &&
6846 !DRR->getDecl()->getType()->isReferenceType()) {
6847 // what is it always going to eval to?
6848 char always_evals_to;
6849 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006850 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006851 always_evals_to = 0; // false
6852 break;
John McCalle3027922010-08-25 11:45:40 +00006853 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006854 always_evals_to = 1; // true
6855 break;
6856 default:
6857 // best we can say is 'a constant'
6858 always_evals_to = 2; // e.g. array1 <= array2
6859 break;
6860 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006861 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006862 << 1 // array
6863 << always_evals_to);
6864 }
6865 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006866 }
Mike Stump11289f42009-09-09 15:08:12 +00006867
Chris Lattner222b8bd2009-03-08 19:39:53 +00006868 if (isa<CastExpr>(LHSStripped))
6869 LHSStripped = LHSStripped->IgnoreParenCasts();
6870 if (isa<CastExpr>(RHSStripped))
6871 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006872
Chris Lattner222b8bd2009-03-08 19:39:53 +00006873 // Warn about comparisons against a string constant (unless the other
6874 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006875 Expr *literalString = 0;
6876 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006877 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006878 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006879 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006880 literalString = lex;
6881 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006882 } else if ((isa<StringLiteral>(RHSStripped) ||
6883 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006884 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006885 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006886 literalString = rex;
6887 literalStringStripped = RHSStripped;
6888 }
6889
6890 if (literalString) {
6891 std::string resultComparison;
6892 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006893 case BO_LT: resultComparison = ") < 0"; break;
6894 case BO_GT: resultComparison = ") > 0"; break;
6895 case BO_LE: resultComparison = ") <= 0"; break;
6896 case BO_GE: resultComparison = ") >= 0"; break;
6897 case BO_EQ: resultComparison = ") == 0"; break;
6898 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006899 default: assert(false && "Invalid comparison operator");
6900 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006901
Ted Kremenek3427fac2011-02-23 01:52:04 +00006902 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006903 PDiag(diag::warn_stringcompare)
6904 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006905 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006906 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006907 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006908
Douglas Gregorec170db2010-06-08 19:50:34 +00006909 // C99 6.5.8p3 / C99 6.5.9p4
6910 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
6911 UsualArithmeticConversions(lex, rex);
6912 else {
6913 UsualUnaryConversions(lex);
6914 UsualUnaryConversions(rex);
6915 }
6916
6917 lType = lex->getType();
6918 rType = rex->getType();
6919
Douglas Gregorca63811b2008-11-19 03:25:36 +00006920 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006921 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006922
Chris Lattnerb620c342007-08-26 01:18:55 +00006923 if (isRelational) {
6924 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006925 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006926 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006927 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006928 if (lType->hasFloatingRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006929 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006930
Chris Lattnerb620c342007-08-26 01:18:55 +00006931 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006932 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006933 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006934
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006935 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006936 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006937 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006938 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006939
Douglas Gregorf267edd2010-06-15 21:38:40 +00006940 // All of the following pointer-related warnings are GCC extensions, except
6941 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00006942 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006943 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006944 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00006945 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006946 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006947
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006948 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006949 if (LCanPointeeTy == RCanPointeeTy)
6950 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006951 if (!isRelational &&
6952 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6953 // Valid unless comparison between non-null pointer and function pointer
6954 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006955 // In a SFINAE context, we treat this as a hard error to maintain
6956 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006957 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6958 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00006959 Diag(Loc,
6960 isSFINAEContext()?
6961 diag::err_typecheck_comparison_of_fptr_to_void
6962 : diag::ext_typecheck_comparison_of_fptr_to_void)
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006963 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006964
6965 if (isSFINAEContext())
6966 return QualType();
6967
John McCalle3027922010-08-25 11:45:40 +00006968 ImpCastExprToType(rex, lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006969 return ResultTy;
6970 }
6971 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006972
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006973 // C++ [expr.rel]p2:
6974 // [...] Pointer conversions (4.10) and qualification
6975 // conversions (4.4) are performed on pointer operands (or on
6976 // a pointer operand and a null pointer constant) to bring
6977 // them to their composite pointer type. [...]
6978 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006979 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006980 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006981 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006982 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006983 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006984 if (T.isNull()) {
6985 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6986 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6987 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006988 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006989 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006990 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006991 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006992 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006993 }
6994
John McCalle3027922010-08-25 11:45:40 +00006995 ImpCastExprToType(lex, T, CK_BitCast);
6996 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006997 return ResultTy;
6998 }
Eli Friedman16c209612009-08-23 00:27:47 +00006999 // C99 6.5.9p2 and C99 6.5.8p2
7000 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7001 RCanPointeeTy.getUnqualifiedType())) {
7002 // Valid unless a relational comparison of function pointers
7003 if (isRelational && LCanPointeeTy->isFunctionType()) {
7004 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7005 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
7006 }
7007 } else if (!isRelational &&
7008 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7009 // Valid unless comparison between non-null pointer and function pointer
7010 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7011 && !LHSIsNull && !RHSIsNull) {
7012 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
7013 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
7014 }
7015 } else {
7016 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00007017 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007018 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00007019 }
John McCall7684dde2011-03-11 04:25:25 +00007020 if (LCanPointeeTy != RCanPointeeTy) {
7021 if (LHSIsNull && !RHSIsNull)
7022 ImpCastExprToType(lex, rType, CK_BitCast);
7023 else
7024 ImpCastExprToType(rex, lType, CK_BitCast);
7025 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00007026 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00007027 }
Mike Stump11289f42009-09-09 15:08:12 +00007028
Sebastian Redl576fd422009-05-10 18:38:11 +00007029 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00007030 // Comparison of nullptr_t with itself.
7031 if (lType->isNullPtrType() && rType->isNullPtrType())
7032 return ResultTy;
7033
Mike Stump11289f42009-09-09 15:08:12 +00007034 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007035 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00007036 if (RHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00007037 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007038 (!isRelational && lType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00007039 ImpCastExprToType(rex, lType,
7040 lType->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 if (LHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00007046 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007047 (!isRelational && rType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00007048 ImpCastExprToType(lex, rType,
7049 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007050 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007051 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007052 return ResultTy;
7053 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007054
7055 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00007056 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007057 lType->isMemberPointerType() && rType->isMemberPointerType()) {
7058 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00007059 // In addition, pointers to members can be compared, or a pointer to
7060 // member and a null pointer constant. Pointer to member conversions
7061 // (4.11) and qualification conversions (4.4) are performed to bring
7062 // them to a common type. If one operand is a null pointer constant,
7063 // the common type is the type of the other operand. Otherwise, the
7064 // common type is a pointer to member type similar (4.4) to the type
7065 // of one of the operands, with a cv-qualification signature (4.4)
7066 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007067 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007068 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00007069 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007070 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007071 if (T.isNull()) {
7072 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007073 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007074 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007075 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007076 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007077 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007078 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007079 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007080 }
Mike Stump11289f42009-09-09 15:08:12 +00007081
John McCalle3027922010-08-25 11:45:40 +00007082 ImpCastExprToType(lex, T, CK_BitCast);
7083 ImpCastExprToType(rex, T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007084 return ResultTy;
7085 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007086
7087 // Handle scoped enumeration types specifically, since they don't promote
7088 // to integers.
7089 if (lex->getType()->isEnumeralType() &&
7090 Context.hasSameUnqualifiedType(lex->getType(), rex->getType()))
7091 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00007092 }
Mike Stump11289f42009-09-09 15:08:12 +00007093
Steve Naroff081c7422008-09-04 15:10:53 +00007094 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00007095 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007096 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
7097 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007098
Steve Naroff081c7422008-09-04 15:10:53 +00007099 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00007100 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007101 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007102 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00007103 }
John McCalle3027922010-08-25 11:45:40 +00007104 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007105 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00007106 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00007107 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00007108 if (!isRelational
7109 && ((lType->isBlockPointerType() && rType->isPointerType())
7110 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00007111 if (!LHSIsNull && !RHSIsNull) {
John McCall7684dde2011-03-11 04:25:25 +00007112 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007113 ->getPointeeType()->isVoidType())
John McCall7684dde2011-03-11 04:25:25 +00007114 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007115 ->getPointeeType()->isVoidType())))
7116 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7117 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00007118 }
John McCall7684dde2011-03-11 04:25:25 +00007119 if (LHSIsNull && !RHSIsNull)
7120 ImpCastExprToType(lex, rType, CK_BitCast);
7121 else
7122 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007123 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00007124 }
Steve Naroff081c7422008-09-04 15:10:53 +00007125
John McCall7684dde2011-03-11 04:25:25 +00007126 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
7127 const PointerType *LPT = lType->getAs<PointerType>();
7128 const PointerType *RPT = rType->getAs<PointerType>();
7129 if (LPT || RPT) {
7130 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7131 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007132
Steve Naroff753567f2008-11-17 19:49:16 +00007133 if (!LPtrToVoid && !RPtrToVoid &&
7134 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007135 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007136 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007137 }
John McCall7684dde2011-03-11 04:25:25 +00007138 if (LHSIsNull && !RHSIsNull)
7139 ImpCastExprToType(lex, rType, CK_BitCast);
7140 else
7141 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007142 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00007143 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007144 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007145 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007146 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
7147 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
John McCall7684dde2011-03-11 04:25:25 +00007148 if (LHSIsNull && !RHSIsNull)
7149 ImpCastExprToType(lex, rType, CK_BitCast);
7150 else
7151 ImpCastExprToType(rex, lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007152 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00007153 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00007154 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007155 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7156 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00007157 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007158 bool isError = false;
7159 if ((LHSIsNull && lType->isIntegerType()) ||
7160 (RHSIsNull && rType->isIntegerType())) {
7161 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007162 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007163 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007164 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007165 else if (getLangOptions().CPlusPlus) {
7166 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7167 isError = true;
7168 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00007169 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00007170
Chris Lattnerd99bd522009-08-23 00:03:44 +00007171 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007172 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00007173 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007174 if (isError)
7175 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00007176 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007177
7178 if (lType->isIntegerType())
John McCalle84af4e2010-11-13 01:35:44 +00007179 ImpCastExprToType(lex, rType,
7180 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00007181 else
John McCalle84af4e2010-11-13 01:35:44 +00007182 ImpCastExprToType(rex, lType,
7183 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007184 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00007185 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007186
Steve Naroff4b191572008-09-04 16:56:14 +00007187 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00007188 if (!isRelational && RHSIsNull
7189 && lType->isBlockPointerType() && rType->isIntegerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00007190 ImpCastExprToType(rex, lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007191 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007192 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00007193 if (!isRelational && LHSIsNull
7194 && lType->isIntegerType() && rType->isBlockPointerType()) {
John McCalle84af4e2010-11-13 01:35:44 +00007195 ImpCastExprToType(lex, rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007196 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007197 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007198
Chris Lattner326f7572008-11-18 01:30:42 +00007199 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007200}
7201
Nate Begeman191a6b12008-07-14 18:02:46 +00007202/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00007203/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00007204/// like a scalar comparison, a vector comparison produces a vector of integer
7205/// types.
7206QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00007207 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00007208 bool isRelational) {
7209 // Check to make sure we're operating on vectors of the same type and width,
7210 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00007211 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00007212 if (vType.isNull())
7213 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007214
Anton Yartsev3f8f2882010-11-18 03:19:30 +00007215 // If AltiVec, the comparison results in a numeric type, i.e.
7216 // bool for C++, int for C
7217 if (getLangOptions().AltiVec)
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007218 return Context.getLogicalOperationType();
Anton Yartsev3f8f2882010-11-18 03:19:30 +00007219
Nate Begeman191a6b12008-07-14 18:02:46 +00007220 QualType lType = lex->getType();
7221 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007222
Nate Begeman191a6b12008-07-14 18:02:46 +00007223 // For non-floating point types, check for self-comparisons of the form
7224 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7225 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007226 if (!lType->hasFloatingRepresentation()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00007227 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
7228 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
7229 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007230 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007231 PDiag(diag::warn_comparison_always)
7232 << 0 // self-
7233 << 2 // "a constant"
7234 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007235 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007236
Nate Begeman191a6b12008-07-14 18:02:46 +00007237 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007238 if (!isRelational && lType->hasFloatingRepresentation()) {
7239 assert (rType->hasFloatingRepresentation());
Chris Lattner326f7572008-11-18 01:30:42 +00007240 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00007241 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007242
Nate Begeman191a6b12008-07-14 18:02:46 +00007243 // Return the type for the comparison, which is the same as vector type for
7244 // integer vectors, or an integer type of identical size and number of
7245 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007246 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00007247 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007248
John McCall9dd450b2009-09-21 23:43:11 +00007249 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00007250 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007251 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00007252 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00007253 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007254 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7255
Mike Stump4e1f26a2009-02-19 03:04:26 +00007256 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007257 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00007258 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7259}
7260
Steve Naroff218bc2b2007-05-04 21:54:46 +00007261inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00007262 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007263 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
7264 if (lex->getType()->hasIntegerRepresentation() &&
7265 rex->getType()->hasIntegerRepresentation())
7266 return CheckVectorOperands(Loc, lex, rex);
7267
7268 return InvalidOperands(Loc, lex, rex);
7269 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007270
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007271 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007272
Douglas Gregor0bf31402010-10-08 23:50:27 +00007273 if (lex->getType()->isIntegralOrUnscopedEnumerationType() &&
7274 rex->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007275 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00007276 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007277}
7278
Steve Naroff218bc2b2007-05-04 21:54:46 +00007279inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner8406c512010-07-13 19:41:32 +00007280 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
7281
7282 // Diagnose cases where the user write a logical and/or but probably meant a
7283 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7284 // is a constant.
7285 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
Eli Friedman6b197e02010-07-27 19:14:53 +00007286 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
Chris Lattnerdeee7a32010-07-15 00:26:43 +00007287 // Don't warn in macros.
Chris Lattner938533d2010-07-24 01:10:11 +00007288 !Loc.isMacroID()) {
7289 // If the RHS can be constant folded, and if it constant folds to something
7290 // that isn't 0 or 1 (which indicate a potential logical operation that
7291 // happened to fold to true/false) then warn.
7292 Expr::EvalResult Result;
7293 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
7294 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
7295 Diag(Loc, diag::warn_logical_instead_of_bitwise)
7296 << rex->getSourceRange()
John McCalle3027922010-08-25 11:45:40 +00007297 << (Opc == BO_LAnd ? "&&" : "||")
7298 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00007299 }
7300 }
Chris Lattner8406c512010-07-13 19:41:32 +00007301
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007302 if (!Context.getLangOptions().CPlusPlus) {
7303 UsualUnaryConversions(lex);
7304 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007305
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007306 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
7307 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007308
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007309 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007310 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007311
John McCall4a2429a2010-06-04 00:29:51 +00007312 // The following is safe because we only use this method for
7313 // non-overloadable operands.
7314
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007315 // C++ [expr.log.and]p1
7316 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007317 // The operands are both contextually converted to type bool.
7318 if (PerformContextuallyConvertToBool(lex) ||
7319 PerformContextuallyConvertToBool(rex))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007320 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007321
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007322 // C++ [expr.log.and]p2
7323 // C++ [expr.log.or]p2
7324 // The result is a bool.
7325 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007326}
7327
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007328/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7329/// is a read-only property; return true if so. A readonly property expression
7330/// depends on various declarations and thus must be treated specially.
7331///
Mike Stump11289f42009-09-09 15:08:12 +00007332static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007333 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7334 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00007335 if (PropExpr->isImplicitProperty()) return false;
7336
7337 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7338 QualType BaseType = PropExpr->isSuperReceiver() ?
7339 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007340 PropExpr->getBase()->getType();
7341
John McCallb7bd14f2010-12-02 01:19:52 +00007342 if (const ObjCObjectPointerType *OPT =
7343 BaseType->getAsObjCInterfacePointerType())
7344 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7345 if (S.isPropertyReadonly(PDecl, IFace))
7346 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007347 }
7348 return false;
7349}
7350
Chris Lattner30bd3272008-11-18 01:22:49 +00007351/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7352/// emit an error and return true. If so, return false.
7353static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007354 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007355 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007356 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007357 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7358 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00007359 if (IsLV == Expr::MLV_Valid)
7360 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007361
Chris Lattner30bd3272008-11-18 01:22:49 +00007362 unsigned Diag = 0;
7363 bool NeedType = false;
7364 switch (IsLV) { // C99 6.5.16p2
Chris Lattner30bd3272008-11-18 01:22:49 +00007365 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007366 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007367 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7368 NeedType = true;
7369 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007370 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007371 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7372 NeedType = true;
7373 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007374 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007375 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7376 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007377 case Expr::MLV_Valid:
7378 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007379 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007380 case Expr::MLV_MemberFunction:
7381 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007382 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7383 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007384 case Expr::MLV_IncompleteType:
7385 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007386 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007387 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00007388 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00007389 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007390 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7391 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00007392 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00007393 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7394 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007395 case Expr::MLV_ReadonlyProperty:
7396 Diag = diag::error_readonly_property_assignment;
7397 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007398 case Expr::MLV_NoSetterProperty:
7399 Diag = diag::error_nosetter_property_assignment;
7400 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007401 case Expr::MLV_SubObjCPropertySetting:
7402 Diag = diag::error_no_subobject_property_setting;
7403 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007404 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007405
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007406 SourceRange Assign;
7407 if (Loc != OrigLoc)
7408 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007409 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007410 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007411 else
Mike Stump11289f42009-09-09 15:08:12 +00007412 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007413 return true;
7414}
7415
7416
7417
7418// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00007419QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
7420 SourceLocation Loc,
7421 QualType CompoundType) {
7422 // Verify that LHS is a modifiable lvalue, and emit error if not.
7423 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007424 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007425
7426 QualType LHSType = LHS->getType();
7427 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007428 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007429 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007430 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007431 // Simple assignment "x = y".
John McCall34376a62010-12-04 03:47:34 +00007432 if (LHS->getObjectKind() == OK_ObjCProperty)
7433 ConvertPropertyForLValue(LHS, RHS, LHSTy);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007434 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007435 // Special case of NSObject attributes on c-style pointer types.
7436 if (ConvTy == IncompatiblePointer &&
7437 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007438 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007439 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007440 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007441 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007442
John McCall7decc9e2010-11-18 06:31:45 +00007443 if (ConvTy == Compatible &&
7444 getLangOptions().ObjCNonFragileABI &&
7445 LHSType->isObjCObjectType())
7446 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7447 << LHSType;
7448
Chris Lattnerea714382008-08-21 18:04:13 +00007449 // If the RHS is a unary plus or minus, check to see if they = and + are
7450 // right next to each other. If so, the user may have typo'd "x =+ 4"
7451 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00007452 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00007453 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7454 RHSCheck = ICE->getSubExpr();
7455 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007456 if ((UO->getOpcode() == UO_Plus ||
7457 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007458 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007459 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00007460 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7461 // And there is a space or other character before the subexpr of the
7462 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00007463 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7464 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007465 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007466 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007467 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007468 }
Chris Lattnerea714382008-08-21 18:04:13 +00007469 }
7470 } else {
7471 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007472 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007473 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007474
Chris Lattner326f7572008-11-18 01:30:42 +00007475 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007476 RHS, AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007477 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007478
Chris Lattner39561062010-07-07 06:14:23 +00007479
7480 // Check to see if the destination operand is a dereferenced null pointer. If
7481 // so, and if not volatile-qualified, this is undefined behavior that the
7482 // optimizer will delete, so warn about it. People sometimes try to use this
7483 // to get a deterministic trap and are surprised by clang's behavior. This
7484 // only handles the pattern "*null = whatever", which is a very syntactic
7485 // check.
7486 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
John McCalle3027922010-08-25 11:45:40 +00007487 if (UO->getOpcode() == UO_Deref &&
Chris Lattner39561062010-07-07 06:14:23 +00007488 UO->getSubExpr()->IgnoreParenCasts()->
7489 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
7490 !UO->getType().isVolatileQualified()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00007491 DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7492 PDiag(diag::warn_indirection_through_null)
7493 << UO->getSubExpr()->getSourceRange());
7494 DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7495 PDiag(diag::note_indirection_through_null));
Chris Lattner39561062010-07-07 06:14:23 +00007496 }
7497
Ted Kremenek64699be2011-02-16 01:57:07 +00007498 // Check for trivial buffer overflows.
Ted Kremenekdf26df72011-03-01 18:41:00 +00007499 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremenek64699be2011-02-16 01:57:07 +00007500
Steve Naroff98cf3e92007-06-06 18:38:38 +00007501 // C99 6.5.16p3: The type of an assignment expression is the type of the
7502 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007503 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007504 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7505 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007506 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007507 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007508 return (getLangOptions().CPlusPlus
7509 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007510}
7511
Chris Lattner326f7572008-11-18 01:30:42 +00007512// C99 6.5.17
John McCall34376a62010-12-04 03:47:34 +00007513static QualType CheckCommaOperands(Sema &S, Expr *&LHS, Expr *&RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007514 SourceLocation Loc) {
7515 S.DiagnoseUnusedExprResult(LHS);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007516
John McCall4bc41ae2010-11-18 19:01:18 +00007517 ExprResult LHSResult = S.CheckPlaceholderExpr(LHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007518 if (LHSResult.isInvalid())
7519 return QualType();
7520
John McCall4bc41ae2010-11-18 19:01:18 +00007521 ExprResult RHSResult = S.CheckPlaceholderExpr(RHS, Loc);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007522 if (RHSResult.isInvalid())
7523 return QualType();
7524 RHS = RHSResult.take();
7525
John McCall73d36182010-10-12 07:14:40 +00007526 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7527 // operands, but not unary promotions.
7528 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007529
John McCall34376a62010-12-04 03:47:34 +00007530 // So we treat the LHS as a ignored value, and in C++ we allow the
7531 // containing site to determine what should be done with the RHS.
7532 S.IgnoredValueConversions(LHS);
7533
7534 if (!S.getLangOptions().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007535 S.DefaultFunctionArrayLvalueConversion(RHS);
John McCall73d36182010-10-12 07:14:40 +00007536 if (!RHS->getType()->isVoidType())
John McCall4bc41ae2010-11-18 19:01:18 +00007537 S.RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007538 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007539
Chris Lattner326f7572008-11-18 01:30:42 +00007540 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007541}
7542
Steve Naroff7a5af782007-07-13 16:58:59 +00007543/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7544/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007545static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7546 ExprValueKind &VK,
7547 SourceLocation OpLoc,
7548 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007549 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007550 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007551
Chris Lattner6b0cf142008-11-21 07:05:48 +00007552 QualType ResType = Op->getType();
7553 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007554
John McCall4bc41ae2010-11-18 19:01:18 +00007555 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007556 // Decrement of bool is not allowed.
7557 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007558 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007559 return QualType();
7560 }
7561 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007562 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007563 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007564 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007565 } else if (ResType->isAnyPointerType()) {
7566 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00007567
Chris Lattner6b0cf142008-11-21 07:05:48 +00007568 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00007569 if (PointeeTy->isVoidType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007570 if (S.getLangOptions().CPlusPlus) {
7571 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007572 << Op->getSourceRange();
7573 return QualType();
7574 }
7575
7576 // Pointer to void is a GNU extension in C.
John McCall4bc41ae2010-11-18 19:01:18 +00007577 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00007578 } else if (PointeeTy->isFunctionType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007579 if (S.getLangOptions().CPlusPlus) {
7580 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007581 << Op->getType() << Op->getSourceRange();
7582 return QualType();
7583 }
7584
John McCall4bc41ae2010-11-18 19:01:18 +00007585 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007586 << ResType << Op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007587 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
7588 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00007589 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00007590 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00007591 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007592 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00007593 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7594 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007595 << PointeeTy << Op->getSourceRange();
7596 return QualType();
7597 }
Eli Friedman090addd2010-01-03 00:20:48 +00007598 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007599 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007600 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007601 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007602 } else if (ResType->isPlaceholderType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007603 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007604 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007605 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7606 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00007607 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7608 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007609 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007610 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00007611 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007612 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007613 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007614 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007615 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007616 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007617 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007618 // In C++, a prefix increment is the same type as the operand. Otherwise
7619 // (in C or with postfix), the increment is the unqualified type of the
7620 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00007621 if (isPrefix && S.getLangOptions().CPlusPlus) {
7622 VK = VK_LValue;
7623 return ResType;
7624 } else {
7625 VK = VK_RValue;
7626 return ResType.getUnqualifiedType();
7627 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007628}
7629
John McCall34376a62010-12-04 03:47:34 +00007630void Sema::ConvertPropertyForRValue(Expr *&E) {
7631 assert(E->getValueKind() == VK_LValue &&
7632 E->getObjectKind() == OK_ObjCProperty);
7633 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7634
7635 ExprValueKind VK = VK_RValue;
7636 if (PRE->isImplicitProperty()) {
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007637 if (const ObjCMethodDecl *GetterMethod =
7638 PRE->getImplicitPropertyGetter()) {
7639 QualType Result = GetterMethod->getResultType();
7640 VK = Expr::getValueKindForType(Result);
7641 }
7642 else {
7643 Diag(PRE->getLocation(), diag::err_getter_not_found)
7644 << PRE->getBase()->getType();
7645 }
John McCall34376a62010-12-04 03:47:34 +00007646 }
7647
7648 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
7649 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007650
7651 ExprResult Result = MaybeBindToTemporary(E);
7652 if (!Result.isInvalid())
7653 E = Result.take();
John McCall34376a62010-12-04 03:47:34 +00007654}
7655
7656void Sema::ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType &LHSTy) {
7657 assert(LHS->getValueKind() == VK_LValue &&
7658 LHS->getObjectKind() == OK_ObjCProperty);
7659 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7660
7661 if (PRE->isImplicitProperty()) {
7662 // If using property-dot syntax notation for assignment, and there is a
7663 // setter, RHS expression is being passed to the setter argument. So,
7664 // type conversion (and comparison) is RHS to setter's argument type.
7665 if (const ObjCMethodDecl *SetterMD = PRE->getImplicitPropertySetter()) {
7666 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7667 LHSTy = (*P)->getType();
7668
7669 // Otherwise, if the getter returns an l-value, just call that.
7670 } else {
7671 QualType Result = PRE->getImplicitPropertyGetter()->getResultType();
7672 ExprValueKind VK = Expr::getValueKindForType(Result);
7673 if (VK == VK_LValue) {
7674 LHS = ImplicitCastExpr::Create(Context, LHS->getType(),
7675 CK_GetObjCProperty, LHS, 0, VK);
7676 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007677 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007678 }
John McCall34376a62010-12-04 03:47:34 +00007679 }
7680
7681 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007682 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007683 InitializedEntity::InitializeParameter(Context, LHSTy);
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007684 Expr *Arg = RHS;
7685 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(),
7686 Owned(Arg));
7687 if (!ArgE.isInvalid())
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007688 RHS = ArgE.takeAs<Expr>();
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007689 }
7690}
7691
7692
Anders Carlsson806700f2008-02-01 07:15:58 +00007693/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007694/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007695/// where the declaration is needed for type checking. We only need to
7696/// handle cases when the expression references a function designator
7697/// or is an lvalue. Here are some examples:
7698/// - &(x) => x
7699/// - &*****f => f for f a function designator.
7700/// - &s.xx => s
7701/// - &s.zz[1].yy -> s, if zz is an array
7702/// - *(x + 1) -> x, if x is an array
7703/// - &"123"[2] -> 0
7704/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007705static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007706 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007707 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007708 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007709 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007710 // If this is an arrow operator, the address is an offset from
7711 // the base's value, so the object the base refers to is
7712 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007713 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007714 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007715 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007716 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007717 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007718 // FIXME: This code shouldn't be necessary! We should catch the implicit
7719 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007720 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7721 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7722 if (ICE->getSubExpr()->getType()->isArrayType())
7723 return getPrimaryDecl(ICE->getSubExpr());
7724 }
7725 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007726 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007727 case Stmt::UnaryOperatorClass: {
7728 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007729
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007730 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007731 case UO_Real:
7732 case UO_Imag:
7733 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007734 return getPrimaryDecl(UO->getSubExpr());
7735 default:
7736 return 0;
7737 }
7738 }
Steve Naroff47500512007-04-19 23:00:49 +00007739 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007740 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007741 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007742 // If the result of an implicit cast is an l-value, we care about
7743 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007744 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007745 default:
7746 return 0;
7747 }
7748}
7749
7750/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007751/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007752/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007753/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007754/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007755/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007756/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007757static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7758 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007759 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007760 return S.Context.DependentTy;
7761 if (OrigOp->getType() == S.Context.OverloadTy)
7762 return S.Context.OverloadTy;
John McCall8d08b9b2010-08-27 09:08:28 +00007763
John McCall4bc41ae2010-11-18 19:01:18 +00007764 ExprResult PR = S.CheckPlaceholderExpr(OrigOp, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007765 if (PR.isInvalid()) return QualType();
7766 OrigOp = PR.take();
7767
John McCall8d08b9b2010-08-27 09:08:28 +00007768 // Make sure to ignore parentheses in subsequent checks
7769 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007770
John McCall4bc41ae2010-11-18 19:01:18 +00007771 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007772 // Implement C99-only parts of addressof rules.
7773 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007774 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007775 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7776 // (assuming the deref expression is valid).
7777 return uOp->getSubExpr()->getType();
7778 }
7779 // Technically, there should be a check for array subscript
7780 // expressions here, but the result of one is always an lvalue anyway.
7781 }
John McCallf3a88602011-02-03 08:15:49 +00007782 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007783 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00007784
Chris Lattner9156f1b2010-07-05 19:17:26 +00007785 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007786 bool sfinae = S.isSFINAEContext();
7787 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7788 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007789 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007790 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007791 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007792 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007793 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007794 } else if (lval == Expr::LV_MemberFunction) {
7795 // If it's an instance method, make a member pointer.
7796 // The expression must have exactly the form &A::foo.
7797
7798 // If the underlying expression isn't a decl ref, give up.
7799 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007800 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007801 << OrigOp->getSourceRange();
7802 return QualType();
7803 }
7804 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7805 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7806
7807 // The id-expression was parenthesized.
7808 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007809 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007810 << OrigOp->getSourceRange();
7811
7812 // The method was named without a qualifier.
7813 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007814 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007815 << op->getSourceRange();
7816 }
7817
John McCall4bc41ae2010-11-18 19:01:18 +00007818 return S.Context.getMemberPointerType(op->getType(),
7819 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007820 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007821 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007822 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007823 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007824 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007825 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007826 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007827 return QualType();
7828 }
John McCall086a4642010-11-24 05:12:34 +00007829 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007830 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00007831 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00007832 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00007833 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007834 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007835 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00007836 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00007837 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007838 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007839 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007840 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00007841 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00007842 << "property expression" << op->getSourceRange();
7843 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007844 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007845 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007846 // with the register storage-class specifier.
7847 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007848 // in C++ it is not error to take address of a register
7849 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007850 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007851 !S.getLangOptions().CPlusPlus) {
7852 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00007853 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007854 return QualType();
7855 }
John McCalld14a8642009-11-21 08:51:07 +00007856 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007857 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007858 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007859 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007860 // Could be a pointer to member, though, if there is an explicit
7861 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007862 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007863 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007864 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007865 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007866 S.Diag(OpLoc,
7867 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007868 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007869 return QualType();
7870 }
Mike Stump11289f42009-09-09 15:08:12 +00007871
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007872 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7873 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007874 return S.Context.getMemberPointerType(op->getType(),
7875 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007876 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007877 }
Anders Carlsson5b535762009-05-16 21:43:42 +00007878 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00007879 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007880 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007881
Eli Friedmance7f9002009-05-16 23:27:50 +00007882 if (lval == Expr::LV_IncompleteVoidType) {
7883 // Taking the address of a void variable is technically illegal, but we
7884 // allow it in cases which are otherwise valid.
7885 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007886 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007887 }
7888
Steve Naroff47500512007-04-19 23:00:49 +00007889 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007890 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007891 return S.Context.getObjCObjectPointerType(op->getType());
7892 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007893}
7894
Chris Lattner9156f1b2010-07-05 19:17:26 +00007895/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007896static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7897 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007898 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007899 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007900
John McCall4bc41ae2010-11-18 19:01:18 +00007901 S.UsualUnaryConversions(Op);
Chris Lattner9156f1b2010-07-05 19:17:26 +00007902 QualType OpTy = Op->getType();
7903 QualType Result;
7904
7905 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7906 // is an incomplete type or void. It would be possible to warn about
7907 // dereferencing a void pointer, but it's completely well-defined, and such a
7908 // warning is unlikely to catch any mistakes.
7909 if (const PointerType *PT = OpTy->getAs<PointerType>())
7910 Result = PT->getPointeeType();
7911 else if (const ObjCObjectPointerType *OPT =
7912 OpTy->getAs<ObjCObjectPointerType>())
7913 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007914 else {
John McCall4bc41ae2010-11-18 19:01:18 +00007915 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007916 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007917 if (PR.take() != Op)
7918 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007919 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007920
Chris Lattner9156f1b2010-07-05 19:17:26 +00007921 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007922 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007923 << OpTy << Op->getSourceRange();
7924 return QualType();
7925 }
John McCall4bc41ae2010-11-18 19:01:18 +00007926
7927 // Dereferences are usually l-values...
7928 VK = VK_LValue;
7929
7930 // ...except that certain expressions are never l-values in C.
7931 if (!S.getLangOptions().CPlusPlus &&
7932 IsCForbiddenLValueType(S.Context, Result))
7933 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007934
7935 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007936}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007937
John McCalle3027922010-08-25 11:45:40 +00007938static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007939 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007940 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007941 switch (Kind) {
7942 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007943 case tok::periodstar: Opc = BO_PtrMemD; break;
7944 case tok::arrowstar: Opc = BO_PtrMemI; break;
7945 case tok::star: Opc = BO_Mul; break;
7946 case tok::slash: Opc = BO_Div; break;
7947 case tok::percent: Opc = BO_Rem; break;
7948 case tok::plus: Opc = BO_Add; break;
7949 case tok::minus: Opc = BO_Sub; break;
7950 case tok::lessless: Opc = BO_Shl; break;
7951 case tok::greatergreater: Opc = BO_Shr; break;
7952 case tok::lessequal: Opc = BO_LE; break;
7953 case tok::less: Opc = BO_LT; break;
7954 case tok::greaterequal: Opc = BO_GE; break;
7955 case tok::greater: Opc = BO_GT; break;
7956 case tok::exclaimequal: Opc = BO_NE; break;
7957 case tok::equalequal: Opc = BO_EQ; break;
7958 case tok::amp: Opc = BO_And; break;
7959 case tok::caret: Opc = BO_Xor; break;
7960 case tok::pipe: Opc = BO_Or; break;
7961 case tok::ampamp: Opc = BO_LAnd; break;
7962 case tok::pipepipe: Opc = BO_LOr; break;
7963 case tok::equal: Opc = BO_Assign; break;
7964 case tok::starequal: Opc = BO_MulAssign; break;
7965 case tok::slashequal: Opc = BO_DivAssign; break;
7966 case tok::percentequal: Opc = BO_RemAssign; break;
7967 case tok::plusequal: Opc = BO_AddAssign; break;
7968 case tok::minusequal: Opc = BO_SubAssign; break;
7969 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7970 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7971 case tok::ampequal: Opc = BO_AndAssign; break;
7972 case tok::caretequal: Opc = BO_XorAssign; break;
7973 case tok::pipeequal: Opc = BO_OrAssign; break;
7974 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007975 }
7976 return Opc;
7977}
7978
John McCalle3027922010-08-25 11:45:40 +00007979static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007980 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007981 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007982 switch (Kind) {
7983 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007984 case tok::plusplus: Opc = UO_PreInc; break;
7985 case tok::minusminus: Opc = UO_PreDec; break;
7986 case tok::amp: Opc = UO_AddrOf; break;
7987 case tok::star: Opc = UO_Deref; break;
7988 case tok::plus: Opc = UO_Plus; break;
7989 case tok::minus: Opc = UO_Minus; break;
7990 case tok::tilde: Opc = UO_Not; break;
7991 case tok::exclaim: Opc = UO_LNot; break;
7992 case tok::kw___real: Opc = UO_Real; break;
7993 case tok::kw___imag: Opc = UO_Imag; break;
7994 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007995 }
7996 return Opc;
7997}
7998
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007999/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8000/// This warning is only emitted for builtin assignment operations. It is also
8001/// suppressed in the event of macro expansions.
8002static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
8003 SourceLocation OpLoc) {
8004 if (!S.ActiveTemplateInstantiations.empty())
8005 return;
8006 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8007 return;
8008 lhs = lhs->IgnoreParenImpCasts();
8009 rhs = rhs->IgnoreParenImpCasts();
8010 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
8011 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
8012 if (!LeftDeclRef || !RightDeclRef ||
8013 LeftDeclRef->getLocation().isMacroID() ||
8014 RightDeclRef->getLocation().isMacroID())
8015 return;
8016 const ValueDecl *LeftDecl =
8017 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
8018 const ValueDecl *RightDecl =
8019 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
8020 if (LeftDecl != RightDecl)
8021 return;
8022 if (LeftDecl->getType().isVolatileQualified())
8023 return;
8024 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
8025 if (RefTy->getPointeeType().isVolatileQualified())
8026 return;
8027
8028 S.Diag(OpLoc, diag::warn_self_assignment)
8029 << LeftDeclRef->getType()
8030 << lhs->getSourceRange() << rhs->getSourceRange();
8031}
8032
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008033/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8034/// operator @p Opc at location @c TokLoc. This routine only supports
8035/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00008036ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008037 BinaryOperatorKind Opc,
John McCalle3027922010-08-25 11:45:40 +00008038 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008039 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008040 // The following two variables are used for compound assignment operators
8041 QualType CompLHSTy; // Type of LHS after promotions for computation
8042 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00008043 ExprValueKind VK = VK_RValue;
8044 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008045
Douglas Gregor1beec452011-03-12 01:48:56 +00008046 // Check if a 'foo<int>' involved in a binary op, identifies a single
8047 // function unambiguously (i.e. an lvalue ala 13.4)
8048 // But since an assignment can trigger target based overload, exclude it in
8049 // our blind search. i.e:
8050 // template<class T> void f(); template<class T, class U> void f(U);
8051 // f<int> == 0; // resolve f<int> blindly
8052 // void (*p)(int); p = f<int>; // resolve f<int> using target
8053 if (Opc != BO_Assign) {
8054 if (lhs->getType() == Context.OverloadTy) {
8055 ExprResult resolvedLHS =
8056 ResolveAndFixSingleFunctionTemplateSpecialization(lhs);
8057 if (resolvedLHS.isUsable()) lhs = resolvedLHS.release();
8058 }
8059 if (rhs->getType() == Context.OverloadTy) {
8060 ExprResult resolvedRHS =
8061 ResolveAndFixSingleFunctionTemplateSpecialization(rhs);
8062 if (resolvedRHS.isUsable()) rhs = resolvedRHS.release();
8063 }
8064 }
8065
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008066 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008067 case BO_Assign:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008068 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00008069 if (getLangOptions().CPlusPlus &&
8070 lhs->getObjectKind() != OK_ObjCProperty) {
John McCall4bc41ae2010-11-18 19:01:18 +00008071 VK = lhs->getValueKind();
8072 OK = lhs->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008073 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008074 if (!ResultTy.isNull())
8075 DiagnoseSelfAssignment(*this, lhs, rhs, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008076 break;
John McCalle3027922010-08-25 11:45:40 +00008077 case BO_PtrMemD:
8078 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00008079 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008080 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00008081 break;
John McCalle3027922010-08-25 11:45:40 +00008082 case BO_Mul:
8083 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00008084 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00008085 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008086 break;
John McCalle3027922010-08-25 11:45:40 +00008087 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008088 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
8089 break;
John McCalle3027922010-08-25 11:45:40 +00008090 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008091 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
8092 break;
John McCalle3027922010-08-25 11:45:40 +00008093 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008094 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
8095 break;
John McCalle3027922010-08-25 11:45:40 +00008096 case BO_Shl:
8097 case BO_Shr:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008098 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008099 break;
John McCalle3027922010-08-25 11:45:40 +00008100 case BO_LE:
8101 case BO_LT:
8102 case BO_GE:
8103 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008104 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008105 break;
John McCalle3027922010-08-25 11:45:40 +00008106 case BO_EQ:
8107 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008108 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008109 break;
John McCalle3027922010-08-25 11:45:40 +00008110 case BO_And:
8111 case BO_Xor:
8112 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008113 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
8114 break;
John McCalle3027922010-08-25 11:45:40 +00008115 case BO_LAnd:
8116 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00008117 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008118 break;
John McCalle3027922010-08-25 11:45:40 +00008119 case BO_MulAssign:
8120 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00008121 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00008122 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008123 CompLHSTy = CompResultTy;
8124 if (!CompResultTy.isNull())
8125 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008126 break;
John McCalle3027922010-08-25 11:45:40 +00008127 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008128 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
8129 CompLHSTy = CompResultTy;
8130 if (!CompResultTy.isNull())
8131 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008132 break;
John McCalle3027922010-08-25 11:45:40 +00008133 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008134 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
8135 if (!CompResultTy.isNull())
8136 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008137 break;
John McCalle3027922010-08-25 11:45:40 +00008138 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008139 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
8140 if (!CompResultTy.isNull())
8141 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008142 break;
John McCalle3027922010-08-25 11:45:40 +00008143 case BO_ShlAssign:
8144 case BO_ShrAssign:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008145 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008146 CompLHSTy = CompResultTy;
8147 if (!CompResultTy.isNull())
8148 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008149 break;
John McCalle3027922010-08-25 11:45:40 +00008150 case BO_AndAssign:
8151 case BO_XorAssign:
8152 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008153 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
8154 CompLHSTy = CompResultTy;
8155 if (!CompResultTy.isNull())
8156 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008157 break;
John McCalle3027922010-08-25 11:45:40 +00008158 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00008159 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John McCall7decc9e2010-11-18 06:31:45 +00008160 if (getLangOptions().CPlusPlus) {
8161 VK = rhs->getValueKind();
8162 OK = rhs->getObjectKind();
8163 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008164 break;
8165 }
8166 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00008167 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008168 if (CompResultTy.isNull())
John McCall7decc9e2010-11-18 06:31:45 +00008169 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy,
8170 VK, OK, OpLoc));
8171
John McCall34376a62010-12-04 03:47:34 +00008172 if (getLangOptions().CPlusPlus && lhs->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00008173 VK = VK_LValue;
8174 OK = lhs->getObjectKind();
8175 }
8176 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
8177 VK, OK, CompLHSTy,
8178 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008179}
8180
Sebastian Redl44615072009-10-27 12:10:02 +00008181/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
8182/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008183static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8184 const PartialDiagnostic &PD,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008185 const PartialDiagnostic &FirstNote,
8186 SourceRange FirstParenRange,
8187 const PartialDiagnostic &SecondNote,
Douglas Gregor89336232010-03-29 23:34:08 +00008188 SourceRange SecondParenRange) {
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008189 Self.Diag(Loc, PD);
8190
8191 if (!FirstNote.getDiagID())
8192 return;
8193
8194 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
8195 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8196 // We can't display the parentheses, so just return.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008197 return;
8198 }
8199
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008200 Self.Diag(Loc, FirstNote)
8201 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregora771f462010-03-31 17:46:05 +00008202 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008203
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008204 if (!SecondNote.getDiagID())
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008205 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008206
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008207 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
8208 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8209 // We can't display the parentheses, so just dig the
8210 // warning/error and return.
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008211 Self.Diag(Loc, SecondNote);
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008212 return;
8213 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008214
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008215 Self.Diag(Loc, SecondNote)
Douglas Gregora771f462010-03-31 17:46:05 +00008216 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
8217 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008218}
8219
Sebastian Redl44615072009-10-27 12:10:02 +00008220/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8221/// operators are mixed in a way that suggests that the programmer forgot that
8222/// comparison operators have higher precedence. The most typical example of
8223/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00008224static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00008225 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00008226 typedef BinaryOperator BinOp;
8227 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
8228 rhsopc = static_cast<BinOp::Opcode>(-1);
8229 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008230 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00008231 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008232 rhsopc = BO->getOpcode();
8233
8234 // Subs are not binary operators.
8235 if (lhsopc == -1 && rhsopc == -1)
8236 return;
8237
8238 // Bitwise operations are sometimes used as eager logical ops.
8239 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00008240 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
8241 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00008242 return;
8243
Sebastian Redl44615072009-10-27 12:10:02 +00008244 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008245 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008246 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008247 << SourceRange(lhs->getLocStart(), OpLoc)
8248 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00008249 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008250 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008251 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
8252 Self.PDiag(diag::note_precedence_bitwise_silence)
8253 << BinOp::getOpcodeStr(lhsopc),
8254 lhs->getSourceRange());
Sebastian Redl44615072009-10-27 12:10:02 +00008255 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008256 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008257 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008258 << SourceRange(OpLoc, rhs->getLocEnd())
8259 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00008260 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008261 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008262 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
8263 Self.PDiag(diag::note_precedence_bitwise_silence)
8264 << BinOp::getOpcodeStr(rhsopc),
8265 rhs->getSourceRange());
Sebastian Redl43028242009-10-26 15:24:15 +00008266}
8267
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008268/// \brief It accepts a '&&' expr that is inside a '||' one.
8269/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8270/// in parentheses.
8271static void
8272EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8273 Expr *E) {
8274 assert(isa<BinaryOperator>(E) &&
8275 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
8276 SuggestParentheses(Self, OpLoc,
8277 Self.PDiag(diag::warn_logical_and_in_logical_or)
8278 << E->getSourceRange(),
8279 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
8280 E->getSourceRange(),
8281 Self.PDiag(0), SourceRange());
8282}
8283
8284/// \brief Returns true if the given expression can be evaluated as a constant
8285/// 'true'.
8286static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8287 bool Res;
8288 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8289}
8290
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008291/// \brief Returns true if the given expression can be evaluated as a constant
8292/// 'false'.
8293static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8294 bool Res;
8295 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8296}
8297
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008298/// \brief Look for '&&' in the left hand of a '||' expr.
8299static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008300 Expr *OrLHS, Expr *OrRHS) {
8301 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008302 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008303 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8304 if (EvaluatesAsFalse(S, OrRHS))
8305 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008306 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8307 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8308 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8309 } else if (Bop->getOpcode() == BO_LOr) {
8310 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8311 // If it's "a || b && 1 || c" we didn't warn earlier for
8312 // "a || b && 1", but warn now.
8313 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8314 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8315 }
8316 }
8317 }
8318}
8319
8320/// \brief Look for '&&' in the right hand of a '||' expr.
8321static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008322 Expr *OrLHS, Expr *OrRHS) {
8323 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008324 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008325 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8326 if (EvaluatesAsFalse(S, OrLHS))
8327 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008328 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8329 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8330 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008331 }
8332 }
8333}
8334
Sebastian Redl43028242009-10-26 15:24:15 +00008335/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008336/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008337static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00008338 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008339 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008340 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008341 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
8342
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008343 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8344 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008345 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008346 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
8347 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008348 }
Sebastian Redl43028242009-10-26 15:24:15 +00008349}
8350
Steve Naroff218bc2b2007-05-04 21:54:46 +00008351// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008352ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008353 tok::TokenKind Kind,
8354 Expr *lhs, Expr *rhs) {
8355 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00008356 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8357 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008358
Sebastian Redl43028242009-10-26 15:24:15 +00008359 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8360 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8361
Douglas Gregor5287f092009-11-05 00:51:44 +00008362 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8363}
8364
John McCalldadc5752010-08-24 06:29:42 +00008365ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008366 BinaryOperatorKind Opc,
8367 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00008368 if (getLangOptions().CPlusPlus) {
8369 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008370
John McCall622114c2010-12-06 05:26:58 +00008371 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8372 UseBuiltinOperator = false;
8373 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8374 UseBuiltinOperator = true;
8375 } else {
8376 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8377 !rhs->getType()->isOverloadableType();
8378 }
8379
8380 if (!UseBuiltinOperator) {
8381 // Find all of the overloaded operators visible from this
8382 // point. We perform both an operator-name lookup from the local
8383 // scope and an argument-dependent lookup based on the types of
8384 // the arguments.
8385 UnresolvedSet<16> Functions;
8386 OverloadedOperatorKind OverOp
8387 = BinaryOperator::getOverloadedOperator(Opc);
8388 if (S && OverOp != OO_None)
8389 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8390 Functions);
8391
8392 // Build the (potentially-overloaded, potentially-dependent)
8393 // binary operation.
8394 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8395 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00008396 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008397
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008398 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00008399 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008400}
8401
John McCalldadc5752010-08-24 06:29:42 +00008402ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008403 UnaryOperatorKind Opc,
John McCall36226622010-10-12 02:09:17 +00008404 Expr *Input) {
John McCall7decc9e2010-11-18 06:31:45 +00008405 ExprValueKind VK = VK_RValue;
8406 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008407 QualType resultType;
8408 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008409 case UO_PreInc:
8410 case UO_PreDec:
8411 case UO_PostInc:
8412 case UO_PostDec:
John McCall4bc41ae2010-11-18 19:01:18 +00008413 resultType = CheckIncrementDecrementOperand(*this, Input, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008414 Opc == UO_PreInc ||
8415 Opc == UO_PostInc,
8416 Opc == UO_PreInc ||
8417 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008418 break;
John McCalle3027922010-08-25 11:45:40 +00008419 case UO_AddrOf:
John McCall4bc41ae2010-11-18 19:01:18 +00008420 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008421 break;
John McCalle3027922010-08-25 11:45:40 +00008422 case UO_Deref:
Douglas Gregor1beec452011-03-12 01:48:56 +00008423 if (Input->getType() == Context.OverloadTy ) {
8424 ExprResult er = ResolveAndFixSingleFunctionTemplateSpecialization(Input);
8425 if (er.isUsable())
8426 Input = er.release();
8427 }
Douglas Gregorb92a1562010-02-03 00:27:59 +00008428 DefaultFunctionArrayLvalueConversion(Input);
John McCall4bc41ae2010-11-18 19:01:18 +00008429 resultType = CheckIndirectionOperand(*this, Input, VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008430 break;
John McCalle3027922010-08-25 11:45:40 +00008431 case UO_Plus:
8432 case UO_Minus:
Steve Naroff31090012007-07-16 21:54:35 +00008433 UsualUnaryConversions(Input);
8434 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008435 if (resultType->isDependentType())
8436 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008437 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8438 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008439 break;
8440 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8441 resultType->isEnumeralType())
8442 break;
8443 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008444 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008445 resultType->isPointerType())
8446 break;
John McCall36226622010-10-12 02:09:17 +00008447 else if (resultType->isPlaceholderType()) {
8448 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8449 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008450 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00008451 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008452
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008453 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8454 << resultType << Input->getSourceRange());
John McCalle3027922010-08-25 11:45:40 +00008455 case UO_Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00008456 UsualUnaryConversions(Input);
8457 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008458 if (resultType->isDependentType())
8459 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008460 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8461 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8462 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008463 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008464 << resultType << Input->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008465 else if (resultType->hasIntegerRepresentation())
8466 break;
8467 else if (resultType->isPlaceholderType()) {
8468 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8469 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008470 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00008471 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008472 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8473 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008474 }
Steve Naroff35d85152007-05-07 00:24:15 +00008475 break;
John McCalle3027922010-08-25 11:45:40 +00008476 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008477 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregorb92a1562010-02-03 00:27:59 +00008478 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroff31090012007-07-16 21:54:35 +00008479 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008480 if (resultType->isDependentType())
8481 break;
John McCall36226622010-10-12 02:09:17 +00008482 if (resultType->isScalarType()) { // C99 6.5.3.3p1
8483 // ok, fallthrough
8484 } else if (resultType->isPlaceholderType()) {
8485 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8486 if (PR.isInvalid()) return ExprError();
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008487 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
John McCall36226622010-10-12 02:09:17 +00008488 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008489 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8490 << resultType << Input->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008491 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008492
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008493 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008494 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008495 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008496 break;
John McCalle3027922010-08-25 11:45:40 +00008497 case UO_Real:
8498 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008499 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00008500 // _Real and _Imag map ordinary l-values into ordinary l-values.
8501 if (Input->getValueKind() != VK_RValue &&
8502 Input->getObjectKind() == OK_Ordinary)
8503 VK = Input->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00008504 break;
John McCalle3027922010-08-25 11:45:40 +00008505 case UO_Extension:
Chris Lattner86554282007-06-08 22:32:33 +00008506 resultType = Input->getType();
John McCall7decc9e2010-11-18 06:31:45 +00008507 VK = Input->getValueKind();
8508 OK = Input->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008509 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008510 }
8511 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008512 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008513
John McCall7decc9e2010-11-18 06:31:45 +00008514 return Owned(new (Context) UnaryOperator(Input, Opc, resultType,
8515 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008516}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008517
John McCalldadc5752010-08-24 06:29:42 +00008518ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008519 UnaryOperatorKind Opc,
8520 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00008521 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00008522 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008523 // Find all of the overloaded operators visible from this
8524 // point. We perform both an operator-name lookup from the local
8525 // scope and an argument-dependent lookup based on the types of
8526 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008527 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008528 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008529 if (S && OverOp != OO_None)
8530 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8531 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008532
John McCallb268a282010-08-23 23:25:46 +00008533 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008534 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008535
John McCallb268a282010-08-23 23:25:46 +00008536 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008537}
8538
Douglas Gregor5287f092009-11-05 00:51:44 +00008539// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008540ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008541 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008542 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008543}
8544
Steve Naroff66356bd2007-09-16 14:56:35 +00008545/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008546ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008547 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008548 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008549 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008550 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008551 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008552}
8553
John McCalldadc5752010-08-24 06:29:42 +00008554ExprResult
John McCallb268a282010-08-23 23:25:46 +00008555Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008556 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008557 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8558 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8559
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008560 bool isFileScope
8561 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008562 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008563 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008564
Chris Lattner366727f2007-07-24 16:58:17 +00008565 // FIXME: there are a variety of strange constraints to enforce here, for
8566 // example, it is not possible to goto into a stmt expression apparently.
8567 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008568
Chris Lattner366727f2007-07-24 16:58:17 +00008569 // If there are sub stmts in the compound stmt, take the type of the last one
8570 // as the type of the stmtexpr.
8571 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008572 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008573 if (!Compound->body_empty()) {
8574 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008575 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008576 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008577 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8578 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008579 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008580 }
8581 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008582 // Do function/array conversion on the last expression, but not
8583 // lvalue-to-rvalue. However, initialize an unqualified type.
8584 DefaultFunctionArrayConversion(LastExpr);
8585 Ty = LastExpr->getType().getUnqualifiedType();
8586
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008587 if (!Ty->isDependentType() && !LastExpr->isTypeDependent()) {
8588 ExprResult Res = PerformCopyInitialization(
8589 InitializedEntity::InitializeResult(LPLoc,
8590 Ty,
8591 false),
8592 SourceLocation(),
8593 Owned(LastExpr));
8594 if (Res.isInvalid())
8595 return ExprError();
8596 if ((LastExpr = Res.takeAs<Expr>())) {
8597 if (!LastLabelStmt)
8598 Compound->setLastStmt(LastExpr);
8599 else
8600 LastLabelStmt->setSubStmt(LastExpr);
8601 StmtExprMayBindToTemp = true;
8602 }
8603 }
8604 }
Chris Lattner944d3062008-07-26 19:51:01 +00008605 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008606
Eli Friedmanba961a92009-03-23 00:24:07 +00008607 // FIXME: Check that expression type is complete/non-abstract; statement
8608 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008609 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8610 if (StmtExprMayBindToTemp)
8611 return MaybeBindToTemporary(ResStmtExpr);
8612 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008613}
Steve Naroff78864672007-08-01 22:05:33 +00008614
John McCalldadc5752010-08-24 06:29:42 +00008615ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008616 TypeSourceInfo *TInfo,
8617 OffsetOfComponent *CompPtr,
8618 unsigned NumComponents,
8619 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008620 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008621 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008622 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008623
Chris Lattnerf17bd422007-08-30 17:45:32 +00008624 // We must have at least one component that refers to the type, and the first
8625 // one is known to be a field designator. Verify that the ArgTy represents
8626 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008627 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008628 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8629 << ArgTy << TypeRange);
8630
8631 // Type must be complete per C99 7.17p3 because a declaring a variable
8632 // with an incomplete type would be ill-formed.
8633 if (!Dependent
8634 && RequireCompleteType(BuiltinLoc, ArgTy,
8635 PDiag(diag::err_offsetof_incomplete_type)
8636 << TypeRange))
8637 return ExprError();
8638
Chris Lattner78502cf2007-08-31 21:49:13 +00008639 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8640 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008641 // FIXME: This diagnostic isn't actually visible because the location is in
8642 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008643 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008644 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8645 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008646
8647 bool DidWarnAboutNonPOD = false;
8648 QualType CurrentType = ArgTy;
8649 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8650 llvm::SmallVector<OffsetOfNode, 4> Comps;
8651 llvm::SmallVector<Expr*, 4> Exprs;
8652 for (unsigned i = 0; i != NumComponents; ++i) {
8653 const OffsetOfComponent &OC = CompPtr[i];
8654 if (OC.isBrackets) {
8655 // Offset of an array sub-field. TODO: Should we allow vector elements?
8656 if (!CurrentType->isDependentType()) {
8657 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8658 if(!AT)
8659 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8660 << CurrentType);
8661 CurrentType = AT->getElementType();
8662 } else
8663 CurrentType = Context.DependentTy;
8664
8665 // The expression must be an integral expression.
8666 // FIXME: An integral constant expression?
8667 Expr *Idx = static_cast<Expr*>(OC.U.E);
8668 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8669 !Idx->getType()->isIntegerType())
8670 return ExprError(Diag(Idx->getLocStart(),
8671 diag::err_typecheck_subscript_not_integer)
8672 << Idx->getSourceRange());
8673
8674 // Record this array index.
8675 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8676 Exprs.push_back(Idx);
8677 continue;
8678 }
8679
8680 // Offset of a field.
8681 if (CurrentType->isDependentType()) {
8682 // We have the offset of a field, but we can't look into the dependent
8683 // type. Just record the identifier of the field.
8684 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8685 CurrentType = Context.DependentTy;
8686 continue;
8687 }
8688
8689 // We need to have a complete type to look into.
8690 if (RequireCompleteType(OC.LocStart, CurrentType,
8691 diag::err_offsetof_incomplete_type))
8692 return ExprError();
8693
8694 // Look for the designated field.
8695 const RecordType *RC = CurrentType->getAs<RecordType>();
8696 if (!RC)
8697 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8698 << CurrentType);
8699 RecordDecl *RD = RC->getDecl();
8700
8701 // C++ [lib.support.types]p5:
8702 // The macro offsetof accepts a restricted set of type arguments in this
8703 // International Standard. type shall be a POD structure or a POD union
8704 // (clause 9).
8705 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8706 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008707 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008708 PDiag(diag::warn_offsetof_non_pod_type)
8709 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8710 << CurrentType))
8711 DidWarnAboutNonPOD = true;
8712 }
8713
8714 // Look for the field.
8715 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8716 LookupQualifiedName(R, RD);
8717 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008718 IndirectFieldDecl *IndirectMemberDecl = 0;
8719 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008720 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008721 MemberDecl = IndirectMemberDecl->getAnonField();
8722 }
8723
Douglas Gregor882211c2010-04-28 22:16:22 +00008724 if (!MemberDecl)
8725 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8726 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8727 OC.LocEnd));
8728
Douglas Gregor10982ea2010-04-28 22:36:06 +00008729 // C99 7.17p3:
8730 // (If the specified member is a bit-field, the behavior is undefined.)
8731 //
8732 // We diagnose this as an error.
8733 if (MemberDecl->getBitWidth()) {
8734 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8735 << MemberDecl->getDeclName()
8736 << SourceRange(BuiltinLoc, RParenLoc);
8737 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8738 return ExprError();
8739 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008740
8741 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008742 if (IndirectMemberDecl)
8743 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008744
Douglas Gregord1702062010-04-29 00:18:15 +00008745 // If the member was found in a base class, introduce OffsetOfNodes for
8746 // the base class indirections.
8747 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8748 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008749 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008750 CXXBasePath &Path = Paths.front();
8751 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8752 B != BEnd; ++B)
8753 Comps.push_back(OffsetOfNode(B->Base));
8754 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008755
Francois Pichet783dd6e2010-11-21 06:08:52 +00008756 if (IndirectMemberDecl) {
8757 for (IndirectFieldDecl::chain_iterator FI =
8758 IndirectMemberDecl->chain_begin(),
8759 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8760 assert(isa<FieldDecl>(*FI));
8761 Comps.push_back(OffsetOfNode(OC.LocStart,
8762 cast<FieldDecl>(*FI), OC.LocEnd));
8763 }
8764 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008765 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008766
Douglas Gregor882211c2010-04-28 22:16:22 +00008767 CurrentType = MemberDecl->getType().getNonReferenceType();
8768 }
8769
8770 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8771 TInfo, Comps.data(), Comps.size(),
8772 Exprs.data(), Exprs.size(), RParenLoc));
8773}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008774
John McCalldadc5752010-08-24 06:29:42 +00008775ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008776 SourceLocation BuiltinLoc,
8777 SourceLocation TypeLoc,
8778 ParsedType argty,
8779 OffsetOfComponent *CompPtr,
8780 unsigned NumComponents,
8781 SourceLocation RPLoc) {
8782
Douglas Gregor882211c2010-04-28 22:16:22 +00008783 TypeSourceInfo *ArgTInfo;
8784 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8785 if (ArgTy.isNull())
8786 return ExprError();
8787
Eli Friedman06dcfd92010-08-05 10:15:45 +00008788 if (!ArgTInfo)
8789 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8790
8791 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8792 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008793}
8794
8795
John McCalldadc5752010-08-24 06:29:42 +00008796ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008797 Expr *CondExpr,
8798 Expr *LHSExpr, Expr *RHSExpr,
8799 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008800 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8801
John McCall7decc9e2010-11-18 06:31:45 +00008802 ExprValueKind VK = VK_RValue;
8803 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008804 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008805 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008806 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008807 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008808 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008809 } else {
8810 // The conditional expression is required to be a constant expression.
8811 llvm::APSInt condEval(32);
8812 SourceLocation ExpLoc;
8813 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008814 return ExprError(Diag(ExpLoc,
8815 diag::err_typecheck_choose_expr_requires_constant)
8816 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008817
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008818 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008819 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8820
8821 resType = ActiveExpr->getType();
8822 ValueDependent = ActiveExpr->isValueDependent();
8823 VK = ActiveExpr->getValueKind();
8824 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008825 }
8826
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008827 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008828 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008829 resType->isDependentType(),
8830 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008831}
8832
Steve Naroffc540d662008-09-03 18:15:37 +00008833//===----------------------------------------------------------------------===//
8834// Clang Extensions.
8835//===----------------------------------------------------------------------===//
8836
8837/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008838void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008839 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8840 PushBlockScope(BlockScope, Block);
8841 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008842 if (BlockScope)
8843 PushDeclContext(BlockScope, Block);
8844 else
8845 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008846}
8847
Mike Stump82f071f2009-02-04 22:31:32 +00008848void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008849 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008850 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008851 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008852
John McCall8cb7bdf2010-06-04 23:28:52 +00008853 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008854 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008855
John McCall3882ace2011-01-05 12:14:39 +00008856 // GetTypeForDeclarator always produces a function type for a block
8857 // literal signature. Furthermore, it is always a FunctionProtoType
8858 // unless the function was written with a typedef.
8859 assert(T->isFunctionType() &&
8860 "GetTypeForDeclarator made a non-function block signature");
8861
8862 // Look for an explicit signature in that function type.
8863 FunctionProtoTypeLoc ExplicitSignature;
8864
8865 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8866 if (isa<FunctionProtoTypeLoc>(tmp)) {
8867 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8868
8869 // Check whether that explicit signature was synthesized by
8870 // GetTypeForDeclarator. If so, don't save that as part of the
8871 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008872 if (ExplicitSignature.getLocalRangeBegin() ==
8873 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008874 // This would be much cheaper if we stored TypeLocs instead of
8875 // TypeSourceInfos.
8876 TypeLoc Result = ExplicitSignature.getResultLoc();
8877 unsigned Size = Result.getFullDataSize();
8878 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8879 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8880
8881 ExplicitSignature = FunctionProtoTypeLoc();
8882 }
John McCalla3ccba02010-06-04 11:21:44 +00008883 }
Mike Stump11289f42009-09-09 15:08:12 +00008884
John McCall3882ace2011-01-05 12:14:39 +00008885 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8886 CurBlock->FunctionType = T;
8887
8888 const FunctionType *Fn = T->getAs<FunctionType>();
8889 QualType RetTy = Fn->getResultType();
8890 bool isVariadic =
8891 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8892
John McCall8e346702010-06-04 19:02:56 +00008893 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008894
John McCalla3ccba02010-06-04 11:21:44 +00008895 // Don't allow returning a objc interface by value.
8896 if (RetTy->isObjCObjectType()) {
8897 Diag(ParamInfo.getSourceRange().getBegin(),
8898 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8899 return;
8900 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008901
John McCalla3ccba02010-06-04 11:21:44 +00008902 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008903 // return type. TODO: what should we do with declarators like:
8904 // ^ * { ... }
8905 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008906 if (RetTy != Context.DependentTy)
8907 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008908
John McCalla3ccba02010-06-04 11:21:44 +00008909 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00008910 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008911 if (ExplicitSignature) {
8912 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8913 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008914 if (Param->getIdentifier() == 0 &&
8915 !Param->isImplicit() &&
8916 !Param->isInvalidDecl() &&
8917 !getLangOptions().CPlusPlus)
8918 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008919 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008920 }
John McCalla3ccba02010-06-04 11:21:44 +00008921
8922 // Fake up parameter variables if we have a typedef, like
8923 // ^ fntype { ... }
8924 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8925 for (FunctionProtoType::arg_type_iterator
8926 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8927 ParmVarDecl *Param =
8928 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8929 ParamInfo.getSourceRange().getBegin(),
8930 *I);
John McCall8e346702010-06-04 19:02:56 +00008931 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008932 }
Steve Naroffc540d662008-09-03 18:15:37 +00008933 }
John McCalla3ccba02010-06-04 11:21:44 +00008934
John McCall8e346702010-06-04 19:02:56 +00008935 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008936 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00008937 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00008938 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8939 CurBlock->TheDecl->param_end(),
8940 /*CheckParameterNames=*/false);
8941 }
8942
John McCalla3ccba02010-06-04 11:21:44 +00008943 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008944 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008945
John McCall8e346702010-06-04 19:02:56 +00008946 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008947 Diag(ParamInfo.getAttributes()->getLoc(),
8948 diag::warn_attribute_sentinel_not_variadic) << 1;
8949 // FIXME: remove the attribute.
8950 }
8951
8952 // Put the parameter variables in scope. We can bail out immediately
8953 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008954 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008955 return;
8956
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008957 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008958 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8959 (*AI)->setOwningFunction(CurBlock->TheDecl);
8960
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008961 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008962 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008963 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008964
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008965 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008966 }
John McCallf7b2fb52010-01-22 00:28:27 +00008967 }
Steve Naroffc540d662008-09-03 18:15:37 +00008968}
8969
8970/// ActOnBlockError - If there is an error parsing a block, this callback
8971/// is invoked to pop the information about the block from the action impl.
8972void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008973 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008974 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008975 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008976}
8977
8978/// ActOnBlockStmtExpr - This is called when the body of a block statement
8979/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008980ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008981 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008982 // If blocks are disabled, emit an error.
8983 if (!LangOpts.Blocks)
8984 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008985
Douglas Gregor9a28e842010-03-01 23:15:13 +00008986 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008987
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008988 PopDeclContext();
8989
Steve Naroffc540d662008-09-03 18:15:37 +00008990 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008991 if (!BSI->ReturnType.isNull())
8992 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008993
Mike Stump3bf1ab42009-07-28 22:04:01 +00008994 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008995 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008996
John McCallc63de662011-02-02 13:00:07 +00008997 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00008998 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8999 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00009000
John McCall8e346702010-06-04 19:02:56 +00009001 // If the user wrote a function type in some form, try to use that.
9002 if (!BSI->FunctionType.isNull()) {
9003 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9004
9005 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9006 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9007
9008 // Turn protoless block types into nullary block types.
9009 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009010 FunctionProtoType::ExtProtoInfo EPI;
9011 EPI.ExtInfo = Ext;
9012 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009013
9014 // Otherwise, if we don't need to change anything about the function type,
9015 // preserve its sugar structure.
9016 } else if (FTy->getResultType() == RetTy &&
9017 (!NoReturn || FTy->getNoReturnAttr())) {
9018 BlockTy = BSI->FunctionType;
9019
9020 // Otherwise, make the minimal modifications to the function type.
9021 } else {
9022 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00009023 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9024 EPI.TypeQuals = 0; // FIXME: silently?
9025 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00009026 BlockTy = Context.getFunctionType(RetTy,
9027 FPT->arg_type_begin(),
9028 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00009029 EPI);
John McCall8e346702010-06-04 19:02:56 +00009030 }
9031
9032 // If we don't have a function type, just build one from nothing.
9033 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00009034 FunctionProtoType::ExtProtoInfo EPI;
9035 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, 0, CC_Default);
9036 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009037 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009038
John McCall8e346702010-06-04 19:02:56 +00009039 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9040 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00009041 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009042
Chris Lattner45542ea2009-04-19 05:28:12 +00009043 // If needed, diagnose invalid gotos and switches in the block.
John McCallaab3e412010-08-25 08:40:02 +00009044 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00009045 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00009046
Chris Lattner60f84492011-02-17 23:58:47 +00009047 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009048
John McCallc63de662011-02-02 13:00:07 +00009049 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCall1d570a72010-08-25 05:56:39 +00009050
Ted Kremenek1767a272011-02-23 01:51:48 +00009051 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9052 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009053 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00009054}
9055
John McCalldadc5752010-08-24 06:29:42 +00009056ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00009057 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009058 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00009059 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009060 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00009061 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00009062}
9063
John McCalldadc5752010-08-24 06:29:42 +00009064ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00009065 Expr *E, TypeSourceInfo *TInfo,
9066 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00009067 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00009068
Eli Friedman121ba0c2008-08-09 23:32:40 +00009069 // Get the va_list type
9070 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00009071 if (VaListType->isArrayType()) {
9072 // Deal with implicit array decay; for example, on x86-64,
9073 // va_list is an array, but it's supposed to decay to
9074 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00009075 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00009076 // Make sure the input expression also decays appropriately.
9077 UsualUnaryConversions(E);
9078 } else {
9079 // Otherwise, the va_list argument must be an l-value because
9080 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00009081 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00009082 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00009083 return ExprError();
9084 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00009085
Douglas Gregorad3150c2009-05-19 23:10:31 +00009086 if (!E->isTypeDependent() &&
9087 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009088 return ExprError(Diag(E->getLocStart(),
9089 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00009090 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00009091 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009092
Eli Friedmanba961a92009-03-23 00:24:07 +00009093 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009094 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00009095
Abramo Bagnara27db2392010-08-10 10:06:15 +00009096 QualType T = TInfo->getType().getNonLValueExprType(Context);
9097 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009098}
9099
John McCalldadc5752010-08-24 06:29:42 +00009100ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009101 // The type of __null will be int or long, depending on the size of
9102 // pointers on the target.
9103 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009104 unsigned pw = Context.Target.getPointerWidth(0);
9105 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009106 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009107 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009108 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009109 else if (pw == Context.Target.getLongLongWidth())
9110 Ty = Context.LongLongTy;
9111 else {
9112 assert(!"I don't know size of pointer!");
9113 Ty = Context.IntTy;
9114 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009115
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009116 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009117}
9118
Alexis Huntc46382e2010-04-28 23:02:27 +00009119static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009120 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00009121 if (!SemaRef.getLangOptions().ObjC1)
9122 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009123
Anders Carlssonace5d072009-11-10 04:46:30 +00009124 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9125 if (!PT)
9126 return;
9127
9128 // Check if the destination is of type 'id'.
9129 if (!PT->isObjCIdType()) {
9130 // Check if the destination is the 'NSString' interface.
9131 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9132 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9133 return;
9134 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009135
Anders Carlssonace5d072009-11-10 04:46:30 +00009136 // Strip off any parens and casts.
9137 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
9138 if (!SL || SL->isWide())
9139 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009140
Douglas Gregora771f462010-03-31 17:46:05 +00009141 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009142}
9143
Chris Lattner9bad62c2008-01-04 18:04:52 +00009144bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9145 SourceLocation Loc,
9146 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009147 Expr *SrcExpr, AssignmentAction Action,
9148 bool *Complained) {
9149 if (Complained)
9150 *Complained = false;
9151
Chris Lattner9bad62c2008-01-04 18:04:52 +00009152 // Decode the result (notice that AST's are still created for extensions).
9153 bool isInvalid = false;
9154 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00009155 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009156
Chris Lattner9bad62c2008-01-04 18:04:52 +00009157 switch (ConvTy) {
9158 default: assert(0 && "Unknown conversion type");
9159 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009160 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009161 DiagKind = diag::ext_typecheck_convert_pointer_int;
9162 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009163 case IntToPointer:
9164 DiagKind = diag::ext_typecheck_convert_int_pointer;
9165 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009166 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009167 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009168 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9169 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009170 case IncompatiblePointerSign:
9171 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9172 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009173 case FunctionVoidPointer:
9174 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9175 break;
John McCall4fff8f62011-02-01 00:10:29 +00009176 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009177 // Perform array-to-pointer decay if necessary.
9178 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9179
John McCall4fff8f62011-02-01 00:10:29 +00009180 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9181 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9182 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9183 DiagKind = diag::err_typecheck_incompatible_address_space;
9184 break;
9185 }
9186
9187 llvm_unreachable("unknown error case for discarding qualifiers!");
9188 // fallthrough
9189 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009190 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009191 // If the qualifiers lost were because we were applying the
9192 // (deprecated) C++ conversion from a string literal to a char*
9193 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9194 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009195 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009196 // bit of refactoring (so that the second argument is an
9197 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009198 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009199 // C++ semantics.
9200 if (getLangOptions().CPlusPlus &&
9201 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9202 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009203 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9204 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009205 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009206 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009207 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009208 case IntToBlockPointer:
9209 DiagKind = diag::err_int_to_block_pointer;
9210 break;
9211 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009212 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009213 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009214 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009215 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009216 // it can give a more specific diagnostic.
9217 DiagKind = diag::warn_incompatible_qualified_id;
9218 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009219 case IncompatibleVectors:
9220 DiagKind = diag::warn_incompatible_vectors;
9221 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009222 case Incompatible:
9223 DiagKind = diag::err_typecheck_convert_incompatible;
9224 isInvalid = true;
9225 break;
9226 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009227
Douglas Gregorc68e1402010-04-09 00:35:39 +00009228 QualType FirstType, SecondType;
9229 switch (Action) {
9230 case AA_Assigning:
9231 case AA_Initializing:
9232 // The destination type comes first.
9233 FirstType = DstType;
9234 SecondType = SrcType;
9235 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009236
Douglas Gregorc68e1402010-04-09 00:35:39 +00009237 case AA_Returning:
9238 case AA_Passing:
9239 case AA_Converting:
9240 case AA_Sending:
9241 case AA_Casting:
9242 // The source type comes first.
9243 FirstType = SrcType;
9244 SecondType = DstType;
9245 break;
9246 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009247
Douglas Gregorc68e1402010-04-09 00:35:39 +00009248 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00009249 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009250 if (Complained)
9251 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009252 return isInvalid;
9253}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009254
Chris Lattnerc71d08b2009-04-25 21:59:05 +00009255bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009256 llvm::APSInt ICEResult;
9257 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9258 if (Result)
9259 *Result = ICEResult;
9260 return false;
9261 }
9262
Anders Carlssone54e8a12008-11-30 19:50:32 +00009263 Expr::EvalResult EvalResult;
9264
Mike Stump4e1f26a2009-02-19 03:04:26 +00009265 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00009266 EvalResult.HasSideEffects) {
9267 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9268
9269 if (EvalResult.Diag) {
9270 // We only show the note if it's not the usual "invalid subexpression"
9271 // or if it's actually in a subexpression.
9272 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9273 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9274 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9275 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009276
Anders Carlssone54e8a12008-11-30 19:50:32 +00009277 return true;
9278 }
9279
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009280 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9281 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009282
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009283 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009284 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9285 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009286 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009287
Anders Carlssone54e8a12008-11-30 19:50:32 +00009288 if (Result)
9289 *Result = EvalResult.Val.getInt();
9290 return false;
9291}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009292
Douglas Gregorff790f12009-11-26 00:44:06 +00009293void
Mike Stump11289f42009-09-09 15:08:12 +00009294Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009295 ExprEvalContexts.push_back(
9296 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009297}
9298
Mike Stump11289f42009-09-09 15:08:12 +00009299void
Douglas Gregorff790f12009-11-26 00:44:06 +00009300Sema::PopExpressionEvaluationContext() {
9301 // Pop the current expression evaluation context off the stack.
9302 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9303 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009304
Douglas Gregorfab31f42009-12-12 07:57:52 +00009305 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9306 if (Rec.PotentiallyReferenced) {
9307 // Mark any remaining declarations in the current position of the stack
9308 // as "referenced". If they were not meant to be referenced, semantic
9309 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009310 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00009311 I = Rec.PotentiallyReferenced->begin(),
9312 IEnd = Rec.PotentiallyReferenced->end();
9313 I != IEnd; ++I)
9314 MarkDeclarationReferenced(I->first, I->second);
9315 }
9316
9317 if (Rec.PotentiallyDiagnosed) {
9318 // Emit any pending diagnostics.
9319 for (PotentiallyEmittedDiagnostics::iterator
9320 I = Rec.PotentiallyDiagnosed->begin(),
9321 IEnd = Rec.PotentiallyDiagnosed->end();
9322 I != IEnd; ++I)
9323 Diag(I->first, I->second);
9324 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009325 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009326
9327 // When are coming out of an unevaluated context, clear out any
9328 // temporaries that we may have created as part of the evaluation of
9329 // the expression in that context: they aren't relevant because they
9330 // will never be constructed.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009331 if (Rec.Context == Unevaluated &&
Douglas Gregorff790f12009-11-26 00:44:06 +00009332 ExprTemporaries.size() > Rec.NumTemporaries)
9333 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9334 ExprTemporaries.end());
9335
9336 // Destroy the popped expression evaluation record.
9337 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009338}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009339
9340/// \brief Note that the given declaration was referenced in the source code.
9341///
9342/// This routine should be invoke whenever a given declaration is referenced
9343/// in the source code, and where that reference occurred. If this declaration
9344/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9345/// C99 6.9p3), then the declaration will be marked as used.
9346///
9347/// \param Loc the location where the declaration was referenced.
9348///
9349/// \param D the declaration that has been referenced by the source code.
9350void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9351 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009352
Douglas Gregorebada0772010-06-17 23:14:26 +00009353 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009354 return;
Mike Stump11289f42009-09-09 15:08:12 +00009355
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00009356 // Mark a parameter or variable declaration "used", regardless of whether we're in a
9357 // template or not. The reason for this is that unevaluated expressions
9358 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9359 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009360 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009361 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009362 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009363 return;
9364 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009365
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009366 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9367 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009368
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009369 // Do not mark anything as "used" within a dependent context; wait for
9370 // an instantiation.
9371 if (CurContext->isDependentContext())
9372 return;
Mike Stump11289f42009-09-09 15:08:12 +00009373
Douglas Gregorff790f12009-11-26 00:44:06 +00009374 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009375 case Unevaluated:
9376 // We are in an expression that is not potentially evaluated; do nothing.
9377 return;
Mike Stump11289f42009-09-09 15:08:12 +00009378
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009379 case PotentiallyEvaluated:
9380 // We are in a potentially-evaluated expression, so this declaration is
9381 // "used"; handle this below.
9382 break;
Mike Stump11289f42009-09-09 15:08:12 +00009383
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009384 case PotentiallyPotentiallyEvaluated:
9385 // We are in an expression that may be potentially evaluated; queue this
9386 // declaration reference until we know whether the expression is
9387 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009388 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009389 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009390
9391 case PotentiallyEvaluatedIfUsed:
9392 // Referenced declarations will only be used if the construct in the
9393 // containing expression is used.
9394 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009395 }
Mike Stump11289f42009-09-09 15:08:12 +00009396
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009397 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009398 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009399 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00009400 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruthc9262402010-08-23 07:55:51 +00009401 if (Constructor->getParent()->hasTrivialConstructor())
9402 return;
9403 if (!Constructor->isUsed(false))
9404 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00009405 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00009406 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009407 if (!Constructor->isUsed(false))
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009408 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
9409 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009410
Douglas Gregor88d292c2010-05-13 16:44:06 +00009411 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009412 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009413 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009414 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009415 if (Destructor->isVirtual())
9416 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009417 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9418 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
9419 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009420 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00009421 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009422 } else if (MethodDecl->isVirtual())
9423 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009424 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009425 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009426 // Recursive functions should be marked when used from another function.
9427 if (CurContext == Function) return;
9428
Mike Stump11289f42009-09-09 15:08:12 +00009429 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009430 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009431 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009432 bool AlreadyInstantiated = false;
9433 if (FunctionTemplateSpecializationInfo *SpecInfo
9434 = Function->getTemplateSpecializationInfo()) {
9435 if (SpecInfo->getPointOfInstantiation().isInvalid())
9436 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009437 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009438 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009439 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009440 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009441 = Function->getMemberSpecializationInfo()) {
9442 if (MSInfo->getPointOfInstantiation().isInvalid())
9443 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009444 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009445 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009446 AlreadyInstantiated = true;
9447 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009448
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009449 if (!AlreadyInstantiated) {
9450 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9451 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9452 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9453 Loc));
9454 else
Chandler Carruth54080172010-08-25 08:44:16 +00009455 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009456 }
John McCall83779672011-02-19 02:53:41 +00009457 } else {
9458 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009459 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9460 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009461 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009462 MarkDeclarationReferenced(Loc, *i);
9463 }
John McCall83779672011-02-19 02:53:41 +00009464 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009465
John McCall83779672011-02-19 02:53:41 +00009466 // Keep track of used but undefined functions.
9467 if (!Function->isPure() && !Function->hasBody() &&
9468 Function->getLinkage() != ExternalLinkage) {
9469 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9470 if (old.isInvalid()) old = Loc;
9471 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009472
John McCall83779672011-02-19 02:53:41 +00009473 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009474 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009475 }
Mike Stump11289f42009-09-09 15:08:12 +00009476
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009477 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009478 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009479 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009480 Var->getInstantiatedFromStaticDataMember()) {
9481 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9482 assert(MSInfo && "Missing member specialization information?");
9483 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9484 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9485 MSInfo->setPointOfInstantiation(Loc);
Chandler Carruth54080172010-08-25 08:44:16 +00009486 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009487 }
9488 }
Mike Stump11289f42009-09-09 15:08:12 +00009489
John McCall15dd4042011-02-21 19:25:48 +00009490 // Keep track of used but undefined variables. We make a hole in
9491 // the warning for static const data members with in-line
9492 // initializers.
John McCall83779672011-02-19 02:53:41 +00009493 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009494 && Var->getLinkage() != ExternalLinkage
9495 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009496 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9497 if (old.isInvalid()) old = Loc;
9498 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009499
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009500 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009501 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009502 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009503}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009504
Douglas Gregor5597ab42010-05-07 23:12:07 +00009505namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009506 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009507 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009508 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009509 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9510 Sema &S;
9511 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009512
Douglas Gregor5597ab42010-05-07 23:12:07 +00009513 public:
9514 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009515
Douglas Gregor5597ab42010-05-07 23:12:07 +00009516 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009517
9518 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9519 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009520 };
9521}
9522
Chandler Carruthaf80f662010-06-09 08:17:30 +00009523bool MarkReferencedDecls::TraverseTemplateArgument(
9524 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009525 if (Arg.getKind() == TemplateArgument::Declaration) {
9526 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9527 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009528
9529 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009530}
9531
Chandler Carruthaf80f662010-06-09 08:17:30 +00009532bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009533 if (ClassTemplateSpecializationDecl *Spec
9534 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9535 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009536 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009537 }
9538
Chandler Carruthc65667c2010-06-10 10:31:57 +00009539 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009540}
9541
9542void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9543 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009544 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009545}
9546
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009547namespace {
9548 /// \brief Helper class that marks all of the declarations referenced by
9549 /// potentially-evaluated subexpressions as "referenced".
9550 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9551 Sema &S;
9552
9553 public:
9554 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9555
9556 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9557
9558 void VisitDeclRefExpr(DeclRefExpr *E) {
9559 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9560 }
9561
9562 void VisitMemberExpr(MemberExpr *E) {
9563 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009564 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009565 }
9566
9567 void VisitCXXNewExpr(CXXNewExpr *E) {
9568 if (E->getConstructor())
9569 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9570 if (E->getOperatorNew())
9571 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9572 if (E->getOperatorDelete())
9573 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009574 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009575 }
9576
9577 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9578 if (E->getOperatorDelete())
9579 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009580 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9581 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9582 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9583 S.MarkDeclarationReferenced(E->getLocStart(),
9584 S.LookupDestructor(Record));
9585 }
9586
Douglas Gregor32b3de52010-09-11 23:32:50 +00009587 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009588 }
9589
9590 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9591 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009592 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009593 }
9594
9595 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9596 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9597 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009598
9599 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9600 Visit(E->getExpr());
9601 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009602 };
9603}
9604
9605/// \brief Mark any declarations that appear within this expression or any
9606/// potentially-evaluated subexpressions as "referenced".
9607void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9608 EvaluatedExprMarker(*this).Visit(E);
9609}
9610
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009611/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9612/// of the program being compiled.
9613///
9614/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009615/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009616/// possibility that the code will actually be executable. Code in sizeof()
9617/// expressions, code used only during overload resolution, etc., are not
9618/// potentially evaluated. This routine will suppress such diagnostics or,
9619/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009620/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009621/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009622///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009623/// This routine should be used for all diagnostics that describe the run-time
9624/// behavior of a program, such as passing a non-POD value through an ellipsis.
9625/// Failure to do so will likely result in spurious diagnostics or failures
9626/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek55ae3192011-02-23 01:51:43 +00009627bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009628 const PartialDiagnostic &PD) {
9629 switch (ExprEvalContexts.back().Context ) {
9630 case Unevaluated:
9631 // The argument will never be evaluated, so don't complain.
9632 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009633
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009634 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009635 case PotentiallyEvaluatedIfUsed:
Ted Kremenek3427fac2011-02-23 01:52:04 +00009636 if (stmt && getCurFunctionOrMethodDecl()) {
9637 FunctionScopes.back()->PossiblyUnreachableDiags.
9638 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9639 }
9640 else
9641 Diag(Loc, PD);
9642
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009643 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009644
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009645 case PotentiallyPotentiallyEvaluated:
9646 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9647 break;
9648 }
9649
9650 return false;
9651}
9652
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009653bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9654 CallExpr *CE, FunctionDecl *FD) {
9655 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9656 return false;
9657
9658 PartialDiagnostic Note =
9659 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9660 << FD->getDeclName() : PDiag();
9661 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009662
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009663 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009664 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009665 PDiag(diag::err_call_function_incomplete_return)
9666 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009667 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009668 << CE->getSourceRange(),
9669 std::make_pair(NoteLoc, Note)))
9670 return true;
9671
9672 return false;
9673}
9674
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009675// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009676// will prevent this condition from triggering, which is what we want.
9677void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9678 SourceLocation Loc;
9679
John McCall0506e4a2009-11-11 02:41:58 +00009680 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009681 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009682
John McCalld5707ab2009-10-12 21:59:07 +00009683 if (isa<BinaryOperator>(E)) {
9684 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009685 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009686 return;
9687
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009688 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9689
John McCallb0e419e2009-11-12 00:06:05 +00009690 // Greylist some idioms by putting them into a warning subcategory.
9691 if (ObjCMessageExpr *ME
9692 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9693 Selector Sel = ME->getSelector();
9694
John McCallb0e419e2009-11-12 00:06:05 +00009695 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009696 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +00009697 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9698
9699 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009700 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +00009701 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9702 }
John McCall0506e4a2009-11-11 02:41:58 +00009703
John McCalld5707ab2009-10-12 21:59:07 +00009704 Loc = Op->getOperatorLoc();
9705 } else if (isa<CXXOperatorCallExpr>(E)) {
9706 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009707 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009708 return;
9709
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009710 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009711 Loc = Op->getOperatorLoc();
9712 } else {
9713 // Not an assignment.
9714 return;
9715 }
9716
John McCalld5707ab2009-10-12 21:59:07 +00009717 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00009718 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009719
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009720 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009721
9722 if (IsOrAssign)
9723 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9724 << FixItHint::CreateReplacement(Loc, "!=");
9725 else
9726 Diag(Loc, diag::note_condition_assign_to_comparison)
9727 << FixItHint::CreateReplacement(Loc, "==");
9728
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009729 Diag(Loc, diag::note_condition_assign_silence)
9730 << FixItHint::CreateInsertion(Open, "(")
9731 << FixItHint::CreateInsertion(Close, ")");
John McCalld5707ab2009-10-12 21:59:07 +00009732}
9733
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009734/// \brief Redundant parentheses over an equality comparison can indicate
9735/// that the user intended an assignment used as condition.
9736void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009737 // Don't warn if the parens came from a macro.
9738 SourceLocation parenLoc = parenE->getLocStart();
9739 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9740 return;
9741
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009742 Expr *E = parenE->IgnoreParens();
9743
9744 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009745 if (opE->getOpcode() == BO_EQ &&
9746 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9747 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009748 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009749
Ted Kremenekae022092011-02-02 02:20:30 +00009750 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
9751 Diag(Loc, diag::note_equality_comparison_to_assign)
9752 << FixItHint::CreateReplacement(Loc, "=");
9753 Diag(Loc, diag::note_equality_comparison_silence)
9754 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9755 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009756 }
9757}
9758
John McCalld5707ab2009-10-12 21:59:07 +00009759bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
9760 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009761 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9762 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009763
9764 if (!E->isTypeDependent()) {
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009765 if (E->isBoundMemberFunction(Context))
9766 return Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9767 << E->getSourceRange();
9768
John McCall34376a62010-12-04 03:47:34 +00009769 if (getLangOptions().CPlusPlus)
9770 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9771
9772 DefaultFunctionArrayLvalueConversion(E);
John McCall29cb2fd2010-12-04 06:09:13 +00009773
9774 QualType T = E->getType();
John McCall34376a62010-12-04 03:47:34 +00009775 if (!T->isScalarType()) // C99 6.8.4.1p1
9776 return Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9777 << T << E->getSourceRange();
John McCalld5707ab2009-10-12 21:59:07 +00009778 }
9779
9780 return false;
9781}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009782
John McCalldadc5752010-08-24 06:29:42 +00009783ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9784 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00009785 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009786 return ExprError();
9787
Douglas Gregorb412e172010-07-25 18:17:45 +00009788 if (CheckBooleanCondition(Sub, Loc))
Douglas Gregore60e41a2010-05-06 17:25:47 +00009789 return ExprError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00009790
9791 return Owned(Sub);
9792}
John McCall36e7fe32010-10-12 00:20:44 +00009793
9794/// Check for operands with placeholder types and complain if found.
9795/// Returns true if there was an error and no recovery was possible.
9796ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) {
9797 const BuiltinType *BT = E->getType()->getAs<BuiltinType>();
9798 if (!BT || !BT->isPlaceholderType()) return Owned(E);
9799
9800 // If this is overload, check for a single overload.
Richard Smith30482bc2011-02-20 03:19:35 +00009801 assert(BT->getKind() == BuiltinType::Overload);
Douglas Gregor89f3cd52011-03-16 19:16:25 +00009802 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
9803 E->getSourceRange(),
9804 QualType(),
9805 diag::err_ovl_unresolvable);
John McCall36e7fe32010-10-12 00:20:44 +00009806}